翻译后如何在画布中获得图像的左上角坐标?

时间:2017-08-25 19:02:42

标签: javascript canvas transform translate-animation

我有一个问题,在画布中翻译图像后如何获得图像左上角的坐标?我想让图像区域可选,同时让白色空间不可选,但没有它,就不可能满足鼠标是否在图像范围内的条件。

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var position = {
    start : {
        x : 0,
        y : 0
    },
    end : {
        x : 0,
        y : 0
    }
};
var imagePos = {
    x : 0,
    y : 0
};
var img = document.getElementById('img');
ctx.drawImage(img, 0, 0);
var drag = false, selected = false;

canvas.addEventListener('mousedown', mouseDown);
window.addEventListener('mouseup', mouseUp);

function mouseDown(p) {
    window.addEventListener('mousemove', moveImg);
    position.start.x = p.pageX - canvas.getBoundingClientRect().left;
    position.start.y = p.pageY - canvas.getBoundingClientRect().top;
    drag = true;

    if (position.start.x >= imagePos.x && position.start.x <= (imagePos.x + img.width) && position.start.y >= imagePos.y && position.start.y <= (imagePos.y + img.height)) {
        selected = true;
    } else {
        selected = false;
    }
}

function mouseUp() {
    window.removeEventListener('mousemove', moveImg);
    selected = false;
}

function moveImg(p) {
    document.getElementById('mouse').innerHTML = 'MouseX: ' + parseInt(p.pageX - canvas.getBoundingClientRect().left) + '/ MouseY: ' + parseInt(p.pageY - canvas.getBoundingClientRect().top);

    if (drag && selected) {
        position.end.x = p.pageX - canvas.getBoundingClientRect().left;
        position.end.y = p.pageY - canvas.getBoundingClientRect().top;

        var x = position.end.x - position.start.x;
        var y = position.end.y - position.start.y;

        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.translate(x, y);
        ctx.save();
        ctx.drawImage(img, 0, 0);
        ctx.restore();

        position.start.x = position.end.x;
        position.start.y = position.end.y;
        imagePos.x = position.end.x;
        imagePos.y = position.end.y;
    }
}
h1 img{
  vertical-align:middle;
}
canvas{
  width:inherit;
  background:white;
}
#info{
  position:absolute;
  top:0;
  right:0;
}
<h1>
Image I'm using:  <img id='img' src="https://scontent-sin6-2.xx.fbcdn.net/v/t39.2081-6/c0.0.51.51/p50x50/10935987_911967968835908_1597235465_n.png?oh=01328f28a865b7cbe62cf67036b3615d&oe=5A5F490A">
</h1>
<div>
<canvas id='canvas' width="500px" height="500px"></canvas>
</div>
<div id='info'>
<p id='mouse'>

</p>
<p id='image'>

</p>
</p>
</div>

1 个答案:

答案 0 :(得分:3)

它不是公式,只是对代码进行了简单的更改:

更改

imagePos.x = position.end.x;
imagePos.y = position.end.y;

imagePos.x += x;
imagePos.y += y;

因为您要按x和y翻译图像,所以还必须按x和y翻译位置...