如果多次应用,带有 alpha 的 rgba fillStyle 不会变得完全不透明 [英] rgba fillStyle with alpha does not get fully opaque if applied multiple times

查看:9
本文介绍了如果多次应用,带有 alpha 的 rgba fillStyle 不会变得完全不透明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了一个奇怪的问题.以下代码导致图像逐渐消失,因为它被半透明的矩形一遍又一遍地覆盖.

I stubled upon a weird problem. The following code results in making the image fade away because it's overdrawn by a semi-opaque rect over and over again.

但至少在 draw(); 的第 10 次迭代中,图像应该完全过度绘制,因为到那时矩形应该是完全不透明的,对吧?但它实际上从未完全消失.

But at least at the 10th iteration of draw(); the image should be completely overdrawn, because the rect should be fully opaque by then, right? But it actually never disappears completely.

这种效果在 Chrome 上比在 Firefox 上更糟糕.但请注意:糟糕的屏幕可能会隐藏这种错误行为 =)

This effect is worse on Chrome than it is on Firefox. But beware: bad screens may hide this faulty behaviour =)

我还在jsFiddle上做了一个demo.

I also made a demo on jsFiddle.

$(function () {
var canvas = $("#mycanvas"),
    ctx = canvas[0].getContext("2d"),
    imgUrl = "http://it-runde.de/dateien/2009/august/14/25.png";


var image = new Image();  
image.src = imgUrl ;  
$(image).load(function() {
    ctx.drawImage(image, 0, 0, canvas.width(), canvas.height());
    draw();
});

function draw() {        
    ctx.fillStyle = "rgba(255, 255, 255, 0.1)";
    ctx.fillRect(0, 0, canvas.width(), canvas.height());
    setTimeout(draw, 100);
    
}    
});

人们可能想要达到的效果是,假设一个对象在整个画布上移动,并且已经绘制的位置只是略微过度绘制,因此会产生淡入淡出效果的余辉.但是这个结果实在是太丑了.

The effect one may want to achieve is that, say an object is moving all over the canvas, and the already drawn positions get overdrawn only slightly so after-glow of after-fade effect. But this result is just fugly.

那么有什么解决办法吗?

So is there any solution to this?

推荐答案

由于矩形只有 10% 不透明,因此在图像上绘制它的结果是 90% 的图像和 10% 的白色合成.每次绘制它,您都会损失 10% 的图像前一次迭代;矩形本身不会变得更加不透明.(要获得这种效果,您需要在图像上放置另一个对象并为其不透明度设置动画.)因此,在 10 次迭代之后,您仍然有 (0.9^10) 或原始图像的大约 35%.请注意,大约 30 次迭代后可能会出现舍入误差.

Since the rectangle is only 10% opaque, the result of drawing it over the image is a composite of 90% of the image and 10% white. Each time you draw it you lose 10% of the previous iteration of the image; the rectangle itself does not become more opaque. (To get that effect, you would need to position another object over the image and animate its opacity.) So after 10 iterations you still have (0.9^10) or about 35% of the original image. Note that rounding errors will probably set in after about 30 iterations.

这篇关于如果多次应用,带有 alpha 的 rgba fillStyle 不会变得完全不透明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆