简体   繁体   中英

Html 5 canvas and background

after trying a few ways to preserve a background under a canvas drawing a moving rectangle (animation code not reproduced), here is my best try :

canvas {background-image:url('background.png');}

var x,y, pixels;
function draw() {
  if(pixels) {
    context.putImageData(pixels,x,y);
  }
  x = //calculate new X
  y = //calculate new Y
  pixels = context.getImageData(x, y, 10, 10);
  context.fillStyle = 'red';
  context.fillRect(x, y, 10, 10);
}

My first question is : why won't replacing the first two lines of draw() with :

context.fillStyle = 'rgba(10,10,10,0)';
context.fillRect(x,y,10,10);

work to clear the previously drawn pixels?

And my second question is : is there really no better way than get and putImageData(), which are very labor-intensive?

EDIT: in particular is there a div containing the background image trick that would maybe work without the get and putImageData calls?

Thanks!

By default, whatever you draw gets drawn on top of each other, instead of being replaced.

Use context.clearRect(x,y,10,10); instead.

There is also the context.globalCompositeOperation property, which could be set to "destination-out" before using fillRect .. but you're better off with clearRect .

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