简体   繁体   English

在HTML Canvas中创建图像淡入

[英]Creating image fade in HTML Canvas

I've been playing with HTML canvas and recently started changing the opacity of images with context.globalAlpha . 我一直在使用HTML canvas ,最近开始使用context.globalAlpha更改图像的不透明度。 I thought it would be fun to write a little script to automatically fade an image out. 我认为编写一个小脚本以自动淡出图像会很有趣。 On the left side of the image, globalAlpha would be 1 (entirely opaque) and on the rightmost side globalAlpha would be 0 (entirely transparent). 在图像的左侧, globalAlpha将为1(完全不透明),在最右侧, globalAlpha将为0(完全透明)。

I tried taking 1-pixel wide slices of the source image and setting the globalAlpha to a gradually decreasing number : 我尝试拍摄源图像的1像素宽的切片并将globalAlpha设置为逐渐减小的数字:

fadeCtx = fadeCanvas.getContext('2d');

for (var i = 0; i < sourceImage.width; i++) {
    fadeCtx.globalAlpha = (sourceImage.width - i) / sourceImage.width;
    console.log(fadeCtx.globalAlpha);
    fadeCtx.drawImage(sourceImage, i, 0, i + 1, sourceImage.height, i, 0, i + 1,    sourceImage.height);
}

( JSFiddle of my code ) 我的代码的JSF中部

But this appears to have no effect. 但这似乎没有效果。 The image is drawn in place, but it is fully opaque throughout. 图像被绘制在适当的位置,但是整个图像都是完全不透明的。

Am I missing something about how to set opacity? 我是否缺少有关如何设置不透明度的信息? As you can see in the fiddle, I've successfully set globalAlpha for an entire image. 正如您在小提琴中看到的那样,我已经为整个图像成功设置了globalAlpha It's just when I try to draw "image slices" that it appears to have no effect. 只是当我尝试绘制“图像切片”时,它似乎没有任何作用。

Fixed it: 修复:

http://jsfiddle.net/mattdlockyer/zNcRB/ http://jsfiddle.net/mattdlockyer/zNcRB/

You were drawing the image over itself using i + 1 as the src image width and dst image width, instead use 1 for both. 您正在使用i + 1作为src图像宽度和dst图像宽度在其自身上绘制图像,而对两者都使用1。

The real offender was the dst image width, but I think using 1 for src image width may improve performance. 真正的犯罪者是dst图像宽度,但我认为对src图像宽度使用1可能会提高性能。

fadeCtx.drawImage(sourceImage, i, 0, 1, sourceImage.height, i, 0, 1, sourceImage.height);

Hope this helps! 希望这可以帮助!

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

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