您好,我正在制作一个多边形并想将其填满。但无论我尝试做什么,我似乎都无法让它发挥作用。
如果有人能指出正确的方向,我将不胜感激。
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>
最佳答案
您只需在 beginPath()
之后为每个路径使用一次 moveTo()
,然后再使用 lineTo()
。在 for
循环中完成所有 lineTo()
之后,您就可以执行 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();
希望对您有所帮助!
关于javascript - HTML Canvas : Fill() not working with no errors in console,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54659432/