Drawing at cursor position on canvas using JavaScript

I try to draw over the canvas by clicking and dragging the mouse. My problem is that, in addition to the fact that the line is of very low quality (I want a more pronounced border), it only respects the position of the mouse when it is equal to 0.0. When I move the mouse to the lower corner, the line increases its distance from it, just as when I am in the middle of the canvas, the line has already left it. I have a code: http://jsfiddle.net/ajTkP/12/

I will also post it here:

var MDown = false; var Color = 'blue'; var Canvas = document.getElementById('canvas'); var Context = Canvas.getContext('2d'); Canvas.onselectstart = function() { return false; }; Canvas.unselectable = "on"; Canvas.style.MozUserSelect = "none"; Canvas.onmousedown = function(e) { MDown = true; Context.strokeStyle = Color; Context.lineWidth = 3; Context.lineCap = 'round'; Context.beginPath(); Context.moveTo(e.pageX - Position(Canvas).left, e.pageY - 5); } Canvas.onmouseup = function() { MDown = false; }; Canvas.onmousemove = function(e) { if (MDown) { Context.lineTo(e.pageX - Position(Canvas).left, e.pageY - 5); Context.stroke(); } } function Position(el) { var position = {left: 0, top: 0}; if (el) { if (!isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) { position.left += el.offsetLeft; position.top += el.offsetTop; } } return position; } 

Thanks for your help!

+4
source share
2 answers

You need to set explicit width and height on the canvas. The default canvas dimensions are 300 width and 150 height ( see the specification here ). By setting the width and height using CSS, you just stretch the canvas.

Or do:

 <canvas id="canvas" width="300" height="200"></canvas> 

or set width / height using javascript:

 canvas.width = 300; canvas.height = 200; 

See the updated jsfiddle file: http://jsfiddle.net/ajTkP/13/

+9
source

It seems that jimr beat me to a hit about the height and width of the canvas.

The poor quality of the line, however, is due to the way you draw the line. You will notice that you call stroke() on every onmousemove event. Keep in mind that it tracks the line path from your beginPath() to closePath() when you closePath() , so you basically stroke the same line several times (each time your mouse moves). This is what gives you aliases (blocky), instead of the smooth smooth lines you expect.

+1
source

All Articles