如何使用 ctx html 在 Line 中填充颜色?

How to fill colour in Line using ctx html?

请检查这个link https://www.jovianarchive.com/content/charts/628003987200000000_.png。我正在创建相同的图表,但所有的线条和几何形状都是动态的。在线有黑色和红色组合的颜色(看起来像条纹)想要相同的。 我的代码

ctx.fillStyle = 'blue';
ctx.fill();
ctx.strokeStyle = 'blue';
ctx.stroke();

您需要在调用描边方法之前创建路径:

 canvas =     document.getElementById("canvas");
 ctx = canvas.getContext("2d");
 ctx.fillStyle = 'blue';
 ctx.strokeStyle = 'blue';
 //point 0, 0
 ctx.moveTo(0, 0);
 //to point 300, 150
 ctx.lineTo(300, 150);
 ctx.closePath();

 ctx.stroke();
 ctx.fill();

您可以更改线宽并添加阴影。查看我的项目:

https://codepen.io/Luis4raujo/pen/GRNEPXO

如果此评论对您有帮助,请为我的答案投票!

您可能要考虑创建一个模式。您可以从图像或屏幕外创建它 canvas。这是第二种方式的快速演示:https://codesandbox.io/s/awesome-khorana-ystxp?file=/index.html

有关 html canvas 中模式创建的更多信息:https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createPattern