Christian
Christian

Reputation: 39

Javascript not loading image object from array onto canvas

I've been reading through (and trying) everything i can find on this subject, without luck. My goal is to load all image sources from arr_images into an array containing the image objects, and then, drawing a specific image onto the canvas.

Any help is much appreciated! Thanks in advance.

index.html

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="js/jquery-2.1.4.min.js"></script>
<script src="js/enginev2.js"></script>
</head>
<body>
<canvas id="main" width="1000" height="500"></canvas>
</body>
</html>

enginev2.js

var arr_images = ["images/player.jpg"];
var obj_images = [];

$.each(arr_images, function(key, image) {
    var img = new Image();
    img.src = image;
    obj_images.push(img);
});

var c = document.getElementById("main");
var ctx = c.getContext("2d");

$(document).ready(function() {
    ctx.drawImage(obj_images[0], 0, 0, 100, 100);
});

Upvotes: 1

Views: 154

Answers (2)

user5306544
user5306544

Reputation:

var arr_images = ["images/player.jpg"];
var obj_images = [];

$.each(arr_images, function(key, image) {
    var img = new Image();
    img.src = image;
    obj_images.push(img);
    img.onload = function() {
        ctx.drawImage(obj_images[0], 0, 0, 100, 100);
    }
});

var c = document.getElementById("main");
var ctx = c.getContext("2d");

Upvotes: 0

Mr_Pouet
Mr_Pouet

Reputation: 4280

My guess right now is that your image isn't properly loaded when you try to draw it (the document is probably ready before the image is fully loaded).

Try calling your ctx.drawImage function using a function callback on your img object:

img.onload = drawImage;  // calls ctx.drawImage

Upvotes: 2

Related Questions