<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>canvas图片缩放与移动</title>
<style>
* {
margin: 0;
padding: 0;
}
#canvas {
position: absolute;
top: 20px;
left: 50%;
width: 400px;
height: 400px;
transform: translateX(-50%);
background: #f7f7f7;
}
</style>
</head>
<body>
<button id="output">点击导出为图片</button>
<canvas id="canvas" width="400" height="400"></canvas>
<script type="module">
const canvas = document.querySelector("#canvas");
const output = document.querySelector("#output");
const ctx = canvas.getContext("2d");
canvas.width = 400 * devicePixelRatio;
canvas.height = 400 * devicePixelRatio;
const cwidth = canvas.width
const cheight = canvas.width
//等待图片加载完成
const pic = new Image();
//你自己的图片地址
pic.src = "./naroto.webp";
//图片加载成功够在canvas中绘制
pic.onload = function () {
/* cwidth canvas内绘制的图片宽度
* <style></style>标签中的400px则为样式宽度
*/
ctx.drawImage(pic, 0, 0, cwidth, cheight);
};
//缩放倍率
let scale = 2;
const resetCanvas = (canvas, scale) => {
/* cwidth - scale*cwidth
* canvas绘制的图片宽度 - 当前绘制的图片宽度 = 两侧流白空隙
* 故此除以2才是正确的X值
*/
let X = (cwidth - scale * cwidth) / 2;
let Y = (cheight - scale * cheight) / 2;
/*清空画布*/
ctx.clearRect(0, 0, cwidth, cheight);
//重绘图片
ctx.drawImage(pic, X, Y, cwidth * scale, cheight * scale);
};
//最大缩放倍数
const MAX_SCALE = 5;
//最小缩放倍数
const MIN_SCALE = 0.5;
//每次缩放大小
const PER_SCALE = 0.5;
canvas.addEventListener("mousewheel", (e) => {
e.stopPropagation();
e.preventDefault()
if (e.deltaY < 0) {
if (scale >= MAX_SCALE) return;
scale = scale + PER_SCALE;
resetCanvas(canvas, scale);
} else if (e.deltaY > 0) {
if (scale <= MIN_SCALE) return;
scale = scale - PER_SCALE;
resetCanvas(canvas, scale);
}
});
//canvas移动图片
let startX = 0
let startY = 0
canvas.addEventListener("mousedown", (e) => {
startX = e.offsetX
startY = e.offsetY
canvas.style.cursor = "grab";
canvas.addEventListener("mousemove", move);
});
//鼠标移动事件
const move = (e) => {
const x = e.offsetX - (cwidth * scale) / 2;
const y = e.offsetY - (cheight * scale) / 2;
//清空画布
ctx.clearRect(0, 0, cwidth, cheight);
//重绘图片
ctx.drawImage(pic, x, y, cwidth * scale, cheight * scale);
};
//放开鼠标
let endX = 0
let endY = 0
const remove = (e) => {
canvas.style.cursor = "default";
canvas.removeEventListener("mousemove", move);
};
//鼠标离开停止
canvas.addEventListener('mouseleave',remove)
canvas.addEventListener("mouseup", remove);
//输出图片
output.onclick = function () {
const url = canvas.toDataURL("image/png");
const img = new Image();
img.src = url;
img.width = 200;
img.height = 200;
document.documentElement.appendChild(img);
//下载图片
// let link = document.createElement('a');
// link.download = '新图片.png';
// link.href = url;
// link.click();
};
</script>
</body>
</html>
标签:canvas,scale,const,cwidth,缩放,cheight,移动,图片
From: https://blog.csdn.net/qq_55139096/article/details/139233565