您好,我正在制作一个多边形并想填充它。但是无论我怎么做,我似乎都无法使其正常工作。
如果有人能指出正确的方向,我将不胜感激。
https://jsfiddle.net/ygesj1do/4/
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
op = {
"pts": [{
"x": 40,
"y": 13.5
}, {
"x": 60,
"y": 27.75
}, {
"x": 60,
"y": 56.25
}, {
"x": 40,
"y": 70.5
}, {
"x": 20,
"y": 56.25
}, {
"x": 20,
"y": 27.75
}],
"color": "#00F",
"fillcolor": "#FF0000",
"lineWidth": 1
};
ctx.save();
ctx.strokeStyle = op.color;
ctx.fillStyle = op.fillcolor;
ctx.lineWidth = op.lineWidth;
ctx.beginPath();
for (i = 1; i <= op.pts.length; i++) {
if (i == op.pts.length) {
ctx.moveTo(op.pts[i - 1].x, op.pts[i - 1].y);
ctx.lineTo(op.pts[0].x, op.pts[0].y);
} else {
ctx.moveTo(op.pts[i - 1].x, op.pts[i - 1].y);
ctx.lineTo(op.pts[i].x, op.pts[i].y);
}
}
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore();
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
答案 0 :(得分:1)
对于moveTo()
之后的每个路径,您只需使用一次beginPath()
,然后在此之后仅使用lineTo()
。一旦完成了lineTo()
循环中的所有for
,您就可以执行ctx.fill()
使其生效。
这是代码的更新部分:
/* set moveTo() once before for loop */
ctx.moveTo(op.pts[0].x,op.pts[0].y);
/*then in the for loop just use lineTo(), using lineTo() will keep track of the last endpoint on the current path so you don't need to use moveTo() unless you are starting a new path.*/
for (i=1;i<=op.pts.length;i++) {
if (i==op.pts.length) {
ctx.lineTo(op.pts[0].x,op.pts[0].y);
} else {
ctx.lineTo(op.pts[i].x,op.pts[i].y);
}
}
/* now the following will work */
ctx.closePath();
ctx.fill();
希望这会有所帮助!