实现一个简单的画布拖动功能
- 主要原理:计算鼠标移动的距离并作出距离限制,设置元素的 translateX translateY 属性
直接贴源码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style></style>
</head>
<body style="overflow: hidden; margin: 0; height: 100vh; width: 100vw">
<div
id="myCanvas"
style="
width: 3200px;
height: 2000px;
background-color: antiquewhite;
position: relative;
"
>
<div
id="box"
style="
width: 192px;
height: 340px;
background-color: aqua;
position: absolute;
top: 500px;
left: 600px;
"
></div>
<div
id="box"
style="
width: 192px;
height: 340px;
background-color: aqua;
position: absolute;
top: 0;
left: 0;
"
></div>
<div
id="box"
style="
width: 192px;
height: 340px;
background-color: aqua;
position: absolute;
bottom: 20px;
right: 0;
"
></div>
</div>
<script>
var divScreenX = 0; // 盒子到屏幕 左侧的距离
var divScreenY = 0; // 盒子到屏幕 顶部的距离
var mouseScreenX = 0; //鼠标到屏幕左边的距离
var mouseScreenY = 0; // 鼠标到屏幕顶部的距离
var div = document.getElementById("myCanvas");
var clientWidth = document.body.clientWidth; // 可见区域宽度
var clientHeight = document.body.clientHeight; // 可见区域高度
div.onmousedown = function (e) {
divScreenX = div.getBoundingClientRect().left;
divScreenY = div.getBoundingClientRect().top;
mouseScreenX = e.offsetX;
mouseScreenY = e.offsetY;
document.onmousemove = function (e) {
div.style.transition = "all ease .2s"; // 丝滑
let moveNumX = divScreenX - (mouseScreenX - e.offsetX); // 鼠标移动的距离 X
let moveNumY = divScreenY - (mouseScreenY - e.offsetY); // 鼠标移动的距离 Y
// moveNumX = moveNumX < -1280 ? -1280 : moveNumX; //3200-1920 画布宽度减去当前屏幕可见区域宽度
moveNumX =
moveNumX < -(3200 - clientWidth) ? -(3200 - clientWidth) : moveNumX; //3200-1920 画布宽度减去当前屏幕可见区域宽度
moveNumX = moveNumX > 0 ? 0 : moveNumX;
// moveNumY = moveNumY < -1024 ? -1024 : moveNumY; // 2000-1024 画布高度减去当前屏幕可见区域高度
moveNumY =
moveNumY < -(2000 - clientHeight)
? -(2000 - clientHeight)
: moveNumY; // 2000-1024 画布高度减去当前屏幕可见区域高度
moveNumY = moveNumY > 0 ? 0 : moveNumY;
div.style.transform = `translateX(${moveNumX}px) translateY(${moveNumY}px) translateZ(1px)`;
return false;
};
document.onmouseup = function () { // 清除事件
document.onmouseup = null;
document.onmousemove = null;
};
};
</script>
</body>
</html>
不是很完善,有兴趣的大佬可以自行修改完善
也请各位大佬不要吝啬完善后的代码