JavaScript Initial Function Not Drawing on Canvas - javascript

Hello stackoverflow community,
I am working on a graphics engine in JavaScript, and currently am trying to repeat an image to use it as a background. Strangely, the initalize() function is not being called, until directly called in the browser console. I before this, I had buttons to move the image which I am now trying to use as the background. Even then, the image would only appear after one of the buttons was pressed. (that old code is commented out). Here is the JavaScript:
var ctx;
var cam_x = 0,cam_y = 0;
//End of Global Variables
function initialize(){
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);//RESETS
var img=new Image();
img.src = "brick.png";
var i;
var j;
for(i = 0; i < 10; i++){
for(j = 0; j < 10; j++){
drawTile(img, i, j, 0);
}
}
console.log("should be drawing");
// drawTile(img, 0,0,0);
// drawTile(img, 1,0,0);
// drawTile(img, 2,0,0);
// drawTile(img, 1,1,0);
// drawTile(img, 2,2,0);
// console.log("should be drawing");
}
function setTransformations(){
ctx.translate(-cam_x,-cam_y);
}
function drawTile(img,x,y,z){
ctx.setTransform(1,0,-1,1,0,z);
setTransformations();
ctx.drawImage(img,x*32,y*32);
ctx.setTransform(1,0,0,1,0,0);
}
function camtranslate(x,y){
cam_x += x;
cam_y += y;
initialize();
}
The commented out drawTile() calls were the to warp the image so it looked oblique (but that's not too relevant). Below is the HTML file:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: #1ABC9C
}
</style>
<script src="main.js"></script>
</head>
<body>
<!-- <button onclick="camtranslate(16,0);"> Right </button>
<button onclick="camtranslate(-16,0);"> Left</button> <br>
<button onclick="camtranslate(0,-16);"> Up </button>
<button onclick="camtranslate(0,16);"> Down </button>
-->
<center>
<h1>Akimbo</h1>
<canvas id="canvas" height="600" width="600" style="border:1px solid #7F8C8D"></canvas>
</center>
<script>camtranslate(16, 0);</script>
</body>
</html>
The commented out buttons made the image appear on pressing them, but now that I've commented them out, even though I've called the function, it doesn't work. The HTML file should call the initialize() function, but nothing appears in the canvas until I call the function directly in the console. How can I make it so that the background appears immediately upon the page's being loaded?
Thanks

Things take time to load and setting an images src attribute does not mean that the image is available for use.
You need to use the image.onload event to flag that the image has loaded and call the function that uses the image.
function drawTiles(){ // create the function to draw the tiles
var i;
var j;
for(i = 0; i < 10; i++){
for(j = 0; j < 10; j++){
drawTile(img, i, j, 0);
}
}
}
var img=new Image(); // create image
img.src = "brick.png"; // set the URL and it will start to load it
img.onload = drawTiles; // the image will call your function when it has loaded

Related

HTML CANVAS - Preload Issue or OnLoad issue - Why do I have to click twice?

I have an HTML page with 2 canvases side-by-side. The left one has a clickable upper region. The right one is where all the drawing takes place. I want the user to click the region on the left, which will load a new image on the right, and replace the one that is already there, but I have to click twice for the new image to show up. Why is this? See code.
THE HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
#centerAll {
margin-left:auto;
margin-right:auto;
width:1300px;
}
</style>
</head>
<body>
<div id="centerAll">
<canvas id="TheLeftCanvas" width="300" height="500"
style="border:2px solid #999999;"></canvas>
<canvas id="TheRightCanvas" width="900" height="500"
style="border:2px solid #999999;"></canvas>
<script type="text/javascript" src="whyClickTwiceForImage.js">
</script>
</div>
</body>
</html>
AND THE JAVASCRIPT
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded () {
canvasApp();
}
function canvasApp() {
var rightCanvas = document.getElementById("TheRightCanvas");
//THE EMPTY CANVAS ON THE RIGHT, WHICH DRAWS THINGS
var rightCtx = rightCanvas.getContext("2d");
var leftCanvas = document.getElementById("TheLeftCanvas");
//THE EMPTY CANVAS ON THE LEFT, WHICH HANDLES USER CLICKS
var leftCtx = leftCanvas.getContext("2d");
var currentMouseXcoor = 0;
var currentMouseYcoor = 0;
var imagesToLoad = 0; //USED TO PRE-LOAD SOME OTHER VISUALS, BEFORE THE USER STARTS
var imagesLoaded = 0;
var picturesTheUserCanChoose = ["pic01.png", "pic02.png",
"pic03.png", "pic04.png", "pic05.png"];
var nameOfPicTheUserChose = "pic05.png"; //LET'S JUST SAY "pic05.png" IS A PLACEHOLDER PICTURE... TO START OFF
var legitMouseClick = 0; //DID THE USER CLICK IN THE UPPER REGION OF THE LEFT CANVAS?
var loaded = function(){ // "LOADED" AND "LOAD IMAGE" ARE USED TO PRELOAD ALL THOSE OTHER VISUALS BEFORE THE USER STARTS
imagesLoaded += 1;
if(imagesLoaded === imagesToLoad){
imagesToLoad = 0;
imagesLoaded = 0;
drawScreen(); // OK... ALL LOADED.... SO DRAW THE SCREEN
}
}
var loadImage = function(url){ // "LOADED" AND "LOAD IMAGE" ARE USED TO PRELOAD ALL THOSE OTHER PICS BEFORE THE USER STARTS
var image = new Image();
image.addEventListener("load",loaded);
imagesToLoad += 1; // ADD THE NUMBER TO THE IMAGES NEEDED TO BE LOADED
image.src = url;
return image; // ...AND RETURN THE IMAGE
}
//--------------------------------------------------------------
leftCanvas.addEventListener('mouseup', function(evt) { var
mousePos = doMouseUp(leftCanvas, evt);
currentMouseXcoor = mousePos.x; currentMouseYcoor =
mousePos.y; processMousePosition();}, false);
//--------------------------------------------------------------
function drawScreen(){
clearScreen();
rightCtx.drawImage(picture1,0,0,100,100);
}
//THIS FUNCTION PRESUMABLY LOADS IMAGES ON-THE-FLY... BUT WHY DOES THE LEFT CANVAS REGION HAVE TO BE CLICKED TWICE FOR THE NEW IMAGE TO SHOW?
function processMousePosition() {
if(currentMouseYcoor >= 0 && currentMouseYcoor <= 50){
//IF THE CLICK IS IN THE UPPER REGION OF THE LEFT CANVAS
nameOfPicTheUserChose = picturesTheUserCanChoose[0];
//WE'LL SAY THE USER CHOSE THE VERY FIRST PIC IN THE ARRAY
picture1.src = ("picturesFolder/"+ nameOfPicTheUserChose);
picture1.onload = legitMouseClick = 1;//I JUST MADE UP FOR SOMETHING TO HAPPEN WHEN THE NEW PICTURE LOADS???
alert(nameOfPicTheUserChose); // THE ALERT CORRECTLY SHOWS THE NAME OF THE FIRST PIC IN THE ARRAY
}
drawScreen();
}
function doMouseUp(leftCanvas, evt){
var rect = leftCanvas.getBoundingClientRect();
return { x: evt.clientX - rect.left, y: evt.clientY - rect.top};
}
function clearScreen(){
rightCtx.clearRect(0, 0, 900, 500);
leftCtx.clearRect(0, 0, 300, 500);
}
//var someOtherVisual1 =
//loadImage("backgroundArtFolder/someOtherVisual1.jpg");
//var someOtherVisual2 =
//loadImage("backgroundArtFolder/someOtherVisual2.png");
//var someOtherVisual3 =
//loadImage("backgroundArtFolder/someOtherVisual3.png");
//var someOtherVisual4 =
//loadImage("backgroundArtFolder/someOtherVisual4.png");
//var someOtherVisual5 =
//loadImage("backgroundArtFolder/someOtherVisual5.png");
var picture1 = loadImage("picturesFolder/pic05.png");
//LET'S JUST PRELOAD "pic05.png" AS A PLACEHOLDER... TO START OFF
}
You can change the image load on click in js file picture1.src = ("picturesFolder/"+ nameOfPicTheUserChose); to picture1 = loadImage("picturesFolder/"+nameOfPicTheUserChose); and picture1.onload = legitMouseClick = 1; to 'legitMouseClick = 1'

JS for -loop always use last element - scope issues

var url_array = ["ulr1", "ulr2", "ulr3", "ulr4", "ulr5"];
var img = document.createElement('img');
for (i = 0; i < url_array.length; i++){
var div = document.createElement('div');
div.setAttribute("id", "div"+i);
document.getElementById('main').appendChild(div);
document.getElementById('div'+i).style.width = ImageWidth+5+"px";
document.getElementById('div'+i).style.height = ImageHeight+5+"px";
console.log("\ncreate all the DIVs. \nFor loop count: "+i);
img.src = loadImage(url_array[i], ImageWidth, ImageHeight);
try{throw img}
catch(c_img) {
document.getElementById('div'+i).appendChild(c_img);
console.log("after load, and append, in Catch: "+img.src);
console.log("div NR = "+document.getElementById('div'+i).id);
console.log(document.getElementById('div'+i).childNodes.length);
} //catch
} // FOR
function loadImage(URL, h, w)
{
console.log("loadImage callaed with URL = "+URL);
return url = URL+Date.now().toString(10);
}
For-Loop is supposed to retrieve urls address of an images (from camera) and append them to DIV. DIV and IMGs are created on the fly. Problem is that only last DIV become image holder.
I am using catch-try to force execute code immediately so each separate Div+i will have distinctive image. Also construction like this one (immediately invoked function expression):
(function(){
something here;
})();
for creating "private" scope gives no hope. Either "Let" - which supposed to define variable locally is not helping. *My knowledge here is limited and I'm relying on data found on web site (can give link later if it is not against rules).
Output of console.log() is not helping much.
Everything goes as it should, except for the childNodes.length which is 1 for each for-loop iteration - that means each DIV have its IMG child I guess... If so - why I can't see them?
I feel I am close to what I want to achieve - using Intervals() refresh each DIV with new camera snapshot, but I need to solve this current issue.
Example of code ready to use:
js.js:
var url_array = [
"https://images.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg",
"https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg",
"https://images.pexels.com/photos/617278/pexels-photo-617278.jpeg"
];
var ImageWidth = 640;
var ImageHeight = 480;
var img = document.createElement('img');
for (i = 0; i < url_array.length; i++){
var div = document.createElement('div');//.setAttribute("id", "div0");
div.setAttribute("id", "div"+i);
document.getElementById('main').appendChild(div);
document.getElementById('div'+i).style.width = ImageWidth+5+"px";
document.getElementById('div'+i).style.height = ImageHeight+5+"px";
var color = ((Math.floor(Math.random() * (16777215)) + 1).toString(16)); // from 1 to (256^3) -> converted to HEX
document.getElementById('div'+i).style.background = "#"+color;
document.getElementById('div'+i).style.width = ImageWidth+5+"px";
document.getElementById('div'+i).style.height = ImageHeight+5+"px";
console.log("\ncreate all the DIVs. \nFor loop count: "+i);
img.src = loadImage(url_array[i], ImageWidth, ImageHeight);
try{throw img}
catch(c_img) {
document.getElementById('div'+i).appendChild(c_img);
console.log("after load, and append, in Catch: "+img.src);
console.log("div NR = "+document.getElementById('div'+i).id);
console.log(document.getElementById('div'+i).childNodes.length);
} // catch
} // FOR
function loadImage(URL, h, w)
{
console.log("loadImage callaed with URL = "+URL);
return url = URL+"?auto=compress&h="+h+"&w="+w;
}
HTML:
<html>
<head>
<meta charset="utf-8">
<STYLE>
div#main {
padding: 5px;
background: black;
}
</STYLE>
</head>
<body>
<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "js.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
<div id="main"></div>
</body>
</html>
The problem is that your
var img = document.createElement('img');
is outside the loop - you're only ever creating one img. When appendChild is called on an element that already exists in the DOM (such as on the second, third, fourth, etc iteration), the element gets removed from its previous location and inserted into the new location.
Create the image inside the loop instead, and try not to implicitly create global variables - when declaring new variables, always use let or const.
Also, when you do
var div = document.createElement('div');
you have a reference to the div you just created - there's no need to assign an id to it in order to select it with
document.getElementById('div'+i)
in below lines in the same scope. Instead, just keep referencing the div:
const ImageWidth = 200;
const ImageHeight = 200;
const main = document.getElementById('main');
var url_array = ["ulr1", "ulr2", "ulr3", "ulr4", "ulr5"];
for (let i = 0; i < url_array.length; i++){
const img = document.createElement('img');
const div = document.createElement('div');
main.appendChild(div);
div.style.width = ImageWidth+5+"px";
div.style.height = ImageHeight+5+"px";
img.src = loadImage(url_array[i], ImageWidth, ImageHeight);
div.appendChild(img);
}
console.log(main.innerHTML);
function loadImage(URL, h, w) {
return URL+Date.now().toString(10);
}
div#main {
padding: 5px;
background: black;
}
<div id="main">
</div>

Firefox won't draw to canvas on first visit

I have an issue I'm having a hard time believing... It seems that when I draw to a dynamically created canvas in Firefox it wont render the first time that source is run... It seems to happen the first time the JavaScript in question is run either by modifying the source or visiting the link for the first time. Here are some repro steps:
1) open a brand new instance of Firefox. visit the jsFiddle below.
2) see nothing
3) open a new tab in Firefox. visit the jsFiddle below.
4) see the result (10 colored squares)
Doing this in Chrome will result in seeing the result at both step 2 and step 4.
https://jsfiddle.net/sk873txv/1/
html
<body>
<div id="a">
</div>
</body>
js
$(document).ready(function(){
var make_canvas = function(i) {
var $canvas = $('<canvas>').appendTo($('#a'));
$canvas.attr('width', '100px');
$canvas.attr('height', '100px');
var canvas = $canvas[0];
var ctx = canvas.getContext('2d');
return ctx;
};
var draw = function(ctx) {
var image = new Image();
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkEAIAAACvEN5AAAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAABa0lEQVR42u3cMU4CARRF0SeyWl0P7FaxoKbBuRrNOZUJCU7xcv9UvGzb7Xa6btvrddse/f2dT0+Xg77noOd58r9c/tTTPvr08hPPc962z7fBoc7b9mFYHEyxSCgWCcUioVgkDIuEU0hCsUgoFgnFImFYJJxCEopFQrFIKBaJe7Hef/sx+G8Ui4RhkfDyTkKxSCgWCcUiYVgknEISikVCsUgoFgnFIqFYJAyLhFNIQrFIKBYJxSJhWCScQhKKRUKxSCgWCcMi4RSSUCwSikVCsUgoFgnFImFYJJxCEvdi+eE1DqZYJLxjkTAsEk4hCcUioVgkFIuEYpFQLBKGRcIpJKFYJBSLhGKRMCwSTiEJxSKhWCQUi4RhkXAKSSgWCcUioVgkFIuEYpEwLBJOIQnFIqFYJBSLhGGRuJ9CP7zGwRSLhJd3EopFQrFIKBYJwyLhFJJQLBKKRUKxSBgWCaeQhGKRUCwSikVCsUh8ARsPyYz6AmddAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDExLTA0LTA3VDIxOjM2OjAyKzEwOjAwezv9bwAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxMS0wNC0wN1QyMTozNjowMisxMDowMApmRdMAAAA2dEVYdFBORzpiS0dEAGNodW5rIHdhcyBmb3VuZCAoc2VlIEJhY2tncm91bmQgY29sb3IsIGFib3ZlKbpeXNkAAAAVdEVYdFBORzpJSERSLmJpdF9kZXB0aAAxNqc4FdcAAAAVdEVYdFBORzpJSERSLmNvbG9yX3R5cGUAMgEnYzIAAAAbdEVYdFBORzpJSERSLmludGVybGFjZV9tZXRob2QAMPs7B4wAAAAedEVYdFBORzpJSERSLndpZHRoLGhlaWdodAAxMDAsIDEwMNtVy6kAAAAkdEVYdFBORzpwSFlzAHhfcmVzPTcyLCB5X3Jlcz03MiwgdW5pdHM9MKQw/n0AAAArdEVYdFBORzp0ZXh0ADIgdEVYdC96VFh0L2lUWHQgY2h1bmtzIHdlcmUgZm91bmRcYYD5AAAAAElFTkSuQmCC";
ctx.drawImage(image, 0, 0);
};
for(var i = 0; i < 10; i++)
{
draw(make_canvas(i));
}
});
You should wait for the load event to fire on the image, before drawing it to a canvas. Even though the image data is embedded as a data URI, there is no guarantee the image will be rendered and ready to draw the instant you set the src. Waiting for the load event will ensure the image is ready.
Working Example (JSFiddle):
$(document).ready(function(){
var make_canvas = function(i) {
var $canvas = $('<canvas>').appendTo($('#a'));
$canvas.attr('width', '100px');
$canvas.attr('height', '100px');
var canvas = $canvas[0];
var ctx = canvas.getContext('2d');
return ctx;
};
var draw = function(ctx) {
var image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkEAIAAACvEN5AAAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAABa0lEQVR42u3cMU4CARRF0SeyWl0P7FaxoKbBuRrNOZUJCU7xcv9UvGzb7Xa6btvrddse/f2dT0+Xg77noOd58r9c/tTTPvr08hPPc962z7fBoc7b9mFYHEyxSCgWCcUioVgkDIuEU0hCsUgoFgnFImFYJJxCEopFQrFIKBaJe7Hef/sx+G8Ui4RhkfDyTkKxSCgWCcUiYVgknEISikVCsUgoFgnFIqFYJAyLhFNIQrFIKBYJxSJhWCScQhKKRUKxSCgWCcMi4RSSUCwSikVCsUgoFgnFImFYJJxCEvdi+eE1DqZYJLxjkTAsEk4hCcUioVgkFIuEYpFQLBKGRcIpJKFYJBSLhGKRMCwSTiEJxSKhWCQUi4RhkXAKSSgWCcUioVgkFIuEYpEwLBJOIQnFIqFYJBSLhGGRuJ9CP7zGwRSLhJd3EopFQrFIKBYJwyLhFJJQLBKKRUKxSBgWCaeQhGKRUCwSikVCsUh8ARsPyYz6AmddAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDExLTA0LTA3VDIxOjM2OjAyKzEwOjAwezv9bwAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxMS0wNC0wN1QyMTozNjowMisxMDowMApmRdMAAAA2dEVYdFBORzpiS0dEAGNodW5rIHdhcyBmb3VuZCAoc2VlIEJhY2tncm91bmQgY29sb3IsIGFib3ZlKbpeXNkAAAAVdEVYdFBORzpJSERSLmJpdF9kZXB0aAAxNqc4FdcAAAAVdEVYdFBORzpJSERSLmNvbG9yX3R5cGUAMgEnYzIAAAAbdEVYdFBORzpJSERSLmludGVybGFjZV9tZXRob2QAMPs7B4wAAAAedEVYdFBORzpJSERSLndpZHRoLGhlaWdodAAxMDAsIDEwMNtVy6kAAAAkdEVYdFBORzpwSFlzAHhfcmVzPTcyLCB5X3Jlcz03MiwgdW5pdHM9MKQw/n0AAAArdEVYdFBORzp0ZXh0ADIgdEVYdC96VFh0L2lUWHQgY2h1bmtzIHdlcmUgZm91bmRcYYD5AAAAAElFTkSuQmCC";
};
for(var i = 0; i < 10; i++)
{
draw(make_canvas(i));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<div id="a">
</div>
</body>

Display image in canvas with Javascript?

I want to be able to click on a button on my page and load an image into a canvas at some X,Y coordinates?
The following code is what I have below. I would like the image to be in either image/photo.jpg or in the same directory but preferably in a subdirectory of the main page.
**Question: How to make a JPG show up in a canvas with the click of a button on the web page?
Code:
<!DOCTYPE html>
<html>
<script>
function draw(){
var ctx = document.getElementById("myCanvas").getContext("2d");
var img = new Image():
// img.src = "2c.jpg";
img.src = "/images/2c.jpg";
ctx.drawImage(img,0,0);
}
</script>
<body background="Black">
<div align="center">
<button type="button" onclick="draw()">Show Image on Canvas</button>
<canvas id="myCanvas" width="900" height="400" style="border:2px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
</div>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="20px Arial";
ctx.fillText("Royal Flush $",500,50);
ctx.fillText("Striaght Flush $",500,80);
ctx.fillText("Flush $",500,110);
ctx.fillText("Four of a Kind $",500,140);
ctx.fillText("Full House $",500,170);
ctx.fillText("Three of a Kind $",500,200);
ctx.fillText("Two Pair $",500,230);
ctx.fillText("Pair of ACES $",500,260);
ctx.rect(495,10,270,350);
ctx.stroke();
</script>
</body>
</html>
March 6th, 2014 Code:
How is the following code not working. Do you have to have an ID tag on Canvas. The page will display but for some reason the image will not when the button is clicked. The image is in the same directory that my index.html file is in.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style type="text/css">
canvas{
border: 5px solid black;
}
</style>
</html>
<button id="galaxy">Add image #1</button>
<button id="circles">Add image #2</button><span></span>
<canvas width="500" height="500"></canvas>
<script>
var Images = {};
function loadImages(list){
var total = 0;
document.querySelector("span").innerText = "...Loading...";
for(var i = 0; i < list.length; i++){
var img = new Image();
Images[list[i].name] = img;
img.onload = function(){
total++;
if(total == list.length){
document.querySelector("span").innerText = "...Loaded.";
}
};
img.src = list[i].url;
}
}
function drawImage(img){
var ctx = document.querySelector("canvas").getContext("2d");
ctx.drawImage(Images[img], 0, 0, 50, 50);
}
loadImages([{
name: "2c.jpg",
url: "mp.jpg"
},{
name: "mp.jpg",
url: "mp.jpg"
}]);
document.querySelector("#galaxy").addEventListener("click", function(){
drawImage("galaxy");
});
document.querySelector("#circles").addEventListener("click", function(){
drawImage("weirdCircles");
});
</script>
</html>
Wait till the image is loaded before drawing:
var img = new Image();
img.onload = function(){ /*or*/ img.addEventListener("load", function(){
ctx.drawImage(img,0,0); ctx.drawImage(img,0,0);
}; };
img.src = "/images/2c.jpg";
Demo: http://jsfiddle.net/DerekL/YcLgw/
If you have more than one image in your game,
It is better to preload all images before it starts.
Preload images: http://jsfiddle.net/DerekL/uCQAH/ (Without jQuery: http://jsfiddle.net/DerekL/Lr9Gb/)
If you are more familiar with OOP: http://jsfiddle.net/DerekL/2F2gu/
function ImageCollection(list, callback){
var total = 0, images = {}; //private :)
for(var i = 0; i < list.length; i++){
var img = new Image();
images[list[i].name] = img;
img.onload = function(){
total++;
if(total == list.length){
callback && callback();
}
};
img.src = list[i].url;
}
this.get = function(name){
return images[name] || (function(){throw "Not exist"})();
};
}
//Create an ImageCollection to load and store my images
var images = new ImageCollection([{
name: "MyImage", url: "//example.com/example.jpg"
}]);
//To pick and draw an image from the collection:
var ctx = document.querySelector("canvas").getContext("2d");
ctx.drawImage(images.get("MyImage"), 0, 0);

Javascript load images in canvas with JCanvaScript

I am using JcanvaScript library to work with Html5 canvas and now I want to load some images in my Canvas, but only last image loading is successful, I can't see any other images but the last one and I don't know what is wrong with my code.
here is the code
<!DOCTYPE HTML>
<html>
<head>
<style>
canvas {
border: 1px solid #9C9898;
}
</style>
<script src="jcanvas/jCanvaScript.1.5.15.js"></script>
<script>
var imagesUrl = [];
var imagesObj = [];
var canvasWidth = 800;
var canvasHeight = 600;
var imagesIdPrefix = 'images_';
var canvas = "canvas";
var fps = 60;
imagesUrl.push('images/image1.jpg');
imagesUrl.push('images/image2.jpg');
imagesUrl.push('images/image3.jpg');
imagesUrl.push('images/image4.jpg');
function init(){
for (i = 0; i < imagesUrl.length; i++){
var xImage = new Image();
xImage.src = imagesUrl[i];
xImage.onload = function(){
jc.start(canvas, fps);
jc.image(xImage, i*10, 0, 200, 200)
.id(imagesIdPrefix.toString() + i.toString());
jc.start(canvas, fps);
}
imagesObj.push(xImage);
}
}
</script>
</head>
<body onload="init()">
<canvas id="canvas" width="800px" height="600px"></canvas>
</body>
</html>
The bug has been identified in comment by MrOBrian : when the onload callbacks are called, i has the value it has at the end of the loop. That's the reason why you think that only last image loading is successful.
A standard solution is to embbed the content of the loop in a closure keeping the value of i :
for (i = 0; i < imagesUrl.length; i++){
(function(i){
var xImage = new Image();
xImage.src = imagesUrl[i];
xImage.onload = function(){
jc.start(canvas, fps);
jc.image(xImage, i*10, 0, 200, 200)
.id(imagesIdPrefix.toString() + i.toString());
jc.start(canvas, fps);
}
imagesObj.push(xImage);
})(i);
}
EDIT :
when you want to ensure all the needed images are loaded before running some code, you may use this function :
function onLoadAll(images, callback) {
var n=0;
for (var i=images.length; i-->0;) {
if (images[i].width==0) {
n++;
images[i].onload=function(){
if (--n==0) callback();
};
}
}
if (n==0) callback();
}
The images must have been provided their src first. You call the function like this :
onLoadAll(imagesObj, function(){
// do something with imagesObj
});
You need to make sure the images are loaded before you go and loop through them.
By defining your onload function inside of the for loop, the image may not have loaded by that point, and so the script will skip over it. And when it's done looping, the last image may be the only one that's loaded in time.
I would recommend adding a loader for each of the images outside the for loop, and when all the images are loaded go ahead and loop through the array.
A loader and checker looks something like this:
var loadedImages = [];
var loadedNumber = 3 //the number of images you need loaded
var imageToBeLoaded = new Image();
imageToBeLoaded.onload = function() {
loadedImages.push(true);
checkImages();
}
function checkImages() {
if (loadedImages.length != loadedNumber) {
setTimeout(checkImages(),1000);
} else {
init(); //your draw function
}
}

Categories