Home > database >  Draw two or more images vertically in a single canvas
Draw two or more images vertically in a single canvas

Time:05-08

var base_image = new Image();
base_image.src = 'https://......jpg'; 
var can = document.getElementById("pai");
var ctx = can.getContext('2d');
base_image.onload = function() {
    can.style.width = base_image.width;
    can.style.height = base_image.height;
          var imgWidth= base_image.width;
        var imgHeight=base_image.height;
        ctx.canvas.width= imgWidth;
        ctx.canvas.height= imgHeight;
        ctx.drawImage(base_image,0,0,imgWidth,imgHeight);

I am using above code to draw a image on canvas is there any way so I could draw 2 or more images vertically, thanks

CodePudding user response:

So in general if you want to draw a bunch of images in a guaranteed order, you can try using a stack/array to store the images and then draw them in a loop!

The order of drawing will determine the order in which they're displayed.

Here's how I recommend you setup your code so that you load all the images you need first before you start drawing:

// Counter to keep track of how many images have loaded so far.
let imagesReady = 0;

// Array of image urls/srcs that you can easily update.
const imageSrcs = ['https://acnhcdn.com/latest/FtrIcon/FtrMarioRoundB.png', 'https://acnhcdn.com/latest/FtrIcon/FtrMarioSquareA.png'];

// Construct a new array with image objects
const images = imageSrcs.map((src) => {
  const image = new Image();
  image.src = src;
  
  // Increment our `imagesReady` counter once this image loads.
  image.onload = () => {
    imagesReady  ;

    if (imagesReady >= imageSrcs.length) {
      // Trigger the image draw
      drawImages();
    }
  }
  return image;
});

const can = document.getElementById("pai");
const ctx = can.getContext('2d');

function drawImages() {
  // Set the canvas height to the sum of all image heights
  can.height = images.reduce((previousValue, image) => previousValue   image.height, 0);

  let lastImage = null;
  let lastImageY = 0;

  // We store the last image data above so that
  // we know what is the next Y to start drawing at.
  for (const image of images) {
    lastImageY = lastImage ? lastImageY   lastImage.height : 0;
    lastImage = image;
    ctx.save();
    ctx.drawImage(image, 0, lastImageY, image.width, image.height);
    ctx.restore();
  }
}

Jsfiddle

Note: Typically, when you have a canvas, you may tend to wrap it in a setInterval or requestAnimationFrame loop so that you keep updating the canvas at, say, 30 or 60 frames per second (for example, if you're making an interactive canvas screen where positions/drawings change or you're making a game).

In that scenario, the above technique is a very simple/basic way of actually setting up a loading bar so that you can load all your assets first (until imagesReady === imageSrcs.length)

You could show a loading bar or loading message for a better user experience.

  • Related