示例
context.lineTo(endX, endY)
从当前笔位置绘制一条线段以协调[endX,endY]
html>
body{ background-color:white; }
#canvas{border:1px solid red; }
window.οnlοad=(function(){
// 获取对canvas元素及其上下文的引用
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// 论点
var startX=25;
var startY=20;
var endX=125;
var endY=20;
// Draw a single line segment drawn using "moveTo" and "lineTo" commands
ctx.beginPath();
ctx.moveTo(startX,startY);
ctx.lineTo(endX,endY);
ctx.stroke();
}); // 结束window.onload
您可以组合多个.lineTo命令以绘制多段线。例如,您可以装配3个线段以形成三角形。
html>
body{ background-color:white; }
#canvas{border:1px solid red; }
window.οnlοad=(function(){
// 获取对canvas元素及其上下文的引用
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// 论点
var topVertexX=50;
var topVertexY=20;
var rightVertexX=75;
var rightVertexY=70;
var leftVertexX=25;
var leftVertexY=70;
// 一组线段绘制为使用
// "moveTo" 和多个 "lineTo" commands
ctx.beginPath();
ctx.moveTo(topVertexX,topVertexY);
ctx.lineTo(rightVertexX,rightVertexY);
ctx.lineTo(leftVertexX,leftVertexY);
ctx.lineTo(topVertexX,topVertexY);
ctx.stroke();
}); // 结束window.onload