HTML代码
<body onload="load()">
<div style="width:500px;height:500px;margin: auto;overflow: hidden;">
<svg id="svg" version="1.1" xmlns="http://www.w3.org/2000/svg"
onmousewheel="mousewheel(event)"
onmousedown="mousedown(event)"
onmousemove="mousemove(event)">
<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" />
</svg>
</div>
</body>
JS代码
load()函数
初始化需要用到的数据
function load(){
this.mousePos={x:0,y:0}
this.offsetX=0
this.offsetY=0
this.radio=1
this.dragging=false
}
鼠标按下事件
鼠标按下svg获取鼠标按下点,当前位置
function mousedown(e) {
const event = window.event || e
event.preventDefault()
let nx = event.clientX
let ny = event.clientY
this.mousePos.x = nx - this.offsetX
this.mousePos.y = ny - this.offsetY
this.dragging=true
window.addEventListener("mouseup",this.mouseupFunction)
}
释放加载在window的鼠标松开事件
鼠标松开事件需要在全局中都要监听到,所以需要在鼠标按下后添加到window上
function mouseupFunction(){
this.dragging=false
window.removeEventListener("mouseup",this.mouseupFunction)
}
鼠标滑动事件
鼠标按下滑动需要移动svg,还需要判断是否是鼠标按下
function mousemove(e) {
if(this.dragging) {
const e = window.event || e
e.preventDefault()
let nx = event.clientX
let ny = event.clientY
let offsetX = nx - this.mousePos.x
let offsetY = ny - this.mousePos.y
this.offsetX = offsetX
this.offsetY = offsetY
let svg = document.getElementById("svg")
svg.style.transform = `translate(${offsetX}px, ${offsetY}px) scale(${this.radio})`
}
}
滚轮滚动事件
鼠标滚动对svg放大缩小
function mousewheel(e) {
const event = window.event || e
e.preventDefault()
let newRadio = this.radio
if(e.deltaY > 0) {
newRadio += 0.1
} else {
newRadio -= 0.1
}
if(newRadio <= 0.1) {
return
}
let svg = document.getElementById('svg')
svg.style.transform = `translate(${this.offsetX}px, ${this.offsetY}px) scale(${newRadio})`
this.radio = newRadio
}