HTML5/Javascript Image loading method & passing to variable - javascript

I have some code for loading images.
var assets = {
total:0,
success:0,
error:0
};
var stillLoading = true;
var img = {};
function LoadImage(name, path){
var toLoad = new Image();
toLoad.src = path;
assets.total++;
toLoad.addEventListener("load", function(){
assets.success++;
console.log(name + " loaded.");
img[name] = toLoad;
}, false);
toLoad.addEventListener("error", function(){
assets.error++;
}, false);
};
function Loading(){
if (assets.success == assets.total){
if (stillLoading){
console.log("All assets loaded. Starting game.");
};
stillLoading = false;
return false;
}else{
stillLoading = true;
return true;
};
};
May still be inefficient, and ugly since I'm new to practicing javascript, open to suggestions. It loads the image and tells the main program when all the assets have finished loading through the function Loading(), and then adds the image to the object img.
I've been using this for a while now for my images, and it works.
For example, if I did.
LoadImage("Car", "imageOfCar.png");
ctx.drawImage(img.Car, 0, 0);
this would draw the image just fine to the canvas.
However, when I assign another variable the image, which for various reasons I want to do, such as assigning images to objects. e.g.
var secondCar = img.Car
then try to draw it.
ctx.drawImage(secondCar, 0, 0);
I get this error.
Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'
If it works for the initial variable, it should act the same way towards another variable that has just been assigned the exact same thing. So why is it am I getting this error?
If I was to load the image the typical way that doesn't check if it's finished loading.
img.Car = new Image();
img.Car.src = "imageOfCar.png";
secondCar = img.Car;
ctx.drawImage(secondCar);
This would work.
The behaviour here is a bit confusing, could someone explain to me what is happening, and perhaps suggest a way to fix it?
EDIT: Just to clarify.
This is the html file, called index.html.
<!DOCTYPE html>
<head>
<title>HTML5 Game Base</title>
<link rel = "stylesheet" type = "text/css" href = "styles.css">
</head>
<body>
<canvas id="screen" width="270" height="480" style="border:1px solid #000000;"></canvas>
<script src = "script.js"></script>
</body>
</html>
The canvas is set up as screen. All the javascript code I've displayed above takes place within script.js which is called in index.html.
This is how screen is called within the script.js.
var canvas = document.getElementById("screen");
var ctx = canvas.getContext("2d");
This is what ctx.drawImage() is referencing.

I realize this won't be the most helpful answer, but I tinkered around with your code a little. This is what I used:
<!DOCTYPE html>
<head>
<title>HTML5 Game Base</title>
</head>
<body>
<canvas id="screen" width="270" height="480" style="border:1px solid #000000;"></canvas>
<script>
var stillLoading = true;
var img = {};
var canvas = document.getElementById("screen");
var ctx = canvas.getContext("2d");
assets = {};
assets.total = 0;
function LoadImage(name, path){
var toLoad = new Image();
toLoad.src = path;
assets.total++;
toLoad.addEventListener("load", function(){
//assets.success++;
console.log(name + " loaded.");
img[name] = toLoad;
}, false);
toLoad.addEventListener("error", function(){
assets.error++;
}, false);
}
</script>
</body>
</html>
Then in Chrome's console I typed
LoadImage("Car", "map.png");
LoadImage("un", "Untitled.png");
ctx.drawImage(img.Car, 0, 0);
ctx.drawImage(img.un, 0, 0);
and get the expected result of images loading in the canvas. Even when assigning one of the img images to a new variable, this works as expected.
var second = img.Car
ctx.drawImage(second, 0, 0)
It appears everything is working fine when run manually, so my guess would be timing. When are you running these commands? Are they in the js file or from the console?
It would appear your LoadImage function is fine. Sorry this is not super helpful, but hopefully will help you rule out where not to look for the problem.

One approach could be to utilize Promise , as load event of new Image is asynchronous secondCar could be undefined when used as parameter within setInterval, e.g., load event of img may not be complete when var secondCar = img.Car applied after call to LoadImage; also added variable reference for setInterval for ability to call clearInterval() if needed
var canvas = document.getElementById("screen");
var ctx = canvas.getContext("2d");
var interval = null;
var assets = {
total: 0,
success: 0,
error: 0
};
var stillLoading = true;
var img = {};
function LoadImage(name, path) {
return new Promise(function(resolve, reject) {
var toLoad = new Image();
assets.total++;
toLoad.addEventListener("load", function() {
assets.success++;
console.log(name + " loaded.");
img[name] = toLoad;
// resolve `img` , `assets` object
resolve([img, assets])
}, false);
toLoad.addEventListener("error", function() {
assets.error++;
reject(assets)
}, false);
toLoad.src = path;
})
};
function Loading() {
if (assets.success == assets.total) {
if (stillLoading) {
console.log("All assets loaded. Starting game.");
};
stillLoading = false;
return false;
} else {
stillLoading = true;
return true;
};
};
var promise = LoadImage("Car", "http://pngimg.com/upload/audi_PNG1736.png");
promise.then(function(data) {
// `data` : array containing `img` , `assets` objects
console.log(data);
var secondCar = data[0].Car;
interval = setInterval(function() {
if (!(Loading())) {
ctx.drawImage(secondCar, 0, 0);
};
}, 1000 / 60);
});
<canvas id="screen" width="1000" height="700" style="border:1px solid #000000;"></canvas>

Solved. Turns out it was a timing issue. In the example I gave, when secondCar is assigned img.Car, img.Car had not yet loaded.
Instead I created a new function called Initialise(), and called it from within Loading(). So from now on I would just have to initialise all my variables that may require images from within Initialise(). This way, variables can only be assigned images after they've loaded.
New Code:
var canvas = document.getElementById("screen");
var ctx = canvas.getContext("2d");
var assets = {
total:0,
success:0,
error:0
};
var stillLoading = true;
var img = {};
function LoadImage(name, path){
var toLoad = new Image();
toLoad.src = path;
assets.total++;
toLoad.addEventListener("load", function(){
assets.success++;
console.log(name + " loaded.");
img[name] = toLoad;
}, false);
toLoad.addEventListener("error", function(){
assets.error++;
}, false);
};
function Loading(){
if (assets.success == assets.total){
if (stillLoading){
console.log("All assets loaded. Starting game.");
Initialise();
};
stillLoading = false;
return false;
}else{
stillLoading = true;
return true;
};
};
LoadImage("Car", "http://pngimg.com/upload/audi_PNG1736.png");
function Initialise(){
window.secondCar = img.Car;
};
setInterval(function(){
if (!(Loading())) ctx.drawImage(secondCar, 0, 0);
}, 1000/60);
Works now, thanks for the help although I ended up solving it myself. I would still appreciate any tips on how to improve it. Or knowing that I'm new to javascript, any nitpicks to help me conform to javascript conventions.

Related

Images on first load don't show on canvas

I want to pass a list of images and draw them each one for canvas.
My view.py:
def myview(request):
...
lista=Myobject.objects.filter(tipo=mytipo)
numero_oggetti = range(len(lista))
lista_formattata=[]
for elem in lista:
lista_formattata.append('/media/'+str(elem.myfield))
context_dict['lista']=lista_formattata
context_dict['numero_oggetti']=numero_oggetti
return render(request, 'mytemplate.html', context_dict)
My template.html:
<script>
<!--
window.onpageshow = function() {
myfunction({{lista|safe}});
};
-->
</script>
{% for c in numero_oggetti %}
<canvas id='componenti_canvas{{ c }}' width='60' height='75' style="border:1px solid #000000;">
Your browser does not support the HTML5 canvas tag.
</canvas>
{% endfor %}
My script.js:
function myfunction(lista) {
lista=lista
for (i=0; i<lista.length; i++) {
var canvas = document.getElementById('componenti_canvas'+i);
var ctx = canvas.getContext("2d");
var base = new Image();
base.src = lista[i];
ctx.scale(0.5,0.5);
ctx.drawImage(base, 0, 0);
};
};
This code works but sometimes the images show, sometimes don't (all of them or no one). When I load the page they don't show, when I re-load the page they show up. If I wait some minutes and re-load they don't show again.
I'm using firefox and in the console log when say GET image_name.png HTTP/1.0 200 they don't show (sometimes they are in cache, sometimes not... it don't make difference), when it don't say nothing they show.
I tried:
-setTimeout
-call the list with an ajax request with cache: false, async: false
-base.onload, like that:
base.onload = function(){
ctx.scale(0.5,0.5);
ctx.drawImage(base, 0, 0);
}
but or the images don't show never or they show in this way. I can give details, of course I can have done errors.
Edit: in the comment say to use onload.
My script.js:
function myfunction(lista) {
lista=lista
for (i=0; i<lista.length; i++) {
var canvas = document.getElementById('componenti_canvas'+i);
var ctx = canvas.getContext("2d");
var base = new Image();
base.onload = function() {
ctx.drawImage(base, 0, 0);
};
base.src = lista[i];
ctx.scale(0.5,0.5);
};
};
It draws only the last image on the last canvas (I have many canvas and I draw an image for each).
This will not work because you keep overwriting the image for every iteration of the loop. There is only one variable called base, it can only hold one image so all the ones before it are lost.
function myfunction(lista) {
lista=lista
for (i=0; i<lista.length; i++) {
var canvas = document.getElementById('componenti_canvas'+i);
var ctx = canvas.getContext("2d");
var base = new Image(); // second and more loops you over write base
base.onload = function() {
ctx.drawImage(base, 0, 0); // when it load only the last image is in base
// there is only one var called base so it
// can not hold more than one image
};
base.src = lista[i];
ctx.scale(0.5,0.5);
};
};
Use a function to wrap all the required vars so that you create a unique set for each image.
function myfunction(lista) {
lista.forEach((name,i)=>{ // each time the call back is called a
// new set of variables are created to
// store each unique image.
var base = new Image();
base.src = name;
base.onload = function() { ctx.drawImage(base, 0, 0); };
var canvas = document.getElementById('componenti_canvas'+i);
var ctx = canvas.getContext("2d");
ctx.scale(0.5,0.5);
});
}

Optimizing performance of a javascript image animation

I've got a question in regards to javascript and dynamically displaying images to
form an animation.
The pictures I have are around 1360x768 in size and quite big despite being .png pics.
I've come up with a code for switching out the pics dynamically, but even run on a local
webserver it is too slow (thus sometimes I see the pic being built).
So my question is: is there a better way to do this than dynamically switching out
the "src" part of the image tag, or is there something else that could be done in combination with that, to make sure that the user doesn't have any strange phenomenons
on the client?
<script>
var title_index = 0;
function display_title()
{
document.getElementById('picture').src=
"pics/title_" + title_index + '.png';
if (title_index < 100) {
title_index = title_index + 5;
setTimeout(display_title,3000);
}
}
</script>
<body onload="setTimeout(display_image,3000)">
<image id="picture" src="pic/title_0.png"/>
</body>
Thanks.
I've had this problem too, even when preloading the images into the cache,
Google's The Hobbit experiment does something interesting. They do low resolution while animating and switch it for a hiresolution if you "pause" (stop scolling in the case of The Hobbit experiment). They also use the HTML5 canvas tag to smooth out the animation.
Here's their blog post about their method:
http://www.html5rocks.com/en/tutorials/casestudies/hobbit-front-end/
Their end product:
http://middle-earth.thehobbit.com
Edit:
Pre loading example:
<!Doctype html>
<head>
<title>test</title>
</head>
<body>
<canvas id="myCanvas" width="1360" height="768"></canvas>
<script type="text/javascript">
var images = {};
var loadedImages = 0;
var numImages = 0;
var context = '';
function loadImages(sources, callback)
{
// get num of sources
for(var src in sources)
{
numImages++;
}
for(var src in sources)
{
images[src] = new Image();
images[src].onload = function()
{
if(++loadedImages >= numImages)
{
callback(images);
}
};
images[src].src = sources[src];
}
}
var canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
var sources =
{
frame0: 'http://piggyandmoo.com/0001.png',
frame1: 'http://piggyandmoo.com/0002.png',
frame2: 'http://piggyandmoo.com/0003.png',
frame3: 'http://piggyandmoo.com/0004.png',
frame4: 'http://piggyandmoo.com/0005.png',
frame5: 'http://piggyandmoo.com/0006.png',
frame5: 'http://piggyandmoo.com/0007.png',
frame5: 'http://piggyandmoo.com/0008.png',
frame5: 'http://piggyandmoo.com/0009.png'
};
var width = 1360;
var height = 768;
var inter = '';
var i = 0;
function next_frame()
{
if(numImages > i)
{
context.drawImage(images['frame' + (i++)], 0, 0);
}
else
{
clearInterval(inter);
}
}
loadImages(sources, function(images)
{
//animate using set_timeout or some such...
inter = setInterval(function()
{
next_frame();
}, 1000);
});
</script>
</body>
Code modified from: www.html5canvastutorials.com/tutorials/html5-canvas-image-loader/
You could overcome this issue by preloading the images on page load. This means that the images would then be stored in memory and immediately available to you. Take a look at the following:
JavaScript Preloading Images
http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

How can i play a gif like 9 gag?

http://www.9gag.com
I want pause and play a gif,like the 9gag,
how can i do that?
I know I have to use one. Jpg and. Gif but I tried a few things but did not work
I found this function
function is_gif_image(i) {
return /^(?!data:).*\.gif/i.test(i.src);
}
function freeze_gif(i) {
var c = document.createElement('canvas');
var w = c.width = i.width;
var h = c.height = i.height;
c.getContext('2d').drawImage(i, 0, 0, w, h);
try {
i.src = c.toDataURL("image/gif"); // if possible, retain all css aspects
} catch(e) { // cross-domain -- mimic original with all its tag attributes
for (var j = 0, a; a = i.attributes[j]; j++)
c.setAttribute(a.name, a.value);
i.parentNode.replaceChild(c, i);
}
}
function unfreeze_gif(id, src) {
i = document.getElementById(id);
i.src = src;
}
but i dont know how to use on the HTML
Can someone give me an example? with HTML , CSS E JS (or Jquery) ?
Thanks
It's just 2 versions of the image: One static JPG, one moving GIF.
Here's a fiddle that mimic the behaviour: http://jsfiddle.net/bortao/QADeM/
JS
$(".gif-post").on("click", function () {
var $this = $(this);
var img = $this.find("img"); // Find the image element
if (!this.playing) {
this.playing = true; // Set or create a variable
img.attr("src", img.attr("src").replace(".jpg", "a.gif"));
$this.find(".play").hide(); // Hide the overlay
} else {
this.playing = false;
img.attr("src", img.attr("src").replace("a.gif", ".jpg"));
$this.find(".play").show();
}
});
I was actually working on a 9gag clone myself, so i was searching as well for a gif player.
You can use this one: http://freezeframe.chrisantonellis.com/
All you have to do for this one is include the javascript and in the .gif link and add the following class: "freezeframe"
There is also this one: http://quickleft.com/blog/embeddable-animated-gifs-with-controls-just-in-time-for-christmas
I haven't used it, but it seems very interesting.

How to detect onload event of image which was loaded in custom object

I am creating a sample program to display an image on canvas but would like to enclose actual drawing process into a custom object.
The following code won't show the image as pictFrame.img.onload can't catch onload event of image file. Chrome console says "TypeError: Cannot set property 'onload' of undefined" with the expression although it can correctly evaluate pictFrame.img.src or pictFrame.img.height.
How should I detect image loading which is being initiated when the object is created?
<html>
<head>
<script type="text/javascript">
function pictFrame(context, imgsrc, pos_x, pos_y, size_x, size_y)
{
this.context = context;
this.img = new Image();
this.img.src = imgsrc;
this.pos_x = pos_x;
this.pos_y = pos_y;
this.size_x = size_x;
this.size_y = size_y;
this.draw = function() {
this.context.drawImage(this.img, this.pos_x, this.pos_y, this.size_x, this.size_y);
};
}
// These variables must live while the page is being displayed.
// Therefore, they can't be defined within window.onload function.
var canvas;
var context;
var pictFrame;
window.onload = function()
{
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
pictFrame = new pictFrame(context, "darwin.jpg", 10, 10, 200, 200);
};
pictFrame.img.onload = function() // Can't catch onload event
{
pictFrame.draw();
}
</script>
</head>
<body>
<canvas id="canvas" width="500" height="300"></canvas>
</body>
</html>
Its because you are calling before pictFrame gets instantiated. You get this in chrome,
Uncaught TypeError: Cannot set property 'onload' of undefined
do like below instead,
window.onload = function()
{
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
pictFrame = new pictFrame(context, "images/bahu.png", 10, 10, 200, 200);
console.log("called");
pictFrame.img.onload = function()
{
console.log(" onload called");
pictFrame.draw();
}
};
I mean, do onload call after window.onload has finished instead of calling it before.

HTML Canvas not displaying image

Im sure this has got to be something simple that I am overlooking, but I can't seem to get my canvas to display an jpg stored on the server.
<img id="test_img" alt="test" src="/media/tmp/a4c1117e-c310-4b39-98cc-43e1feb64216.jpg"/>
<canvas id="user_photo" style="position:relative;"></canvas>
<script type="text/javascript">
var image = new Image();
image.src = "/media/tmp/a4c1117e-c310-4b39-98cc-43e1feb64216.jpg";
var pic = document.getElementById("user_photo");
pic.getContext('2d').drawImage(image, 0, 0);
</script>
the <img> displays as expected, however the canvas is blank, though it does seem to have the correct dimensions. Any one see what I'm doing wrong?
My tired eyes will appreciate any help.
Thanks
you may want to use the following approach
image.onload = function() {
pic.getContext('2d').drawImage(image, 0,0);
}
so you ensure that the image is loaded when trying to draw it.
var initialFloorplanWidth = 0;
var initialFloorplanHeight = 0;
var canvasImage = new Image();
documentReady = function () {
preloadFloorplan();
}
preloadFloorplan = function () {
onLoad = function () {
initialFloorplanHeight = canvasImage.height;
initialFloorplanWidth = canvasImage.width;
var canvasHtml = '<canvas id="MainCanvas" width="' + initialFloorplanWidth + '" height="' + initialFloorplanHeight + '">Canevas non supportés</canvas>';
$("#MainContainer").append(canvasHtml);
var canvas = $("#MainCanvas")[0];
var canvasContext = canvas.getContext("2d");
canvasContext.drawImage(canvasImage, 0, 0);
}
canvasImage.onload = onLoad;
canvasImage.src = initialFloorplan;
}
This code works well.
Try doing that when the document is loaded. I have a feeling your code is running before the image is available. You can also detect when the img itself is loaded. See this.
Maybe it's something to do with the rest of your code. Is "user_photo" identified in the code?

Categories

Resources