Skip to content
Advertisement

Drawing at cursor position on canvas with JavaScript

I am trying to draw over a canvas by clicking and dragging the mouse. My problem is that, apart from the fact that the line has a very poor quality (I want a more pronounced border) it only respects the mouse position when this is at 0,0. As I move the mouse to the lower corner, the line increments its distance from it as much as when I am in the middle of the canvas, the line is already out of it. I have my code at: 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!

Advertisement

Answer

You need to set an explicit width and height on the canvas. The default dimensions of a canvas are a width of 300 and a height of 150 (see the spec here). By setting the width and height via CSS you are just stretching the canvas.

Either do:

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

or set the width/height via JavaScript:

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

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

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement