gpt4 book ai didi

javascript - Canvas - 图像不透明度循环(淡入)

转载 作者:行者123 更新时间:2023-11-30 12:34:06 24 4
gpt4 key购买 nike

伙计们。这里有一些应该没问题的代码,虽然它不起作用......嘿......非常典型=)

function xxx() {

var txtCanvas = document.getElementById('text');
var textOne = txtCanvas.getContext('2d');
var alpha = 0.5;
textOne.globalAlpha = alpha;
// loading image
var img = new Image();
img.src = "http://tvangeste.com/gallery/selani/tv4_2.jpg"
img.onload = function () {
textOne.drawImage(img, 0, 0);

}
//end of image loader

if (alpha < 1)
{
alpha += 0.1;

}



}
requestAnimationFrame(xxx);

这是 Fiddle 来展示它是如何不起作用的...... http://jsfiddle.net/gLs1owd6/

该脚本应该做一件简单的事情 - 使图像淡入淡出。有什么建议么?谢谢!

最佳答案

您需要一个循环才能在不同的不透明度级别重绘图像。对于循环,您需要一些既不会阻塞 UI 又不会随着每次监视器更新而刷新的东西,因此,requestAnimationFrame 可以助您一臂之力。

这是解决此问题的一种方法:

var img = new Image();
img.onload = function () {

// when image has loaded we can use it.
// this is a self-invoking function used to fade in the image
(function loop() {
// we can update the property directly
textOne.globalAlpha += 0.01;

// as we have opacity involved we need to clear the canvas each time
textOne.clearRect(0, 0, txtCanvas.width, txtCanvas.height);

// redraw the image
textOne.drawImage(img, 0, 0);

// if not full opacity, loop (canvas will clamp the value for us)
if (textOne.globalAlpha < 1.0) {
requestAnimationFrame(loop);
}
else {
// when done, call the next step from here...
}
})();

}

// set source as last step for image loading
img.src = "http://tvangeste.com/gallery/selani/tv4_2.jpg"

Modified fiddle

希望这对您有所帮助!

关于javascript - Canvas - 图像不透明度循环(淡入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26667397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com