<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>图形缩放平移</title>
<script type="text/javascript" src="./js/jquery-1.11.1.min.js"></script>
</head>
<body>
<canvas id="myCanvas" width="1000" height="800"></canvas>
</body>
<script type="text/javascript">
class model {
constructor(canvasid) {
// 获取Canvas元素
this.canvas = document.getElementById(canvasid);
this.ctx = this.canvas.getContext('2d');
this.mx = 0;
this.my = 0;
//平移参数:
this.cx = 0;
this.cy = 0;
//缩放参数:
this.sx = 1;
this.sy = 1;
this.scale = 1.2;
// 监听鼠标点击事件
this.canvas.addEventListener('mousedown', (event) => {
// 获取鼠标点击位置坐标
var mouseX = event.offsetX;
var mouseY = event.offsetY;
// 计算平移的偏移量
this.cx = mouseX;
this.cy = mouseY;
this.paint();
});
// 监听鼠标点击事件
this.canvas.addEventListener('mousemove', (event) => {
let mat = this.ctx.getTransform();
// 计算平移的偏移量
this.cx = event.offsetX;
this.cy = event.offsetY;
this.paint();
});
// 监听鼠标滚轮事件
this.canvas.addEventListener('mousewheel', (event) => {
// 阻止默认的滚轮事件
event.preventDefault();
// 进行缩放操作
let scale = event.wheelDelta > 0 ? this.scale : 1 / this.scale;
this.sx *= scale;
this.sy *= scale;
this.paint();
});
}
paint() {
//清空背景:
this.ctx.save();
this.ctx.resetTransform();
this.ctx.fillStyle = 'blue';
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.restore();
// 绘制示例图形
this.ctx.save();
this.ctx.translate(this.cx, this.cy);
this.ctx.scale(this.sx, this.sy);
this.ctx.fillStyle = 'red';
this.ctx.fillRect(-50, -50, 100, 100);
this.ctx.restore();
}
}
$(document).ready(function() {
new model("myCanvas");
});
</script>
</html>