如何使用 html5 Canvas 创建透明渐变描边?我需要它从一个点到另一个点,如下图所示。
目前我得到了这个:
const gradient = ctx.createLinearGradient(1, 0, 100, 0);
gradient.addColorStop(0, '#fff');
gradient.addColorStop(1, '#d29baf');
ctx.lineWidth = 30;
ctx.strokeStyle = gradient;
ctx.beginPath();
ctx.moveTo(fromXPos, fromYPos);
ctx.lineTo(toXPos, toYPos);
ctx.stroke();
这使它看起来像一个实心 block ,尽管像:
谢谢。
最佳答案
填充形状
使用形状并用渐变填充它。
您可以使用 CSS 颜色类型 rgba(red,green,blue,alpha)
其中红色、绿色、蓝色的值范围为 0-255,alpha 为 0 透明到 1 不透明。
要创建形状,请先使用 ctx.beginPath() 创建一个新形状,然后使用 lineTo(x,y) 标记出每个 Angular 。如果您想使用相同的填充或描边添加另一个形状,您可以使用 ctx.moveTo(x,y) 移动到第一个点。
注意很多人使用 ctx.beginPath(); ctx.moveTo(x,y);
但这与 ctx.beginPath(); ctx.lineTo(x,y);
的工作原理相同由于 beginPath 之后的第一个点始终转换为 moveTo
对于任何类型的路径对象。
const ctx = canvas.getContext("2d");
// draw first box (left of canvas)
ctx.fillStyle = "#ab7383";
ctx.fillRect(20,100,50,50);
// draw second box (to right of first)
ctx.fillStyle = "#904860";
ctx.fillRect(100,20,50,130);
// gradient from top of second box to bottom of both boxes
const g = ctx.createLinearGradient(0, 20, 0, 150);
g.addColorStop(0, `rgba(${0xd2},${0xba},${0xaf},1`); // opaque
g.addColorStop(1, `rgba(${0xd2},${0xba},${0xaf},0`); // transparent
ctx.fillStyle = g;
ctx.beginPath();
ctx.lineTo(70, 100); // top right of first box
ctx.lineTo(100, 20); // top left of second box
ctx.lineTo(100, 150); // bottom left of second box
ctx.lineTo(70, 150); // bottom right of first box
ctx.fill(); // fill the shape
<canvas id="canvas" style="border:2px solid black"></canvas>
关于javascript - Html5 Canvas描边透明渐变线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46979592/