Book Image

Canvas Cookbook

Book Image

Canvas Cookbook

Overview of this book

With the growing popularity of HTML5 Canvas, this book offers tailored recipes to help you develop portable applications, presentations, and games. The recipes are simple yet creative and build on each other. At every step, the book inspires the reader to develop his/her own recipe. From basic to advanced, every aspect of Canvas API has been covered to guide readers to develop their own application, presentation, or game.
Table of Contents (16 chapters)
Canvas Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Creating a pixelated image focus


Here is a fancy way to focus an image. In this recipe, we'll explore the art of image pixelation by looping through an algorithm that reduces the pixelation until it's completely focused:

How to do it

The recipe is as follows:

The HTML code:

<html>
<head>
<script src="pixelation.js"></script> 
</head>
<body onload="init();">
<canvas id="myCanvas" width="578" height="400"></canvas>
</body>
</html>

The JavaScript code:

function init()
{
var pixelation = 40;

function focusImage(context, imageObj, sourceWidth, sourceHeight, destX, destY) {
var sourceX = destX;
var sourceY = destY;

var imageData = context.getImageData(sourceX, sourceY, sourceWidth, sourceHeight);
var data = imageData.data;

for(var y = 0; y <sourceHeight; y += pixelation) {
for(var x = 0; x <sourceWidth; x += pixelation) {
var red = data[((sourceWidth * y) + x) * 4];
var green = data[((sourceWidth * y) + x) * 4 + 1];
var blue = data...