I'm simply trying to load 3 different images side by side, but when I run the following code it only draws the last image I push into src[]
multiple times.
function draw(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var tileWidth = 25;
var tileWCount = 3;
var multi = 2;
var src = [];
src.push("http://st.hzcdn.com/simgs/6361d7eb0dee6b28_4-1763/contemporary-tile.jpg");
src.push("http://www.in.all.biz/img/in/catalog/middle/205131.jpeg");
src.push("http://www.magnet-textures.com/textures/2011/7/715-1259-1-blue-tiles-ico-big.jpg");
for(var i=0; i < tileWCount; i++){
var img = new Image();
img.onload = (function(value){
return function() {
ctx.drawImage(img, (value * tileWidth * multi), 0, tileWidth * multi, tileWidth * multi);
}
})(i);
img.src = src[i];
}
}
I took a big chunk of this code from this Stack Overflow post. I can set the src
to a single image but when I try to use my iterator it starts failing. I did notice that the answer there is using ctx.drawImage
with src[value]
but I couldn't get a single thing to draw with that.
I'm at a complete loss as to why this might be happening.
I've set up a jsfiddle project for convenience: http://jsfiddle.net/fierstarter/jv0ko966/
function draw(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var tileWidth = 25;
var tileWCount = 3;
var multi = 2;
var imgA = [];
var src = [];
src.push("http://st.hzcdn.com/simgs/6361d7eb0dee6b28_4-1763/contemporary-tile.jpg");
src.push("http://www.in.all.biz/img/in/catalog/middle/205131.jpeg");
src.push("http://www.magnet-textures.com/textures/2011/7/715-1259-1-blue-tiles-ico-big.jpg");
for(var i=0; i < tileWCount; i++){
var img = new Image();
img.onload = (function(value){
return function() {
ctx.drawImage(img, (value * tileWidth * multi), 0, tileWidth * multi, tileWidth * multi);
}
})(i);
img.src = src[i];
}
}
draw();
#canvas{
border: 1px solid black;
}
<canvas id="canvas" width="320" height="240"></canvas>