<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>
JavaScript Painting with Canvas
I spent some time today messing with JavaScript canvas stuff. Here's a simple paint snippet. Enjoy.
Labels:
javascript
Subscribe to:
Post Comments (Atom)
5 comments:
Thank you for this. I was having trouble finding a simple implementation of this sort of thing.
You're welcome. I was having trouble finding it too :)
It doesn't seem to work in IE. Is canvas tag Mozilla, Chrome specific?
Yes, the canvas tag is part of HTML5 and not supported in IE without a plugin.
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