Lets build a simple image gallery application quickly, using HTML5’s canvas.
Demo
index.html and myStyle.css file content are same as Linear Gradients in Canvas: HTML5
JavaScript file: Array Element
myScript.js
var myImages = [ 'images/1.png', 'images/2.jpg', 'images/3.jpg', 'images/4.jpg', 'images/5.jpg', 'images/6.jpg', 'images/technotip.jpg' ];
We put some images inside images folder. Create an array and have the paths of all the images inside the array: myImages.
JavaScript file: Creating and Setting Image properties on the fly
myScript.js
var img = document.createElement("img"); img.setAttribute('width', context.canvas.width); img.setAttribute('height', context.canvas.height); img.setAttribute('src', myImages[i++]);
We create img tag on the fly by using createElement() method. And by using setAttribute() method, we set the image tag’s width, height and it’s source(i.e., src). We fetch the image path from the array myImages and loop through the array elements with the help of an index variable i.
JavaScript file: drawImage and setInterval
myScript.js
setInterval(function(){ img.setAttribute('src', myImages[i++]); img.onload = function(){ if(i >= myImages.length) { i = 0; } context.drawImage(img, 0, 0, context.canvas.width, context.canvas.height); } }, 2000);
For every 2 seconds delay, the anonymous function sets the image source and checks if the index has exceeded the actual length of the myImages array, if it exceeds, we set it back to the start index 0. Now using drawImage() method, we draw the image on to the canvas.
Simple Image Gallery Application using Canvas: HTML5
[youtube https://www.youtube.com/watch?v=qvaKJFIbWuo]
Note: If you’re using separate methods to write the setInterval() calls, then make sure the variables corresponding to canvas, context, image array and the index variables are in global scope.
JavaScript file: Full Free Code!
myScript.js
window.onload = canvas; function canvas() { var myCanvas = document.getElementById("myCanvas"); if( myCanvas && myCanvas.getContext("2d") ) { var context = myCanvas.getContext("2d"); var myImages = [ 'images/1.png', 'images/2.jpg', 'images/3.jpg', 'images/4.jpg', 'images/5.jpg', 'images/6.jpg', 'images/technotip.jpg' ]; var img = document.createElement("img"); var i = 0; img.setAttribute('width', context.canvas.width); img.setAttribute('height', context.canvas.height); setInterval(function(){ img.setAttribute('src', myImages[i++]); img.onload = function(){ if(i >= myImages.length) { i = 0; } context.drawImage(img, 0, 0, context.canvas.width, context.canvas.height); } }, 2000); } }
This is a simple image gallery application, and you can build upon this to give some transition effects and make it look lot cooler than this!