javascripthtmlcanvasclipglobalcompositeoperation

Using globalCompositeOperation for a limited number of images


I have a very simple question : is it possible to use globalCompositeOperation for only a restricted number of images?

For example, I draw a lot of stuff into my canvas. And on top of everything, and completed unrelated, I want to do some operations on two images (and I just want the result to be displayed, not both images). How can that be done?

For now, doing such operations affects everything that's already drawn underneath.

So a solution I found is doing the operations in another canvas, which I display on top of my main, first canvas. But this looks bad. First, it hits performances. Then, it doesn't feel intuitive. And last, I loose control over the layers : whatever is in my second canvas will always be on top of the first canvas.

This looks like a pretty simple feature, I hope I'm just bad at googling!

Thanks a lot!


Solution

  • Create a offscreen canvas and use it as a work space. You can create many as long as you have the RAM to store them.

    To create an offscreen canvas

    function createCanvas(w,h){
          var canvas = document.createElement("canvas");
          canvas.width = w;
          canvas.height = h;
          canvas.ctx = ctx.getContext("2d");
          return canvas;
    }
    

    Easy as that and then you just treat it as an image. To draw to another canvas

    var offScreenCan = createCanvas(1024,1024);
    offScreenCan.ctx.drawImage(myImage);  // put something on the canvas
    ctx.drawImage(offScreenCan,0,0);  // draw that canvas to another
    

    I attach the context to the canvas rather than wrap the canvas in a containing object. I used to worry that the canvas would affect performance now I convert all images to canvas as soon as I load them and it does not impact performance at all.