CSS变换缩放鼠标不能正常工作



我试图在画布上绘制与转换div大小但是我不能准确地从鼠标点开始绘制,鼠标和线之间有一段距离,实际绘制发生。

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;
};

<canvas id="c" width="500" height="300"></canvas>
演示小提琴

您需要从鼠标位置减去画布的左侧和顶部,并将所有内容乘以2(或您的比例的倒数)。

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);

此处更新jsfiddle ->http://jsfiddle.net/Lqbeqjzb/7/

编辑:修改你的小提琴基于评论-> https://jsfiddle.net/pb5ckhjm/4/

尝试使用鼠标悬停

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

让我知道这是你想要的

最新更新