简体   繁体   English

如何在html5画布中为白色背景创建褪色蒙版

[英]How to create a fading mask in html5 canvas for a white background

I got a circular canvas animation and I want to fade out the edges. 我有一个圆形的画布动画,我想淡出边缘。 The solution I ended up with was to create a larger canvas to put in front with a radial gradient from transparent to whatever color the background is. 我最终的解决方案是创建一个更大的画布,以从透明到背景颜色的径向渐变放置在前面。 This works great for a black background, but I cannot figure out why I get a gray gradient when I make it white . 这对于黑色背景非常有用,但是我无法弄清楚为什么将其设置为白色时会出现灰色渐变。

var c = document.getElementById('canvas'),
    ctx = c.getContext('2d'),
    w = 300,
    w2 = w / 2,
    h = 300,
    h2 = h / 2,
    cr = 100
;

c.width = w;
c.height = h;
ctx.rect(0, 0, w, h);
var g = ctx.createRadialGradient(
    w2,
    h2,
    1,
    w2,
    h2,
    cr * 90 / 100
);
g.addColorStop(0, 'transparent');
g.addColorStop(1, '#ffffff');
ctx.fillStyle = g;
ctx.fill();

Any thoughts? 有什么想法吗?

Your problem seems to be ignoring the fact that "transparent" has a colour. 您的问题似乎正在忽略“透明” 具有颜色的事实。 Transparent maps to rgba(0,0,0,0), which is invisible black. 透明映射到rgba(0,0,0,0),这是不可见的黑色。 When you transition from invisible black to visible white, in the middle you'll get transparent grey. 当您从不可见的黑色过渡到可见的白色时,在中间,您将获得透明的灰色。

Therefore, you can just replace 因此,您只需更换

g.addColorStop(0, 'transparent');

with

g.addColorStop(0, 'rgba(255,255,255,0)');

Which is invisible white. 这是无形的白色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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