JavaScript Painting with Canvas

I spent some time today messing with JavaScript canvas stuff. Here's a simple paint snippet. Enjoy.
<head>
<script>
function draw() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "black";
ctx.beginPath();

var x;
var y;

canvas.onmousedown = function(e) {
x = e.clientX;
y = e.clientY;
ctx.moveTo(x, y);
}

canvas.onmouseup = function(e) {
x = null;
y = null;
}

canvas.onmousemove = function(e) {
if (x == null || y == null) {
return;
}
x = e.clientX;
y = e.clientY;
x -= canvas.offsetLeft;
y -= canvas.offsetTop;
ctx.lineTo(x, y);
ctx.stroke();
ctx.moveTo(x, y);
}
};
</script>
</head>
<body onload="draw();">
<canvas id="canvas" width="300" height="300"
style="border: 1px solid black;"></canvas>
</body>

5 comments:

SammyIAm said...

Thank you for this. I was having trouble finding a simple implementation of this sort of thing.

Damon said...

You're welcome. I was having trouble finding it too :)

Purvi said...

It doesn't seem to work in IE. Is canvas tag Mozilla, Chrome specific?

Damon said...

Yes, the canvas tag is part of HTML5 and not supported in IE without a plugin.

Alain said...

You should put this :
x -= canvas.offsetLeft;
y -= canvas.offsetTop;
on your onmousedown.
Else, you will have a bug if you put your canvas in an other position on the screen then 0,0.

Post a Comment