修复画布中的线条定位

时间:2017-08-16 19:34:40

标签: javascript canvas

我在这样的div中有一个画布

<div class="col-md-6">
    <img src="{{ image }}" class="img-class img-thumbnail img-responsive">
    <canvas id="can" class="hidden" style="position: absolute; width: 100%; height: 100%; top: 0px; left: 0px;"></canvas>
    <div class="hidden hover-div" style="position: absolute; width: 100%; height: 100%; background-color: rgba(128, 128, 128, 0.07); top: 0;">

    </div>
</div>

以及用它画线的代码

var canvas, ctx, flag = false,
prevX = 0,
currX = 0,
prevY = 0,
currY = 0,
dot_flag = false;

var x = "black",
y = 2;

function initialize() {
    canvas = document.getElementById('can');
    ctx = canvas.getContext("2d");
    w = canvas.width;
    h = canvas.height;

    canvas.addEventListener("mousemove", function (e) {
        findxy('move', e)
    }, false);
    canvas.addEventListener("mousedown", function (e) {
        findxy('down', e)
    }, false);
    canvas.addEventListener("mouseup", function (e) {
        findxy('up', e)
    }, false);
    canvas.addEventListener("mouseout", function (e) {
        findxy('out', e)
    }, false);
}

function draw() {
    ctx.beginPath();
    ctx.moveTo(prevX, prevY);
    ctx.lineTo(currX, currY);
    ctx.strokeStyle = x;
    ctx.lineWidth = y;
    ctx.stroke();
    ctx.closePath();
}

function findxy(res, e) {
    if (res == 'down') {
        prevX = currX;
        prevY = currY;
        currX = e.clientX - canvas.offsetLeft;
        currY = e.clientY - canvas.offsetTop;

        flag = true;
        dot_flag = true;
        if (dot_flag) {
            ctx.beginPath();
            ctx.fillStyle = x;
            ctx.fillRect(currX, currY, 2, 2);
            ctx.closePath();
            dot_flag = false;
        }
    }
    if (res == 'up' || res == "out") {
        flag = false;
    }
    if (res == 'move') {
        if (flag) {
            prevX = currX;
            prevY = currY;
            currX = e.clientX - canvas.offsetLeft;
            currY = e.clientY - canvas.offsetTop;
            draw();
        }
    }
}

它有效,但x,y坐标关闭,需要帮助解决这个问题。

以下是该行为https://youtu.be/e8SUUZF81rk

的屏幕记录演示

与鼠标相比,y pos远远落在画布上,而x略微偏向右边。

我从这里的一个例子中得到了这个代码并编辑了一下。

1 个答案:

答案 0 :(得分:0)

您需要设置画布分辨率以匹配画布显示大小,或将鼠标坐标缩放到画布分辨率。

设置分辨率以匹配画布显示大小

 const bounds = canvasElement.getBoundingClientRect();
 canvasElement.width = bounds.width;
 canvasElement.height = bounds.height;

或者如果您愿意,可以缩放鼠标位置以匹配画布分辨率

 const bounds = canvasElement.getBoundingClientRect();
 const scaleX = canvasElement.width / bounds.width;
 const scaleY = canvasElement.height / bounds.height;

 // then scale the mouse with the above scales
 // in mouse event

 mouseX = mouseEvent.clientX * scaleX;
 mouseY = mouseEvent.clientY * scaleY;