Hi!
I'm trying to make a simple drawing tool using JS and Canvas element. My problem is that I would like to have several canvases and user should be able to draw one line through all of them. Here's a little page I did:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
var act = null;
var context = null;
var draw = false;
var c = false;
function boot() {
$('.can')
.mouseenter(function(){
act = this;
context = act.getContext('2d');
// console.log(this);
})
.mouseleave(function(){
act = null;
context = null;
// console.log('out');
})
.mousedown(function(){
draw = true;
})
.mouseup(function(){
draw = false;
})
.mousemove(function(ev){
// console.log(act);
if (ev.layerX || ev.layerX == 0) { // Firefox
x = ev.layerX;
y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) { // Opera
x = ev.offsetX;
y = ev.offsetY;
}
if(draw && context != null)
if (!c) {
context.beginPath();
context.moveTo(x, y);
c = true;
} else {
context.lineTo(x, y);
context.stroke();
}
});
}
$(document).ready(boot);
</script>
<style>
.can {border: 1px solid blue; display:block; float:left; margin:0;}
</style>
</head>
<body>
<canvas class="can" id="c2" width="200" height="200"></canvas>
<canvas class="can" id="c1" width="200" height="200"></canvas>
<canvas class="can" id="c3" width="200" height="200"></canvas>
</body>
</html>
And it partially works: I can draw only in the first canvas. I debugged it and i got really confused, because the context changes as expected and drawing is enabled only in the first canvas.
Any ideas what's the cause of such behavior?