Reputation: 537
I intend to draw free with the mouse cursor in canvas. My code seems to do the part with color but it doesn't take the exact coordinates of my current mouse position in canvas when i draw.
<body>
<canvas id="canvas" style=" width: 400; height: 400px; background-color:yellow; position: absolute; margin-left:100px; margin-top:30px"></canvas>
<script>
var Color = 'blue';
var Canvas = document.getElementById('canvas');
var Context = Canvas.getContext('2d');
$("canvas").on("mousemove",function(e){
X = e.clientX - canvas.offsetLeft;
Y = e.clientY - canvas.offsetTop;
Context.strokeStyle = Color;
Context.lineWidth = 3;
Context.lineCap = 'round';
Context.beginPath();
Context.moveTo(X,Y);
Context.lineTo(X,Y);
Context.fillRect(X,Y, 3,3)
Context.stroke();
Context.closePath();
});
</script>
</body>
https://jsfiddle.net/93L8mLnf/
I tested in console.log
the coordinates and they are corect. I'm confused..
Upvotes: 2
Views: 160
Reputation: 382404
You need to synchronize the dimension of the canvas with the DOM element. Add this:
Canvas.width = Canvas.clientWidth;
Canvas.height = Canvas.clientHeight;
You'll also notice the canvas isn't blurred anymore.
Note that this must be done every time the canvas DOM element changes size (usually because the window is resized) so when your element isn't of fixed size you should bind an event handler on the window resize
event to do that synchronization again (and usually to redraw the content).
Upvotes: 3
Reputation: 318
You have to add width and height by canvas attributes see in fiddle
<canvas id="canvas" style="background-color:yellow;" width="250" height="250"></canvas>
Upvotes: 1