Im just learning Java Script and im trying to a code a really simple canvas application where you can draw on with your mouse. But something with the calculation of the variables seems wrong. In the top left hand corner the stroke matches the mouse Position exactly but when you move it from there the stroke doesn´t match the mouse Position anymore.
Here is the Code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
<script>
jQuery(document).ready(function(){
var stift;
var c = document.getElementById("canvas");
var rect = c.getBoundingClientRect();
var context = c.getContext("2d");
var e = 0;
$("#canvas").mousedown(function(){
var x = event.clientX - rect.left;
var y = event.clientY -rect.top;
context.moveTo(x, y);
context.beginPath();
context.lineWidth = "1px";
context.strokeStyle = "black";
e = 1;
});
$("#canvas").mousemove(function(){
if(e == 1){
var x = event.clientX - rect.left;
var y = event.clientY - rect.top;
console.log(x+"; "+y)
context.lineTo(x, y);
context.stroke();
}
})
$("#canvas").mouseup(function(){
e=2;
context.stroke()
context.closePath();
});
});
</script>
</head>
<body>
<canvas id="canvas" style="width: 500px; height: 500px; position: absolute; top:0; left:0; border: 1px solid black;"></canvas>
</body>
</html>
As you can see its quite simple. But I cant find my mistake. Thanks in advance
Edit: I also created a short fiddle: https://jsfiddle.net/3mb7hdcs/7/