Chapter 6: Map, Take 1
HTML
<div id="canvas"></div>
CSS
#canvas {
background: #eee;
}
JavaScript
var canvas = document.getElementById('canvas'),
paper = new Raphael(canvas, 500, 700),
colour = 'black',
mousedown = false,
width = 1,
lastX, lastY, path, pathString;
$(canvas).mousedown(function (e) {
mousedown = true;
var x = e.offsetX,
y = e.offsetY;
pathString = 'M' + x + ' ' + y + 'l0 0';
path = paper.path(pathString);
path.attr({
'stroke': colour,
'stroke-linecap': 'round',
'stroke-linejoin': 'round',
'stroke-width': width
});
lastX = x;
lastY = y;
});
$(document).mouseup(function () {
mousedown = false;
});
$(canvas).mousemove(function (e) {
if (!mousedown) {
return;
}
var x = e.offsetX,
y = e.offsetY;
pathString += 'l' + (x - lastX) + ' ' + (y - lastY);
path.attr('path', pathString);
lastX = x;
lastY = y;
});
$(document).keydown(function (e) {
if (e.keyCode > 48 && e.keyCode < 58) {
width = e.keyCode - 48;
}
});
$('#canvascolours [data-colour]').each(function () {
var $this = $(this),
divColour = $this.data('colour');
// Change the background colour of the box
$this.css('background-color', divColour);
// Add the event listener
$this.click(function () {
colour = divColour;
});
});