Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drawImage behind all other content on a canvas? [duplicate]

I have a canvas, and I want to use drawImage to draw an image behind the current content on the canvas.

Due to the fact that there is content already on the canvas (I'm using Literally Canvas to create a canvas containing an image, so I can't really draw the image first), I cannot use drawImage before I render the rest of my content.

Is it possible to drawImage behind all other content on a canvas?

like image 546
Lucas Avatar asked Feb 06 '23 23:02

Lucas


1 Answers

Yes you can just use globalCompositeOperation destination-over, but note that your first image needs some transparency, otherwise, you will obviously not see anything :

var img1 = new Image();
var img2 = new Image();

var loaded = 0;
var imageLoad = function(){
   if(++loaded == 2){
     draw();
     }
   };
img1.onload = img2.onload = imageLoad;

var draw = function(){
  var ctx = c.getContext('2d');
  ctx.drawImage(img1, 100,100);
  // wait a little bit before drawing the background image
  setTimeout(function(){
    ctx.globalCompositeOperation = 'destination-over';
    ctx.drawImage(img2, 0,0);
    }, 500);
  }
img1.src = "https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png";
img2.src = "https://picsum.photos/200/200";
<canvas id="c" width="200" height="200"></canvas>
like image 120
Kaiido Avatar answered Feb 10 '23 23:02

Kaiido