smythdev
smythdev

Reputation: 43

Best way to display an array of images to the canvas in HTML5?

As the title states, I'm trying to put a series of images into an array and then draw them onto the canvas in HTML5, I'm getting no errors but nothing is showing up. I'm new to HTML5 so am having a bit of trouble.

Here's what I have:

    var canvas = document.querySelector('Canvas');

    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    var ctx = canvas.getContext('2d');


    function drawImagesToCanvas() {
        var imageArray = new Array();
        imageArray[0] = "graphics/1.png";
        imageArray[1] = "graphics/2.png";
        imageArray[2] = "graphics/3.png";
        imageArray[3] = "graphics/4.png";
        imageArray[4] = "graphics/5.png";
        imageArray[5] = "graphics/6.png";
        imageArray[6] = "graphics/7.png";
        imageArray[7] = "graphics/8.png";
        imageArray[8] = "graphics/9.png";
        imageArray[9] = "graphics/10.png";

        ctx.drawImage(imageArray[0], 120, 280, 220, 150);

    }

I thought it may be the file path but I've tried multiple variations.

Upvotes: 0

Views: 1574

Answers (1)

Daniel Beck
Daniel Beck

Reputation: 21485

You don't feed a source URL to drawImage; it wants the image itself. This can be read from a DOM element or by constructing an Image object in code, as shown here:

var canvas = document.querySelector('Canvas');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext('2d');

function drawImagesToCanvas() {
  var imageArray = new Array();
  imageArray[0] = "https://placehold.it/220x150";
  // ...

  var img = new Image(); 
  img.onload = function() {
    ctx.drawImage(img, 20, 80, 220, 150);
  };
  img.src = imageArray[0];
}

drawImagesToCanvas();
<canvas></canvas>

Upvotes: 1

Related Questions