canvas 自定义图片鼠标事件(放大缩小拖动)

Posted on 2021-06-25 14:47:09
Author: 可乐小可爱メ
1. 背景

业务需求是 自定义放大某个版本, 最后实现放弃了 canvas 绘制img 放大的思路, 这里记录一下。


2. 代码
<!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>Canvas diy image</title>
<style>
canvas {
border: 1px dashed #eee;
width: 634px;
height: 673px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script>
const canvas = document.querySelectorAll("#canvas")[0];
const context = canvas.getContext("2d");
const img = new Image();
let stemp = 10; // 步进
// 计算尺寸的函数
const roll = function (e) {
e = e || window.event;
if (e.wheelDelta) {
//IE,谷歌
if (e.wheelDelta > 0) {
//当滑轮向上滚动时
stemp--;
return e.wheelDelta / 100 + stemp;
}
if (e.wheelDelta < 0) {
//当滑轮向下滚动时
stemp++;
return e.wheelDelta / 100 + stemp;
}
} else if (e.detail) {
//Firefox
if (e.detail > 0) {
stemp--;
return e.wheelDelta / 100 + stemp;
}
if (e.detail < 0) {
stemp++;
return e.wheelDelta / 100 + stemp;
}
}
};
//给页面绑定滑轮滚动事件
if (document.addEventListener) {
document.addEventListener("DOMMouseScroll", roll, false);
}
canvas.onmousewheel = canvas.onmousewheel = roll; // 给canvas绑定滑轮滚动事件
let resize = 0;
let moveX = 0;
let moveY = 0;

//滚动滑轮触发scrollFunc方法
window.onload = function () {
img.src = "https://www.tiankele.cn/_nuxt/img/5e7bb66.png";
img.onload = function () {
drawImageScale();

canvas.onmousewheel = canvas.onmousewheel = function () {
resize = roll();
drawImageScale();
};

canvas.onmousedown = function (event) {
const { clientX, clientY } = event;
const preX = moveX;
const preY = moveY;
canvas.onmousemove = function (evt) {
//移动
canvas.style.cursor = "grabbing";
moveX = evt.clientX - clientX + preX;
moveY = evt.clientY - clientY + preY;
drawImageScale();
};
canvas.onmouseup = function () {
canvas.onmousemove = null;
canvas.onmouseup = null;
canvas.style.cursor = "default";
};
};
};
};
// 控制写入图片大小的函数
function drawImageScale() {
resize = resize || 1;
canvas.width = 634;
canvas.height = 673;
let imgWidth = 634 + resize * 20;
let imgHeight = 673 + resize * 20;
// let sx = imgWidth / 2 - canvas.width / 2
// let sy = imgHeight / 2 - canvas.height / 2
let dx = canvas.width / 2 - imgWidth / 2;
let dy = canvas.height / 2 - imgHeight / 2;
context.clearRect(0, 0, canvas.width, canvas.height);
// context.drawImage(img, 0, 0, imgWidth, imgHeight);
context.drawImage(
img,
dx,
dy,
imgWidth,
imgHeight,
moveX,
moveY,
canvas.width,
canvas.height
);
}
</script>
</html>


3. 参考

https://www.w3school.com.cn/tags/canvas_drawimage.asp

https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API/Tutorial


当前评论 (1) 登录后评论

可乐小可爱メ
2021-08-15 22:05:41

<script>alert(1)</script>

回复
1