Html5 Canvas笔划透明渐变线

时间:2017-10-27 16:25:48

标签: javascript html5 canvas

如何使用html5画布创建透明渐变笔触?我需要它从一个点到另一个点,看起来像下面的图像。

enter image description here

目前我已经得到了这个:

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

这使它看起来像一个坚固的块,但是:

enter image description here

感谢。

1 个答案:

答案 0 :(得分:3)

填充形状

使用形状并用渐变填充。

您可以使用CSS颜色类型rgba(red,green,blue,alpha),其中红色,绿色,蓝色是0-255的值,alpha是0透明,1个不透明。

要创建一个形状,首先使用ctx.beginPath()创建一个新形状,然后使用lineTo(x,y)标出每个角。如果要使用相同的填充或描边添加其他形状,请使用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>