HTML5 canvas photo slide show issue - javascript

Hi I found this code on Stackoverflow for a canvas photo slide show, but I'm just wondering how to make the transitions between images slower?
var loaded = 0, numOfImages = 4;
//first part of chain, invoke async load
var image0 = document.createElement('img'); //this will work in new Chrome
var image1 = document.createElement('img'); //instead of new Image
var image2 = document.createElement('img');
var image3 = document.createElement('img');
//common event handler when images has loaded with counter
//to know that all images has loaded
image0.onload = image1.onload =
image2.onload = image3.onload = function(e) {
loaded+;
if (loaded === numOfImages)
draw(); // <-- second part of chain, invoke loop
}
//show if any error occurs
image0.onerror = image1.onerror =
image2.onerror = image3.onerror = function(e) {
console.log(e);
}
//invoke async loading... you can put these four into your
//window.onload if you want to
image0.src = "img/pic1.jpg";
image1.src = "img/pic2.jpg";
image2.src = "img/pic3.jpg";
image3.src = "img/pic4.jpg";
// this is the main function
function draw() {
var images = new Array(image0, image1, image2, image3),
counter = 0,
maxNum = images.length - 1,
myCanvas = document.getElementById('myCanvas'),
ctx = myCanvas.getContext('2d'),
me = this; //this we need for setTimeout()
//third part of chain, have a function to invoke by setTimeout
this._draw = function() {
//if the next image will cover the canvas
//there is no real need to clear the canvas first.
//I'll leave it here as you ask for this specifically
ctx.clearRect(0, 0, myCanvas.width, myCanvas.height)
ctx.drawImage(images[counter++], 0, 0);
if (counter > maxNum) counter = 0;
setTimeout(me._draw, 1000); //here we use me instead of this
}
this._draw(); //START the loop
}
but I'm just wondering how to make the transitions between images slower?

You have a typo in your onload methods:
loaded++; // instead of loaded+;
The setTimeout controls the delay until me._draw is called again.
For example 3 seconds of delay would be 3000 milliseconds, like this:
setTimeout(me._draw, 3000);
If you instead want an actual transition, you could use something like this:
changing images on a canvas with transitions
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/m8E6J/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
<script src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var loaded = 0, numOfImages = 4;
//first part of chain, invoke async load
var image0 = document.createElement('img'); //this will work in new Chrome
var image1 = document.createElement('img'); //instead of new Image
var image2 = document.createElement('img');
var image3 = document.createElement('img');
//common event handler when images has loaded with counter
//to know that all images has loaded
image0.onload = image1.onload =
image2.onload = image3.onload = function(e) {
loaded++;
if (loaded === numOfImages)
draw(); // <-- second part of chain, invoke loop
}
//show if any error occurs
image0.onerror = image1.onerror =
image2.onerror = image3.onerror = function(e) {
console.log(e);
}
//invoke async loading... you can put these four into your
//window.onload if you want to
image0.src = "https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-1.jpg";
image1.src = "https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-2.jpg";
image2.src = "https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-3.jpg";
image3.src = "https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-4.jpg";
// this is the main function
function draw() {
var images = new Array(image0, image1, image2, image3),
counter = 0,
maxNum = images.length - 1,
myCanvas = document.getElementById('myCanvas'),
ctx = myCanvas.getContext('2d'),
me = this; //this we need for setTimeout()
//third part of chain, have a function to invoke by setTimeout
this._draw = function() {
//if the next image will cover the canvas
//there is no real need to clear the canvas first.
//I'll leave it here as you ask for this specifically
ctx.clearRect(0, 0, myCanvas.width, myCanvas.height)
ctx.drawImage(images[counter++], 0, 0);
if (counter > maxNum) counter = 0;
setTimeout(me._draw, 3000); //here we use me instead of this
}
this._draw(); //START the loop
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="myCanvas" width=600 height=400></canvas>
</body>
</html>

Related

Canvas Clearing After Multiple DrawImage

I have been trying to draw a tile-like map to the canvas, although if i try to draw the same sprite twice, it will only render the final call of drawImage. Here is my code if it helps :
window.onload = function(){
function get(id){
return document.getElementById(id);
}
var canvas = get("canvas");
ctx = canvas.getContext("2d");
canvas.width = 160;
canvas.height = 160;
grass = new Image();
water = new Image();
grass.src = "res/Grass.png";
water.src = "res/Water.png";
path = {
draw: function(image,X,Y){
X = (X*32)-32;
Y = (Y*32)-32;
image.onload = function(){
ctx.drawImage(image,X,Y);
}
},
}
path.draw(water,2,2);
path.draw(grass,1,2);
path.draw(grass,1,1);
path.draw(water,2,1);
}
You're overwriting onload on the image next time you call it.
Think of it this way:
var image = {
onload: null
};
// Wait for the image to "load"
// Remember, onload is asynchronous so it won't be called until the rest of
// your code is done and the image is loaded
setTimeout(function() {
image.onload();
}, 500);
image.onload = function() {
console.log('I will never be called');
};
image.onload = function() {
console.log('I overwrite the previous one');
};
Instead, you might try waiting for your images to load then do the rest of your logic.
var numOfImagesLoading = 0;
var firstImage = new Image();
var secondImage = new Image();
// This is called when an image finishes loading
function onLoad() {
numOfImagesLoading -= 1;
if (numOfImagesLoading === 0) {
doStuff();
}
}
function doStuff() {
// This is where you can use your images
document.body.appendChild(firstImage);
document.body.appendChild(secondImage);
}
firstImage.src = 'http://placehold.it/100x100';
firstImage.onload = onLoad;
numOfImagesLoading += 1;
secondImage.src = 'http://placehold.it/200x200';
secondImage.onload = onLoad;
numOfImagesLoading += 1;

Load Image in only one canvas

UPDATED
I have an HTML code below:
<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>
I have a function below:
var Context;
function onSign(canvas){
var ctx = document.getElementById(canvas).getContext('2d');
SigWebSetDisplayTarget(ctx);
tmr = setInterval(SigWebRefresh, 50);
}
function SigWebSetDisplayTarget( obj ){
Context = obj;
}
I called the function OnSign twice with different canvas id parameters.
OnSign('canvas1');
OnSign('canvas2');
Below is the SigWebRefresh function that is repeatedly called for a reason.
function SigWebRefresh(){
xhr2 = new XMLHttpRequest();
requests.push(xhr2);
xhr2.open("GET", baseUri + "SigImage/0", true );
xhr2.responseType = "blob"
xhr2.onload = function (){
var img = new Image();
img.src = 'image.jpg';
img.onload = function (){
Ctx.drawImage(img, 0, 0);
revokeBlobURL( img.src );
img = null;
}
}
xhr2.send(null);
}
After that, I noticed that the two canvas was being updated and the image is loaded to the 2 canvas. Why is it? I have to load the image, only to the last canvas I supplied with the function OnSign. Where am I missing?
var Context; is declared in global scope
OnSign('canvas1');
OnSign('canvas2');
Doing so you are assigning value of canvas number two.
Update: http://jsfiddle.net/bmynvtLd/2/
This is what you desired to update both contexts? if yes this is how you pass the parameter to setInterval function: setInterval(function() {SigWebRefresh(ctx)}, 300);
running example:
var images = ['http://img09.deviantart.net/6d02/i/2015/284/0/b/beginning_autumn_by_weissglut-d9cssxw.jpg', 'http://orig06.deviantart.net/063c/f/2013/105/3/6/free_crystal_icons_by_aha_soft_icons-d61tfi1.png', 'http://img15.deviantart.net/b126/i/2015/118/c/1/this_small_tree_by_weissglut-d8re8q7.jpg', 'http://img00.deviantart.net/84f8/i/2015/284/d/f/nuclear_light_by_noro8-d9cs4u6.jpg'];
function OnSign(canvas){
var ctx = document.getElementById(canvas).getContext('2d');
tmr = setInterval(function() {SigWebRefresh(ctx)}, 300);
}
OnSign('canvas1');
OnSign('canvas2');
var index = 0;
function MyIndex()
{
// console.log(index);
index = images.length == index ? 0 : index+1;
return images[index];
}
function SigWebRefresh(Context){
var img = new Image();
img.src = MyIndex();
img.onload = function (){
Context.drawImage(img, 0, 0);
img = null;
}
}

javascript drawImage() issues

Currently having some issues with drawImage();. Namely it wont actually draw. I tried it out with fillRect(); and it worked aswell as putting the drawImage(); inside the the onload function aswell (which worked).
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 640;
canvas.height = 400;
document.body.appendChild(canvas);
var tileArray = [
[0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,1,1,1,1,0,0,1,0,0,0],
[0,0,0,1,1,1,1,0,1,1,1,0,0],
[0,0,0,1,1,1,0,0,0,0,1,1,0],
[0,0,0,1,1,1,0,0,0,0,0,0,0],
[0,0,0,1,1,1,0,0,0,0,0,0,0],
[0,0,0,0,1,1,1,0,0,0,0,0,0],
[0,0,0,0,1,1,1,0,0,0,0,0,0],
[0,0,0,0,0,1,1,1,0,0,0,0,0],
[0,0,0,0,0,0,1,1,0,0,0,0,0]
];
var grassReady = false;
var grass = new Image();
grass.onload = function() {
grassReady = true;
};
grass.src = "images/grass.png";
var sandReady = false;
var sand = new Image();
sand.onload = function() {
sandReady = true;
};
sand.src = "images/sand.png";
var posX = 0;
var posY = 0;
if(grassReady) {
ctx.drawImage(grass, posX, posY);
}
Any pointers as to why this is would be greatly appreciated and I appologize in advance if messed up the code section in anyway. I went through other similar posts and coulden't find a solution that seemed to work.
As #Suman Bogati correctly says, you must wait for your images to load before using them in drawImage.
A Demo: http://jsfiddle.net/m1erickson/jGPGj/
Here's an image loader that preloads all images and then calls the start() function where you can use drawImage because all the images are fully loaded.
var imageURLs=[]; // put the paths to your images here
var imagesOK=0;
var imgs=[];
imageURLs.push("images/grass.png");
imageURLs.push("images/sand.png");
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
function start(){
// the imgs[] array holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
// grass.png is in imgs[0]
// sand.png is in imgs[1]
}
This statement ctx.drawImage(); should be inside the grass.onload = function() {} function, something like
grass.onload = function() {
ctx.drawImage(grass, posX, posY);
}
If you define drawImage() outside the grass.onload() function, then that statment would executed first, so at that point grassReady is false, So the condition is not satisfied.
Bascially it's related to asynchronous concept.
Your code is running into order
1) First
var grassReady = false;
if(grassReady) {
//grassReady is false, this condition is not satisfied
ctx.drawImage(grass, posX, posY);
}
2) Second
grass.onload = function() {
grassReady = true;
};

Fading a loaded image into Canvas with drawImage

This question about crossfading images already gave an answer to the crossfading solution in Canvas. I am trying to do the same thing, only difference is that i am trying to fade images that are loaded on runtime.
The images are loaded propperly but no fade is visible. Is this not working because of the loaded images? Thanks.
HTML
<div id="wrapper">
<canvas id="bg1"></canvas>
<canvas id="bg2"></canvas>
</div>
JS
var toggle = true;
var canvas = document.getElementById('bg1');
canvas.width = $(document).width();
canvas.height = $(document).height();
var ctx = canvas.getContext('2d');
var canvas2 = document.getElementById('bg2');
canvas2.width = $(document).width();
canvas2.height = $(document).height();
var ctx2 = canvas2.getContext('2d');
var image = new Image();
image.src = 'download1.jpg';
var image2 = new Image();
image2.src = 'download2.jpg';
image.onload = function() {
ctx.drawImage(image, 0, 0, 200, 100);
ctx2.drawImage(image2, 0, 0, 200, 100);
};
$('#wrapper').click(function () {
if (toggle)
{
$('#bg2').fadeIn();
$('#bg1').fadeOut();
}
else
{
$('#bg1').fadeIn();
$('#bg2').fadeOut();
}
toggle = !toggle;
});
Yep, you need to give your images time to load.
But also, jQuery cannot do fadeIn/fadeout on a canvas element so you will have to do that manually.
Demo: http://jsfiddle.net/m1erickson/zw9S4/
Code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
$("#fade").hide();
var imageURLs=[]; // put the paths to your images here
var imagesOK=0;
var imgs=[];
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-1.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-2.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-3.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-4.jpg");
loadAllImages();
//
function loadAllImages(){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
$("#fade").show();
ctx.drawImage(imgs[0],0,0);
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var fadeOutIndex=imgs.length-1;
var fadeInIndex=0;
var fadePct=0;
function animateFade(){
if(fadePct>100){return;}
requestAnimationFrame(animateFade);
ctx.clearRect(0,0,canvas.width,canvas.height);
draw(imgs[fadeInIndex],fadePct/100);
draw(imgs[fadeOutIndex],(1-fadePct/100));
fadePct++;
}
function draw(img,opacity){
ctx.save();
ctx.globalAlpha=opacity;
ctx.drawImage(img,0,0);
ctx.restore();
}
$("#fade").click(function(){
fadePct=0;
if(++fadeOutIndex == imgs.length){fadeOutIndex=0;}
if(++fadeInIndex == imgs.length){fadeInIndex=0;}
animateFade();
});
}); // end $(function(){});
</script>
</head>
<body>
<button id="fade">Fade to next Image</button><br>
<canvas id="canvas" width=204 height=204></canvas><br>
</body>
</html>
Try to fade in/out the images directly on the canvas instead of fading in and out the canvas elements (or there is not really any point using the canvas as you could use image elements instead).
First, of course, wait for the images to load:
var isBusy = false, /// for fade loop
count = 2; /// number of images to load
image = new Image();
image2 = new Image();
/// setup load handler
image.onload = image2.onload = handleLoad;
image.src = 'download1.jpg';
image2.src = 'download2.jpg';
function handleLoad() {
count--;
if (count === 0) {
/// when loaded draw a single image onto canvas
ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height);
}
};
Now we can change the click handler a little bit around and use canvas only to do the fade in of the next image:
$('#wrapper').click(function () {
var img, /// current image to fade in
opacity = 0; /// current globalAlpha of canvas
/// if we're in a fade exit until done
if (isBusy) return;
isBusy = true;
/// what image to use
img = toggle ? image2 : image;
/// fade in
(function fadeIn() {
/// set alpha
ctx.globalAlpha = opacity;
/// draw image with current alpha
ctx.drawImage(img, 0, 0, ctx.canvas.width, ctx.canvas.height);
/// increase alpha to 1, then exit resetting isBusy flag
opacity += 0.02;
if (opacity < 1)
requestAnimationFrame(fadeIn);
else
isBusy = false;
})();
toggle = !toggle;
});
Online demo
Hope this helps.

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