简体   繁体   English

HTML Canvas:Fill() 无法在控制台中正常工作且没有错误

[英]HTML Canvas: Fill() not working with no errors in console

Hello I am making a polygon and want to fill it up.你好,我正在制作一个多边形,想把它填满。 But whatever I try to do I can't seem to make it work.但无论我尝试做什么,我似乎都无法让它发挥作用。

If anyone can point me in the right direction I appreciate it.如果有人能指出我正确的方向,我将不胜感激。

https://jsfiddle.net/ygesj1do/4/ 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>

You only need to use moveTo() once for each path after beginPath() then just use lineTo() after that.您只需要在beginPath()之后对每个路径使用moveTo()一次,然后在此之后使用lineTo() Once you do all of the lineTo() 's in the for loop, then you can do the ctx.fill() to get it to work.for循环中完成所有lineTo()之后,您就可以执行ctx.fill()以使其工作。

Here's the updated part of the code:这是代码的更新部分:


/* 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();


Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM