javascript - Html5 Canvas描边透明渐变线

标签 javascript html canvas

如何使用 html5 Canvas 创建透明渐变描边?我需要它从一个点到另一个点,如下图所示。

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

这使它看起来像一个实心 block ,尽管像:

enter image description here

谢谢。

最佳答案

填充形状

使用形状并用渐变填充它。

您可以使用 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/

相关文章:

javascript - 将类别添加到一个下拉列表中 从其他下拉列表中删除类别

javascript - 使用 Flow 复制 TypeScript 'as'

html - 当我使用浏览器刷新页面 (F5) 重新加载页面时,Odoo 状态栏出现故障

javascript - 我们如何动态生成证书?

javascript - Canvas 不显示在移动设备上

javascript - 使用 JavaScript 和 Canvas 绘制形状

javascript - 将大型 JSON 数据从 C# Web API 发送到 Javascript 客户端

javascript - 在滚动 div 中保持鼠标指针附近悬停工具提示图像?

javascript - 我应该为我的网站使用 JQuery 的加载方法吗,因为 Google 看不到从该方法加载的内容

javascript - 在 FabricJS 上缩放对象时如何停止控制边框填充增加?