我想知道如何减少html画布中所有像素的alpha值。
我通过鼠标输入在画布上绘制自由线,因此尝试重做一些预先编程的形状,这对我来说不是解决方案。
目标是在图像上添加fadeOut效果,所以我尝试使用此功能:
var canvas = document.getElementById('myCanvas');
context = canvas.getContext("2d");
var img = context.getImageData(0, 0, canvas.width, canvas.height);
var alpha = 1.0;
while(alpha > 0){
context.save();
context.clearRect(0, 0, canvas.width, canvas.height);
context.globalAlpha = alpha;
context.putImageData(img, 0, 0);
context.restore();
alpha = alpha - .01;
console.log(alpha);
img = context.getImageData(0, 0, canvas.width, canvas.height);
}
答案 0 :(得分:2)
减少容器div的不透明度会轻易降低所包含的画布的不透明度。
如果您不希望整个画布消失,那么将增加的透明度与globalAlpha
和copy
合成相结合可能会很有用。 copy
合成将允许您重绘现有的自定义绘图,而无需使用非常昂贵的putImageData
。
示例代码和演示:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var alpha=1.00;
var img=new Image();
img.onload=start;
img.src="https://source.unsplash.com/random/300x300";
function start(){
ctx.drawImage(img,0,0);
}
function fade(decrement){
alpha-=decrement
if(alpha<0.01){ctx.clearRect(0,0,canvas.width,canvas.height);return}
ctx.globalAlpha=alpha;
ctx.globalCompositeOperation='copy';
ctx.drawImage(canvas,0,0,img.width,img.height,0,0,img.width,img.height);
ctx.globalAlpha=1.00;
ctx.globalCompositeOperation='source-over';
}
$('#go').click(function(){
fade(0.10);
});
$('#fadeit').click(function(){
requestAnimationFrame(animateFadeOut);
});
function animateFadeOut(){
fade(0.01);
if(alpha>0.00){requestAnimationFrame(animateFadeOut);}
}
&#13;
body{ background-color: ivory; }
#canvas{border:1px solid red;}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id=go>Repeatedly click to fade out the image</button>
<br>
<button id=fadeit>Animate a fadeout</button>
<br>
<canvas id="canvas" width=300 height=300></canvas>
&#13;