canvas绘制多边形

发布时间 2023-04-18 12:00:30作者: kaookiee
1、获取ctx,id为canvasId的canvas标签
document.getElementById("canvasId")。getXO你text("2d");

2、确定尺寸

3、添加点击画布的监听

ctx.addEventListener("click",(e)=>that.addLis(e), false);//单击添加多边形顶点
addEventListener("dblclick",(e)=>that.stopDraw(e), false);//双击暂定绘制

4、通过单击画布获取到[ {x:'',y:''},{},{} ]的数组

ctx.strokeStyle = "#f00";
ctx.lineWidth = 1;
ctx.fillStyle = "#0000ff66";
ctx.clearRect(0,0,that.canvas.width,that.canvas.height);
ctx.beginPath();
if (that.array[0]) {
that.canvas_ctx.moveTo(that.array[0].x,that.array[0].y);
}
for (let i = 1; i < that.array.length; i++) {
that.canvas_ctx.lineTo(that.array[i].x,that.array[i].y);
}
that.canvas_ctx.closePath();
that.canvas_ctx.stroke();
ctx.fill();