When to load an image to use the Javascript function drawImage()? - javascript

I would like to use the drawImage() function to load an image in a Javascript animation, but the image does not load with my current code. I think I need to specifically ask for the image to be loaded at some point, but I'm not sure when or how. The idea is to make a cloud that goes across the canvas. Thank you for your help.
function draw(x,y){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
x += 2;
if(x>1000){
x=0;
}
var cloud = new image();
cloud.src='small_cloud.png';
ctx.drawImage(cloud,x,0);
var loopTimer = setTimeout('draw('+x+','+y+')',20);
}

Try new Image()rather than new image()
Also move
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var cloud = new image();
cloud.src='small_cloud.png';
to outside the draw()function, as you only want to set these things up once. Delay this setting up until the browser has had time to parse the document, for example using
window.onload = function(){ ... };
(Though in reality you'd have to make sure not to overwrite any existing window.onload listeners by using proper even handler registration.) Also delay the first invocation to draw()until the image has loaded, for example like so:
cloud.onload = function(){
draw(cloud, 0, 0);
}
I'd also change
var loopTimer = setTimeout('draw('+x+','+y+')',20);
to
setTimeout(function(){ draw(x, y); }, 20);
since you seem not to be using the loopTimer variable, and since passing setTimeout an anonymous function rather than a string is considered better practice.
Finally, it would look like this:
window.onload = function() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var cloud = new image();
cloud.src='small_cloud.png';
cloud.onload = function(){
draw(ctx, cloud, 0, 0);
};
};
function draw(ctx, cloud, x,y){
x += 2;
if(x>1000){
x=0;
}
ctx.drawImage(cloud,x,0);
setTimeout(function(){ draw(ctx, cloud, x, y); }, 20);
}
Note that, since ctx is no longer defined inside the draw() function, as it is local to the anonymous window.onload function, you also has to pass ctx to the draw() function.

Related

Canva image dont display the image sometime using drawImage() method? [duplicate]

This question already has an answer here:
CanvasContext2D drawImage() issue [onload and CORS]
(1 answer)
Closed 3 years ago.
I want just to draw an image on canva using drawImage() method .But it happen sometime that the image is not drawn . even when I use the onload event it still fail to display the image.
Before I ask my question I want just to precise that the image is drawn somtimes and not drawn sometime .So what is the reason of the this problem and how can I tackle or fix it .
let imagez = new Image();
imagez.src="photo/run.png";
context.drawImage(imagez,10,10,50,60); // it does not draw the image always. why?
I expect the image to be drawn whenever I refresh the page
That most likely happens because the drawImage() method is called before the actual image is completely loaded.
Wait for it to finish loading before you call drawImage().
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);
canvas.width = 400;
canvas.height = 300;
var context = canvas.getContext("2d");
let imagez = new Image();
imagez.onload = function() {
context.drawImage(imagez, 10, 10, 50, 60);
}
imagez.src = "https://picsum.photos/400/300";
For this you have to wait for the image(s) to load into memory before they are available to draw to the canvas.
A simple loadIMAGE() function to achieve this might look something like this...
function loadIMAGE(path, x, y, w, h) {
var img = new Image();
img.addEventListener("load", function(e) {
// 'this' === the image Object
context.drawImage(this, x, y, w, h);
}, !1);
img.src = path;
}
// USAGE
loadIMAGE("photo/run.png", 10, 10, 50, 60);
It is important that the event-Handling function is defined before the src value is assigned.
Hope that helped :)
You are attempting to draw the image without knowing if it was successfully loaded...
Here is a working sample, using the onload event
const canvas = document.getElementById("gameArea");
context = canvas.getContext("2d");
let imagez = new Image();
imagez.onload = function () {
context.drawImage(imagez, 10, 10, 50, 60);
}
imagez.src = "https://upload.wikimedia.org/wikipedia/commons/e/e2/3D_Gyroscope.png";
<canvas id=gameArea></canvas>

How do I use an image to fill a layer in OpenLayers?

I'm using OpenLayers to draw a map, and I'd like to fill the polygon that describes a country with a photo from that country. I know I can pass a CanvasPattern to ol.style.Fill's color, but I don't know to generate an image.
Here's my code, and a JSfiddle with a full example: http://jsfiddle.net/07366L44/5/
function getPhoto() {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var photo = new Image();
photo.src = 'http://i.imgur.com/C6PL9tB.jpg';
return context.createPattern(photo, 'repeat');
}
I think it's because the photo is loaded async. Other examples create the pattern in the photo.onload method but I don't know how to return that.
Optimally I'd like to return a canvas which I can animate or update later with other photos, but I'll settle for just a single static image per country!
You'll have to set your style's fill color in the image's onload handler.
/**
* #param {ol.style.Style} style Style to set the pattern on.
*/
function setPattern(style) {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var photo = new Image();
photo.onload = function() {
canvas.width = photo.width;
canvas.height = photo.height;
var pattern = context.createPattern(photo, 'repeat');
style.getFill().setColor(pattern);
}
photo.src = 'http://i.imgur.com/C6PL9tB.jpg';
}
Note that the fill's color needs to be set before the style function is called, so you cannot call the setPattern function in the style function. It's better to create the style before loading the layer.

HTML Canvas Function

I have been writing some HTML canvas code in order to make a landscape. The code will not execute properly. What is my syntax error? Thanks, Benjamin
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
var llocation = 600;
var length = 360;
var linewidth = 2;
var testInt = length/(linewidth*2);
var wColour = "#994c00";
function isEven(value) {
if (value%2 == 0)
return true;
else
return false;
}
for(i=0;i<testInt+1;i++){
if(isEven(i)==true){
var wColour = "#994c00";
}
else if(isEven(i)==false){
var wColour = "#B87333";
}
ctx.beginPath();
ctx.strokeStyle = wColour;
ctx.lineWidth = linewidth;
ctx.rect(llocation,300,length,250);
ctx.stroke();
ctx.closePath();
var llocation = llocation + linewidth;
var length = length - (linewidth*2);
}
Placement and order of javascript is important. At the simplest level javascript code is executed in the order it appears on the page. This means that if you have a function function foo() in a file foo.js and try to call it from a script above where you load the file foo.js it will fail because the function has not yet been loaded.
For the safest way put all your code at the bottom of the page just before the closing </body> tag with the files containing the function above the code that calls the functions.
The same goes for element that you access. If you are accessing the canvas element in script above where the canvas element is in the document, it will fail because the canvas element has not yet been loaded and does not exist.
Alternately you can use the document on load event to start you code. This will ensure that everything has been loaded and parsed ready for your code.
document.addEventListener("load",function(){
// your code
});

Javascript - canvas - drawImage does not work

I have read all the other similar posts but I don't understand why it I have this problem.
I have a canvas (#canvas) and an image (hero.png) on the page, and a JS file loaded at the end of the body. In the JS code...
This works:
var game = {};
game.canvas = document.getElementById('canvas');
game.ctx = game.canvas.getContext("2d");
game.draw = function(){
game.ctx.drawImage(game.hero, 200, 200);
}
game.hero = new Image();
game.hero.src = "hero.png";
game.hero.onload = game.draw;
And this doesn't work:
var game = {};
game.canvas = document.getElementById('canvas');
game.ctx = game.canvas.getContext("2d");
game.hero = new Image();
game.hero.src = "hero.png";
game.hero.onload = game.draw;
game.draw = function(){
game.ctx.drawImage(game.hero, 200, 200);
}
Nothing appears. No error in the console. Why???
Thanks!
You can call functions before define them only with this syntax:
function draw()
{
//COde here
}
By writting
game.draw = function(){};
You define a method to your object, you don't define a JavaScript function: that's why you can't call it before define it :)
In your second hunk of code, you're defining
game.hero.onload = game.draw;
When game.draw is undefined, so your onload is undefined and nothing happens when the image is done loading.
game.draw is not set when you assign it in your second example, you are copying an undefined value into hero.onload.
One workaround is to wrap the function you want to call in an anonymous function and call yours from there:
game.hero.onload = function(){ game.draw(); };
Have in mind that if hero loads before the definition of game.draw is finished, this code will fail.

HTML5,Javascript canvas tag image.onload() issue

function LoadResources(){
alert("In load socket");
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var tiles= new Array();
var loadedCount=0;
for (x = 101; x <= 155; x++) {
var imageObj = new Image(); // new instance for each image
imageObj.src = "Resources/ClassicCardImages/deck1/dood_deck/"+x+".GIF";
imageObj.onload=function(){
loadedCount++;
if(loadedCount==55){
cardsImagesLoaded();
}else {
alert(loadedCount);
}
};
tiles.push(imageObj);
}
};
So when i call the function LoadResources() it does give the alert "in load socket" but does not gives the alert while in imageObj.onload function.
You can use window.onload function i.e "window.onload = function() {..}" and my function in it while use in the body of html document.
Plus i m running it on Google chrome .Is there the problem with chrome's onload or something .
You are trying to increase the loading counter even if the onload function are called only once (at the moment when the images has been loaded completely), so there is no way to trigger the alert many times. For me it's not quite obvious what are you trying to do. Anyway if you want to load multiple images with onload function the best practice is to use a closure, otherwise on each iteration it may happens that at the end of the loop you will get only the last image loaded. I'm not going into detail into what a closure is, but the principle is something like this:
for (var i = 0; i< 4; i++) {
var imgObj = new Image();
imgObj.onload = (function(img) {
return function () {
ctx.drawImage(imgObj, 0, 0);
}
})(i);
imgObj.src = 'image.png';
}
This way by calling a new function you will create a new execution context retaining the value of i on each iteration.
I am just adding a little help for your code.
For assigning functions the way you're doing it , it is cheaper to do it the way below.
for (x = 101; x <= 155; x++) {
var imageObj = new Image(); // new instance for each image
imageObj.src = "Resources/ClassicCardImages/deck1/dood_deck/"+x+".GIF";
imageObj.onload= imageOnLoad;
}
function imageOnLoad(){
loadedCount++;
if(loadedCount==55){
cardsImagesLoaded();
}else {
alert(loadedCount);
}
};
tiles.push(imageObj);
}

Categories

Resources