vishal
vishal

Reputation: 1506

css transform scale mouse is not working properly

i am trying to draw in canvas with transforming the div size but i am not able to draw exactly from mouse point, there is some distance between mouse and line where is actual drawing happen.

CSS

canvas {
    border: 1px solid #ccc;
    transform: scale(0.5)
}

JS

var el = document.getElementById('c');
var ctx = el.getContext('2d');
var isDrawing;

el.onmousedown = function (e) {
    isDrawing = true;
    ctx.moveTo(e.clientX, e.clientY);
};
el.onmousemove = function (e) {
    if (isDrawing) {
        ctx.lineTo(e.clientX, e.clientY);
        ctx.stroke();
    }
};

el.onmouseup = function () {
    isDrawing = false;
};

HTML

<canvas id="c" width="500" height="300"></canvas>

Demo fiddle

Upvotes: 0

Views: 704

Answers (2)

praty
praty

Reputation: 1121

You need to subtract the left and top of the canvas from the mouse positions and multiply everything by 2 (or the reciprocal of whatever your scale is).

var rect = el.getBoundingClientRect();

// code here
ctx.moveTo((e.clientX - rect.left) * 2, (e.clientY - rect.top) * 2);

// code here
ctx.lineTo((e.clientX - rect.left) * 2, (e.clientY - rect.top) * 2);

Updated jsfiddle here -->http://jsfiddle.net/Lqbeqjzb/7/

EDIT: Made changes to your fiddle based on the comment --> https://jsfiddle.net/pb5ckhjm/4/

Upvotes: 3

Mr.M
Mr.M

Reputation: 1480

Try using mouseover

el.onmouseover = function (e) {
isDrawing = true;
ctx.moveTo(e.clientX, e.clientY);
 };

Let me know this is what you want

Upvotes: 0

Related Questions