In an application i’m working on it should be possible to open several div boxes and draw on each of them (like MS paint light).
I have succeeded open one box and draw on it but when I changed from canvas “id” to canvas “class” (to be able to open several boxes and paint on each of them) it stopped working. Now when I try to paint, nothing happens. What am I doing wrong?
var color = "red";
var shape = "square";
var size = 10;
var theWindow = $('.window').last();
var bottomWindow = $('.windowBottom').last();
var letsdraw = false;
var theCanvas = $('.paint').last();
var ctx = theCanvas.getContext('2d');
ctx.strokeStyle = 'red';
theCanvas.width = 430;
theCanvas.height = 317;
var canvasOffset = $(theCanvas).offset();
$(theCanvas).mousemove(function(e) {
if (letsdraw === true) {
ctx.lineTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
ctx.stroke();
}
});
$(theCanvas).mousedown(function(e) {
letsdraw = true;
ctx.strokeStyle = color;
ctx.lineWidth = size;
ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
});
$(window).mouseup(function() {
letsdraw = false;
});
This problem is you are still treating it as one canvas.
So I removed
theCanvasand usingthisto reference the canvas. Click the demo link to see it in action:Demo
Some more edits using the data attr:
Changing the height and width:
I only do this once, because changing the height/width of a canvas actually erases all drawing.