ali
ali

Reputation: 11045

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!

Upvotes: 4

Views: 7506

Answers (2)

Zhihao
Zhihao

Reputation: 14747

It looks like jimr beat me to the punch about the canvas height and width.

The poor quality of the line though is due to how you're drawing the line. You'll notice that you're calling stroke() on every onmousemove event. Keep in mind that it's keeping track of the path of the line from when you beginPath() to when you closePath(), so you're basically stroking the same line multiple times (every time your mouse moves). This is what's giving you the aliased (blocky-looking) lines, instead of the smooth anti-aliased lines you're expecting.

Upvotes: 1

jimr
jimr

Reputation: 11230

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/

Upvotes: 9

Related Questions