简体   繁体   中英

Html5 Canvas stroke transparent gradient line

How do I create a transparent gradient stroke that using html5 canvas? I need it to go from one point to another and look like the below image.

在此处输入图片说明

At the moment I have got this:

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

This makes it look like a solid block though like:

在此处输入图片说明

Thanks.

Fill a shape

Use a shape and fill it with the gradient.

You can use CSS colour type rgba(red,green,blue,alpha) where red,green,blue are values from 0-255 and alpha is 0 transparent to 1 opaque.

To create a shape you start with ctx.beginPath() to create a new shape then use lineTo(x,y) to mark out each corner. If you want to add another shape using the same fill or stroke you use ctx.moveTo(x,y) to move to the first point.

Note many people use ctx.beginPath(); ctx.moveTo(x,y); ctx.beginPath(); ctx.moveTo(x,y); but that works just the same as ctx.beginPath(); ctx.lineTo(x,y); ctx.beginPath(); ctx.lineTo(x,y); As the first point after beginPath is always converted to a moveTo for any type of path object.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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