javascript - 是否可以使用 Canvas 制作渐变透明/图层蒙版图像?

标签 javascript html canvas transparency gradient

我一直在学习 Mozilla 网站上有关透明度和渐变的类(class):https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors但我一直无法弄清楚这一点。

我知道我可以用 png 图像实现这些效果;然而,在我正在处理的程序中,渐变会根据图像移动的位置不断变化。

这是我正在寻找的效果示例。 http://home.insightbb.com/~epyonxl1/gradientex.jpg

最佳答案

可以使用 context.globalCompositeOperation 来制作掩码

context.drawImage(img, 0, 0, img.width, img.height, 0,0, img.width, img.height);
context.globalCompositeOperation = "destination-out";
gradient = context.createLinearGradient(0, 0, 0, img.height);
gradient.addColorStop(0, "rgba(255, 255, 255, 0.5)");
gradient.addColorStop(1, "rgba(255, 255, 255, 1.0)");
context.fillStyle = gradient;
context.fillRect(0, 0, img.width, img.height);

这不会对每个像素进行操作,应该会更快

关于javascript - 是否可以使用 Canvas 制作渐变透明/图层蒙版图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3320417/

相关文章:

javascript - 如何在angularjs中的 Controller 和配置之间传递值

html - 使用 UTF-8 不显示特殊字符 ">"

javascript - 使用 JQuery 检查单独 div 中的多个复选框

javascript - Fabric JS : Set X Y Coordinates in Canvas Image | Set Position in Canvas Image

javascript - 如何分离一个js函数?

javascript - 如何让这个程序化 JS 变得更加实用呢?

javascript - 在 Internet Explorer 8 中看不到 CSS 菜单(潜在的 JavaScript 问题?)

html - 手动剥离 Bootstrap 表

jquery - Chart.js 如何在条形图的 Canvas 中添加一条线

javascript - 如何限制 <canvas> 上的绘图?