如何实现Canvas图像的拖拽,点击等操作

2024-12-29 11:44:10
推荐回答(1个)
回答1:

  思路:当点击到图片上,获取鼠标位置,计算出鼠标X,Y轴分别与图片左边和上边的距离,移动鼠标的时候,让这个距离不变,就可以了。

function drag(obj) {
var oM = document.getElementById(obj);
oM.onmousedown = function (ev) {
var oEvent = ev || event;
var ol = oEvent.clientX - oM.offsetLeft;
var ot = oEvent.clientY - oM.offsetTop;
document.onmousemove = function (ev) {
var oEvent = ev || event;
oM.style.left = oEvent.clientX - ol + 'px';
oM.style.top = oEvent.clientY - ot + 'px';
return false;
}
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
}
}