简体   繁体   中英

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);
});

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
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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM