在mousemove上获得自适应画布上的鼠标位置

时间:2018-09-07 07:23:27

标签: javascript jquery canvas

我有一个响应式画布,它在mousemove上绘制了一个正方形,但是我无法定位画布的鼠标位置,但是如果画布没有响应,它就可以工作。如何定位鼠标的位置?预先谢谢你。

https://jsfiddle.net/Paul017/yz028mwe/3/

这是代码。

HTML:

<h4>Drag the mouse to create a rectangle</h4>
<canvas id="canvas" width=300 height=300></canvas>

CSS:

body{ background-color: ivory; }
#canvas{border:1px solid red; width:100%}

JS:     var canvas = document.getElementById(“ canvas”);     var ctx = canvas.getContext(“ 2d”);

ctx.strokeStyle = "rgba(255, 235, 59, 0.5)";
ctx.fillStyle = "red";
ctx.fill();
ctx.lineWidth = 1;

var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();

var isDown = false;

var startX;
var startY;


function handleMouseDown(e) {
    e.preventDefault();
    e.stopPropagation();

    startX = parseInt(e.clientX - offsetX);
    startY = parseInt(e.clientY - offsetY);

    // set a flag indicating the drag has begun
    isDown = true;
}

function handleMouseUp(e) {
    e.preventDefault();
    e.stopPropagation();

    isDown = false;
}

function handleMouseOut(e) {
    e.preventDefault();
    e.stopPropagation();

    isDown = false;
}

function handleMouseMove(e) {
     e.preventDefault();
        e.stopPropagation();

        // if we're not dragging, just return
        if (!isDown) {
            return;
        }

        // get the current mouse position
        mouseX = parseInt(e.clientX - offsetX);
        mouseY = parseInt(e.clientY - offsetY);

        ctx.clearRect(0, 0, canvas.width, canvas.height);

        var width = mouseX - startX;
        var height = mouseY - startY;

        ctx.strokeRect(startX, startY, width, height);

    }

2 个答案:

答案 0 :(得分:0)

您可以使用selectionStart方法的selectionEndtarget属性。

您可以使用以下方法获得每个位置的目标:

e.target.selectionStart

e.target.selectionEnd

在您的代码中:

function handleMouseMove(e) {
console.log('target event ', e.target);
console.log('selectionStart', e.target.selectionStart);
console.log('selectionEnd', e.target.selectionEnd)
     e.preventDefault();
        e.stopPropagation();

        // if we're not dragging, just return
        if (!isDown) {
            return;
        }

        // get the current mouse position
        mouseX = parseInt(e.clientX - offsetX);
        mouseY = parseInt(e.clientY - offsetY);

        ctx.clearRect(0, 0, canvas.width, canvas.height);

        var width = mouseX - startX;
        var height = mouseY - startY;

        ctx.strokeRect(startX, startY, width, height);

    }

如果控制台日志显示未定义,请尝试以e.target控制台日志。您将找到selectionStart和selectionEnd方法。

让我知道您是否还需要其他东西。

答案 1 :(得分:0)

我已经通过使用这些鼠标位置代码来定位响应画布中的x和y位置来弄清楚了

 e.offsetX * canvas.width / canvas.clientWidth | 0
 e.offsetY * canvas.width / canvas.clientWidth | 0

https://jsfiddle.net/Paul017/yz028mwe/28/