简体   繁体   中英

Reduce opacity all pixels in a html canvas

I'd like to know how can I reduce the alpha of all pixels in a html canvas.

I draw free lines on the canvas through a mouse input, so trying to redo some pre-programmed shapes it's not a solution for me.

The goal is to add a fadeOut effect on the image, so I was trying to do it with this function:

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);
}

Reducing the opacity of the container div will easily reduce the contained canvas's opacity.

If you don't want the whole canvas to fade, it might be useful to combine an increasing transparency with globalAlpha with copy compositing. The copy compositing will let you redraw your existing custom drawings without using the very expensive putImageData .

Example code and a Demo:

 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);} } 
 body{ background-color: ivory; } #canvas{border:1px solid red;} 
 <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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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