lineTo
2023年08月11日
一、认识
ctx.lineTo()
是 Canvas 2D API
使用直线连接子路径的终点到 x,y
坐标的方法(并不会真正地绘制)。
二、语法
void ctx.lineTo(x, y);
-
x
: 直线终点的x
轴坐标。 -
y
: 直线终点的y
轴坐标。
三、场景
3.1 直线
直线流程: 通过 beginPath()
开始路径, 从 moveTo(startX,startY)
处开始, 从 lineTo(endX,endY)
处结束, 通过 strokeStyle
来改变线条颜色, 使用 stroke()
填充。
<canvas id="canvas"></canvas>
<script>
const canvas = document.querySelector("#canvas");
canvas.width = 500;
canvas.height = 500;
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.strokeStyle = 'blue';
ctx.moveTo(0,0);
ctx.lineTo(200,0);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle = 'red';
ctx.moveTo(200,0);
ctx.lineTo(200,200);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle = 'green';
ctx.moveTo(200,200);
ctx.lineTo(0,200);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle = 'brown';
ctx.moveTo(0,200);
ctx.lineTo(0,0);
ctx.stroke();
</script>