vue3 Canvas鼠标滚轮缩放不超过canvas尺寸以及画布拖动,不可以超过canvas的尺寸,并显示完成代码
时间: 2025-01-04 20:39:50 浏览: 5
在Vue3中,我们可以结合HTML5的Canvas API和一些事件处理机制来实现在Canvas上通过鼠标滚轮缩放和拖拽时保持画面在canvas范围内。这里是一个简单的示例代码:
```html
<template>
<div ref="canvasWrapper" style="position:relative">
<canvas :ref="canvasRef" @wheel="onWheelZoom" @mousedown="onMouseDown" @mouseup="onMouseUp"></canvas>
</div>
</template>
<script setup>
import { onMounted } from 'vue';
const canvasRef = ref(null);
let isDragging = false;
let lastMousePos;
function onMounted() {
canvasRef.value.addEventListener('contextmenu', preventDefault);
}
function preventDefault(e) {
e.preventDefault();
}
// 鼠标滚轮缩放函数
function onWheelZoom(event) {
const delta = event.deltaY || -event.wheelDelta; // 判断滚动方向
const scale = Math.exp(delta / 100); // 滚动步长调整缩放比例
if (isDragging) return;
const canvasRect = canvasRef.value.getBoundingClientRect();
const center = { x: canvasRect.left + canvasRect.width / 2, y: canvasRect.top + canvasRect.height / 2 };
const mousePos = { x: event.clientX - center.x, y: event.clientY - center.y };
const newCenter = { x: center.x * scale, y: center.y * scale };
const newCanvasSize = Math.max(1, canvasRect.width * scale), Math.max(1, canvasRect.height * scale);
setCanvasSize(newCanvasSize);
moveCanvasBy(newCenter.x - center.x, newCenter.y - center.y);
}
// 鼠标按下开始拖拽
function onMouseDown(event) {
isDragging = true;
lastMousePos = getMousePos(event);
}
// 鼠标抬起结束拖拽
function onMouseUp(event) {
isDragging = false;
}
// 获取鼠标位置
function getMousePos(event) {
return {
x: event.clientX,
y: event.clientY
};
}
// 更新Canvas大小并移动到指定位置
function setCanvasSize(size) {
canvasRef.value.width = size;
canvasRef.value.height = size;
}
// 移动Canvas
function moveCanvasBy(dx, dy) {
const transformMatrix = `translate(${dx}, ${dy})`;
canvasRef.value.style.transform = transformMatrix;
}
// 计算鼠标相对于canvas的位置
function getRelativeMousePos(event) {
const rect = canvasRef.value.getBoundingClientRect();
return { x: event.clientX - rect.left, y: event.clientY - rect.top };
}
function handleMouseMove(event) {
if (!isDragging) return;
const relativeMousePos = getRelativeMousePos(event);
const newCanvasPos = { x: lastMousePos.x + relativeMousePos.x, y: lastMousePos.y + relativeMousePos.y };
moveCanvasBy(newCanvasPos.x - canvasRef.value.offsetLeft, newCanvasPos.y - canvasRef.value.offsetTop);
}
// 监听mousemove事件
canvasRef.value.addEventListener('mousemove', handleMouseMove);
</script>
```
这个示例实现了鼠标滚轮缩放、鼠标拖动Canvas并且始终保证Canvas在屏幕内。请注意,这只是一个基础的实现,实际项目中可能还需要考虑更多的边界情况和优化。
阅读全文