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>

9 comments:

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

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

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

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

    ReplyDelete
  5. 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.

    ReplyDelete
  6. To support touch devices like iPhones and iPads, just add the following

    canvas.ontouchstart = function(e) {
    var first = e.changedTouches[0];

    x = first.clientX;
    y = first.clientY;
    ctx.moveTo(x, y);
    }

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

    canvas.ontouchmove = function(e) {
    if (x == null || y == null) {
    return;
    }
    var first = e.changedTouches[0];

    x = first.pageX;
    y = first.pageY;
    x -= canvas.offsetLeft;
    y -= canvas.offsetTop;
    ctx.lineTo(x, y);
    ctx.stroke();
    ctx.moveTo(x, y);
    }

    ReplyDelete
  7. If you dont want to think how to realize functions like onmousemove() with some objects on canvas, you can use javascript frameworks, like jCanvaScript. Its very simple and have good documentation.

    ReplyDelete
  8. how can I submit it to a Mysql data base?

    or how can I save it as an image

    ReplyDelete