beginPath
2023年08月11日
一、认识
ctx.beginPath()
是 Canvas 2D API
通过清空子路径列表开始一个新路径的方法。当你想创建一个新的路径时,调用此方法。
二、语法
ctx.beginPath();
三、场景
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>