Reputation: 21208
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;
});
Upvotes: 1
Views: 1031
Reputation: 82604
This problem is you are still treating it as one canvas.
$('.paint').mousemove(function(e) {
if (letsdraw === true) {
var ctx = this.getContext('2d');
var canvasOffset = $(this).offset();
ctx.lineTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
ctx.stroke();
}
});
So I removed theCanvas
and using this
to reference the canvas. Click the demo link to see it in action:
// using data attr to store lets draw per canvas
$(window).mouseup(function() {
$('.paint').each(function () {
$(this).data('letsdraw', false);
});
});
$('.paint').mousemove(function(e) {
if ($(this).data('letsdraw') === true) {
var ctx = this.getContext('2d');
var canvasOffset = $(this).offset();
ctx.lineTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
ctx.stroke();
}
});
Changing the height and width:
$('.paint').each(function () {
this.width = 430;
this.height = 20
})
I only do this once, because changing the height/width of a canvas actually erases all drawing.
Upvotes: 2