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
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
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!
window.onload = canvas;
function canvas()
{
var myCanvas = document.getElementById("myCanvas");
if( myCanvas && myCanvas.getContext("2d") )
{
var context = myCanvas.getContext("2d");
var imgSrc = document.getElementById("img");
context.drawImage(imgSrc, 0, 0, 350, 350);
var image = context.getImageData(0, 0, 350, 350);
var pixel = image.data;
var init = 1;
while(init < context.canvas.height){
for(var j = 0; j < 5; j++)
{
var row = (init + j) * context.canvas.width * 4;
for(var i = 0; i < context.canvas.width * 4; i += 4)
{
pixel[row + i] = 255 - pixel[row + i]; //red
pixel[row + i + 1]= 255 - pixel[row + i + 1]; //green
pixel[row + i + 2] = 255 - pixel[row + i + 2]; //blue
}
}
init += 15;
}
context.putImageData(image, 0, 0, 0, 0, 175, 350);
}
}
window.onload = canvas;
function canvas()
{
var myCanvas = document.getElementById("myCanvas");
if( myCanvas && myCanvas.getContext("2d") )
{
var context = myCanvas.getContext("2d");
var imgSrc = document.getElementById("img");
context.drawImage(imgSrc, 0, 0, 350, 350);
var image = context.getImageData(0, 0, 350, 350);
var pixel = image.data;
var init = 1;
while(init < context.canvas.height){
for(var j = 0; j < 5; j++)
{
var row = (init + j) * context.canvas.width * 4;
for(var i = 0; i < context.canvas.width * 4; i += 4)
{ pixel[row + i] = 255 - pixel[row + i]; //red pixel[row + i + 1]= 255 - pixel[row + i + 1]; //green pixel[row + i + 2] = 255 - pixel[row + i + 2]; //blue
}
}
init += 15;
}
context.putImageData(image, 0, 0, 0, 0, 175, 350);
}
}
We draw an image on to the canvas using drawImage() method. Once we draw the image, we get all the raw pixel data of the image using getImageData() method. Extract it’s data property(it’s a single dimension array of raw pixel data) and store it inside a variable called pixel.
To process the image data, we proceed executing until init is lesser than the height of the canvas. Inside the while loop we calculate the current row and it’s width and iterate till the entire row pixels are manipulated. We change the values of RGB and assign it back to those pixels selected using the loop.
Once the control is out of while loop, we put back the image using putImageData() method. We also play around with the optional parameters and put back a portion of the manipulated data on to the canvas.
Today lets learn in-depth about drawImage() method of HTML5.
Using drawImage() method we can draw a portion or an entire image, fetch a video frame, fetch an image(drawing) from another canvas element. We can grab – re-size, crop etc an image, video or something present on another canvas.
drawImage() syntax
Basic: drawImage(imgSrc, dx, dy);
imgSrc – image soruce.
Top Right Corner Position dx – destination/main canvas x-axis value. dy – destination/main canvas y-axis value.
drawImage(imgSrc, dx, dy, dw, dy);
dw – destination width to which the image should fit into. [optional] dh – destination height to which the image should fit into. [optional]
drawImage(imgSrc, sx, sy, sw, sh, dx, dy, dw, dy); sx – source image or video or another canvas elements x-axis value. [optional] sy – source image or video or another canvas elements y-axis value. [optional]
sw – selecting source image or video or another canvas’s width. [optional] sh – selecting source image or video or another canvas’s height. [optional]
sx – The x coördinate where to start clipping(optional). sy – The y coördinate where to start clipping(optional). x – The x coördinate where to place the image on the canvas. y – The y coördinate where to place the image on the canvas. swidth– The width of the clipped image(optional). sheight– The height of the clipped image(optional).
stretch or reduce the image width– The width of the image to use(optional). height– The height of the image to use(optional) .
Here we have 2 canvas elements. 1 image and 1 video. Image and video are set to display none, so that they’re not shown below or besides the canvas element on the html document. Our main canvas with the id myCanvas has a width of 500px and a height of 300px. This is the canvas on which we draw image by fetching it from an image file or a video frame or another canvas element.
CSS file myStyle.css
1
2
3
canvas {
border: 2px dotted black;
}
canvas {
border: 2px dotted black;
}
We assign 2px black dotted border to the canvas present on our HTML page.
Fetch the image by its id. Using drawImage() method, we grab a portion of the image and fit display it on the main canvas.
JavaScript file: Fetching video frame myScript.js
1
2
3
4
5
6
7
8
9
10
11
12
var myVideo = document.getElementById("video");
myVideo.play();
setInterval(function(){
var myCanvas = document.getElementById("myCanvas");
var context = myCanvas.getContext("2d");
var myVideo = document.getElementById("video");
context.drawImage(myVideo, 30, 0, 950, 720, 0, 0, 500, 300);
}, 3000);
var myVideo = document.getElementById("video");
myVideo.play();
setInterval(function(){
var myCanvas = document.getElementById("myCanvas");
var context = myCanvas.getContext("2d");
var myVideo = document.getElementById("video");
context.drawImage(myVideo, 30, 0, 950, 720, 0, 0, 500, 300);
}, 3000);
We grab the video using its id. using play() method, we start playing the video automatically. Once the video starts playing, we set the time interval to 3 seconds and for every 3 seconds we grab the current video playback frame and display it on the specified position and in specified width and height of the main canvas.
JavaScript file: Fetching image from another canvas myScript.js
window.onload = canvas;
function canvas()
{
var myCanvas = document.getElementById("myCanvas");
if( myCanvas && myCanvas.getContext("2d") )
{
var context = myCanvas.getContext("2d");
// var myImg = document.getElementById("img");
// context.drawImage(myImg, 35, 15, 550, 550, 0, 0, 500, 300);
var second = document.getElementById("two");
var canvas2 = second.getContext("2d");
canvas2.arc(25, 25, 25, 0, 2 * Math.PI);
canvas2.fillStyle = "red";
canvas2.strokeStyle = "blue";
canvas2.fill();
canvas2.stroke();
context.drawImage(second, 0, 0, 50, 50, 120, 20, 250, 250);
var myVideo = document.getElementById("video");
myVideo.play();
setInterval(function(){
var myCanvas = document.getElementById("myCanvas");
var context = myCanvas.getContext("2d");
var myVideo = document.getElementById("video");
context.drawImage(myVideo, 30, 0, 950, 720, 0, 0, 500, 300);
}, 3000);
}
}
window.onload = canvas;
function canvas()
{
var myCanvas = document.getElementById("myCanvas");
if( myCanvas && myCanvas.getContext("2d") )
{
var context = myCanvas.getContext("2d");
// var myImg = document.getElementById("img");
// context.drawImage(myImg, 35, 15, 550, 550, 0, 0, 500, 300);
var second = document.getElementById("two");
var canvas2 = second.getContext("2d");
canvas2.arc(25, 25, 25, 0, 2 * Math.PI);
canvas2.fillStyle = "red";
canvas2.strokeStyle = "blue";
canvas2.fill();
canvas2.stroke();
context.drawImage(second, 0, 0, 50, 50, 120, 20, 250, 250);
var myVideo = document.getElementById("video");
myVideo.play();
setInterval(function(){
var myCanvas = document.getElementById("myCanvas");
var context = myCanvas.getContext("2d");
var myVideo = document.getElementById("video");
context.drawImage(myVideo, 30, 0, 950, 720, 0, 0, 500, 300);
}, 3000);
}
}
By changing the x-axis and y-axis values of source and destination, we can change position of the image and we can snatch a particular video frame or a particular part of an image or another canvas element. By using source / destination width and height we can shrink or stretch the image.
drawImage() method will be helpful in building image manipulation and video oriented applications.
Example: You can grab a particular frame image from your video and set it as it’s cover pic! Like YouTube allows video uploader to select a cover image to each video – by default, it’s fetched randomly from the uploaded video file frames.
This creates a circular clipping region, with a radius of 180px. We use drawImage() method to draw the image. Clip() method is used to create clipping region.
sx – The x coordinate where to start clipping(optional). sy – The y coordinate where to start clipping(optional). x – The x coordinate where to place the image on the canvas. y – The y coordinate where to place the image on the canvas. swidth– The width of the clipped image(optional). sheight– The height of the clipped image(optional).
stretch or reduce the image width– The width of the image to use(optional). height– The height of the image to use(optional) .
Note: By default, current clipping path is the entire canvas. Clipping path is a region inside which drawing takes place, outside which drawing has no effect. Any path can be a clipping path. You simply draw a path as normal and then call the context’s clip method to clip the region. With this clipping path, we can restrict the drawing to a particular area on the canvas.