[英]canvas clearrect, with alpha
So I know that context.clearRect
makes pixels transparent, but I'm wondering, is there a function to make pixels translucent? 所以我知道context.clearRect
使像素透明,但我想知道,是否有一个使像素半透明的功能?
For example, say I have a canvas with these colors (fourth one in each color is alpha): 例如,假设我有一个带有这些颜色的画布(每种颜色中的第四个是alpha):
#ffff #feef #abff
#5f6f #000f #ffff
Running clearRect
would resolve into this (or something, just make them all transparent): 运行clearRect
会解析为这个(或者其他东西,只是让它们全透明):
#fff0 #fee0 #abf0
#5f60 #0000 #fff0
I want to remove opacity, but not make it transparent (kind of like globalAlpha
for clearRect
), so that it can end up like this (lets say I set the globalAlpha
equivalent to 0.5): 我想删除不透明度,但不要使它透明(类似于clearRect
globalAlpha
),因此它可以像这样结束(假设我将globalAlpha
等效设置为0.5):
#fff8 #fee8 #abf8
#5f68 #0008 #fff8
Is this possible? 这可能吗? Or would it be simpler just to draw everything on an off-screen canvas, then draw that canvas (with globalAlpha
set) on an on-screen one? 或者只是在屏幕外画布上绘制所有内容,然后在屏幕上绘制画布(使用globalAlpha
设置)会更简单吗?
Let me know if this isn't clear in any way. 如果这一点不清楚,请告诉我。
The answer above gets the job done, however getImageData is super slow and if you have a lot of other stuff going on it will slow down your animation immensely. 上面的答案可以完成工作,但是getImageData非常慢,如果你有很多其他的东西,它会极大地减慢你的动画。 If you create a second off screen canvas element you can set its global alpha to .9 and shuffle them back and forth and get the same effect with much greater speed. 如果你创建了第二个屏幕外的画布元素,你可以将它的全局alpha设置为.9并来回移动它们,并以更快的速度获得相同的效果。
context2.clearRect(0,0,width,height);
context2.globalAlpha = .9;
context2.drawImage(canvas1,0,0);
context1.clearRect(0,0,width,height);
context1.drawImage(canvas2,0,0);
context1.the rest of the drawing that you are doing goes here.
I just tried to figure this out too, and I've decided to count through the pixels, setting the alpha channel of each one manually. 我只是试图解决这个问题,我决定计算像素,手动设置每个像素的alpha通道。 This is a bit more work, because I can't just cover the entire canvas with a rect, but it's working so far. 这是一个更多的工作,因为我不能用rect直接覆盖整个画布,但它到目前为止工作。
I'm doing this so that I can set a background image for the webpage and put my canvas animation over it, without having to draw the background in the canvas element. 我这样做是为了我可以为网页设置背景图像并将我的画布动画放在它上面,而不必在canvas元素中绘制背景。
var oldArray = context.getImageData(0,0,canvas.width,canvas.height);
//count through only the alpha pixels
for(var d=3;d<oldArray.data.length;d+=4){
//dim it with some feedback, I'm using .9
oldArray.data[d] = Math.floor(oldArray.data[d]*.9);
}
sw.context.putImageData(oldArray,0,0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.