HTML and CSS Reference
In-Depth Information
You can see that we're using the distance formula from Chapter 3 to get the distance from the mouse
cursor to the current pixel. The pixel iteration is slightly different in this example; we're using a double for
loop to specify the pixel's coordinate location on the canvas element. The code here can be found in
example 15-pixel-move.html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Pixel Move</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
mouse = utils.captureMouse(canvas);
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
//draw some stripes: red, green, and blue
for (var i = 0; i < canvas.width; i += 10) {
for (var j = 0; j < canvas.height; j += 10) {
context.fillStyle = (i % 20 === 0) ? "#f00" : ((i % 30 === 0) ? "#0f0" : "#00f");
context.fillRect(i, j, 10, 10);
}
}
var imagedata = context.getImageData(0, 0, canvas.width, canvas.height),
pixels = imagedata.data;
//pixel iteration
for (var y = 0; y < imagedata.height; y += 1) {
for (var x = 0; x < imagedata.width; x += 1) {
var dx = x - mouse.x,
dy = y - mouse.y,
dist = Math.sqrt(dx * dx + dy * dy),
offset = (x + y * imagedata.width) * 4,
r = pixels[offset],
g = pixels[offset + 1],
b = pixels[offset + 2];
pixels[offset] = Math.cos(r * dist * 0.001) * 256;
pixels[offset + 1] = Math.sin(g * dist * 0.001) * 256;
pixels[offset + 2] = Math.cos(b * dist * 0.0005) * 256;
}
}
Search WWH ::




Custom Search