Ubersimple Canvas Drawing App
A very very stripped-down version of a larger app. I asked a question on Stack Overflow because the mouse coordinates were drifting on repeated line drawings. Turns out I was translating by 0.5px each time for reasons I can no longer remember; the offending line remains but is commented out, for great justice.
HTML
<!-- canvas is so big for various reasons -->
<img id="baseImg" src="http://i.stack.imgur.com/uVQ0X.jpg" width="100%" height="100%" style="visibility:hidden"/>
<canvas id="canvas" width="400" height="400"></canvas>
<div id="cover"></div>
CSS
#canvas {
position: fixed;
width: 400px;
height: 400px;
top: 0px;
left: 40px;
overflow: hidden;
outline: 1px dashed orange;
}
#cover {
position: fixed;
width: 400px;
height: 400px;
top: 0px;
left: 40px;
background-color: transparent;
/* Background 1px clear image for IE */
background-image: url('data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
}
JavaScript
var offsetX = 0, offsetY = 0;
var currentMouseCoords = {
x : 0,
y : 0
};
var drawPing = null;
var ctx = null;
$('#cover').mousedown(function (event) {
event.preventDefault();
var f = $(this).offset();
offsetX = f.left;
offsetY = f.top;
currentMouseCoords.x = event.pageX - offsetX;
currentMouseCoords.y = event.pageY - offsetY;
drawStart();
if (!drawPing) {
drawPing = setInterval(draw, 10);
}
})
.mousemove(function (event) {
currentMouseCoords.x = event.pageX - offsetX;
currentMouseCoords.y = event.pageY - offsetY;
})
.mouseout(function (event) {
//When mouse leaves canvas, quit drawing
drawEnd();
})
.mouseup(function (event) {
//When mouse leaves canvas, quit drawing
drawEnd();
})
/* Functions that perform the actual drawing */
function drawStart () {
//Get canvas context
ctx = document.getElementById('canvas').getContext("2d");
ctx.save();
var imgBase = new Image();
imgBase.src = document.getElementById('baseImg').src();
//imgBase.onload = function() {
ctx.save();
ctx.globalCompositeOperation = 'source-in';
ctx.drawImage(imgBase, 0, 0);
ctx.restore();
//};
ctx.drawImage(imgBase, 0, 0);
// ctx.translate(0.5,0.5);
//Set styles
ctx.strokeStyle = '#333333';
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.lineWidth = 10;
//Begin path
ctx.beginPath();
ctx.moveTo(
currentMouseCoords.x,
currentMouseCoords.y
);
}
function draw () {
ctx.lineTo(
currentMouseCoords.x,
currentMouseCoords.y
);
ctx.stroke();
}
function drawEnd () {
clearInterval(drawPing);
drawPing = null;
if (ctx) {
ctx.closePath();
ctx = null;
}
}