Step 2 : In the Solution Explorer there are two files that we will primarily work with; the Default.Html file.
Step 3 : The Default.Html file is as in the following code:
Code :
<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Image Fading</title>
<style>
body
{background:white;
border:black;
cursor:crosshair
}
#mycanvas
{background:white
}
</style>
</head>
<body>
<div><h3>Image Fading Using HTML5</h3>
<input type="button" id="fade_button"value="Fade Button" />
</div>
<canvas id='mycanvas' width='650' height='450'></canvas>
<script type="text/javascript" src="fade.js">
</script>
</body>
</html>
Step 4 : The feade.js JavaScript file is as in the following code:
Code :
var img = new Image(),
mycanvas = document.getElementById('mycanvas'),
context = mycanvas.getContext('2d'),
newcanvas = document.createElement('canvas'),
offscreenContext = newcanvas.getContext('2d'),
fade_button = document.getElementById('fade_button'),
imgd,
gap = null,
imgdnewcanvas;
function incvisiblity(imgd, steps) {
var x,
dx,
nxt,
l = imgd.data.length;
for (var a = 3; a < l; a += 4) {
x = imgdnewcanvas.data[a];
if (x > 0) {
dx = imgd.data[a];
nxt = Math.ceil(x / steps);
if (dx + nxt <= x) {
imgd.data[a] += nxt;
}
else {
imgd.data[a] = x;
}
}
}
}
function startfade(context, imgd, steps, millisecondsPerStep) {
var y = 0;
for (var a = 3; a < imgd.data.length; a += 4) {
imgd.data[a] = 0;
}
gap = setInterval(function () {
y++;
if (y > steps) {
clearInterval(gap);
}
else {
incvisiblity(imgd, steps);
context.putImageData(imgd, 0, 0);
}
}, millisecondsPerStep);
}
fade_button.onclick = function () {
imgdnewcanvas = offscreenContext.getImageData(0, 0, mycanvas.width, mycanvas.height);
startfade(context, offscreenContext.getImageData(0, 0, mycanvas.width, mycanvas.height), 50, 1000 / 60);
};
img.src = 'color.jpg';
img.onload = function () {
newcanvas.width = mycanvas.width;
newcanvas.height = mycanvas.height;
offscreenContext.drawImage(img, 0, 0);
};
Step 5 : After running this code the output looks like this: