HTML and CSS Reference
In-Depth Information
context.putImageData(imagedata, 0, 0);
}());
};
</script>
</body>
</html>
When you run this script, you should see an effect that can be described as a “psychedelic flashlight.” The
color values are passed to some trigonometry functions and scaled to fit within the range of color values.
We're just having fun here, so don't worry about what these functions are doing exactly, just understand
that we're trying to get some interesting looking colors. Feel free to change the values around and
experiment with your own color combinations.
For the last example in this chapter, we bring it back home to the first example: the simple drawing
application ( 01-drawing-app.html ). But this time, we create a spray paint effect by drawing directly to
the pixels. Here's the code (example 16-spray-paint.html ):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Spray Paint</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),
imagedata = context.getImageData(0, 0, canvas.width, canvas.height),
pixels = imagedata.data,
brush_size = 25,
brush_density = 50,
brush_color;
canvas.addEventListener('mousedown', function () {
brush_color = utils.parseColor(Math.random() * 0xffffff, true); //to number
canvas.addEventListener('mousemove', onMouseMove, false);
}, false);
canvas.addEventListener('mouseup', function () {
canvas.removeEventListener('mousemove', onMouseMove, false);
}, false);
function onMouseMove () {
//loop over each brush point
for (var i = 0; i < brush_density; i++) {
var angle = Math.random() * Math.PI * 2,
radius = Math.random() * brush_size,
xpos = (mouse.x + Math.cos(angle) * radius) | 0, //remove decimal
Search WWH ::




Custom Search