简单使用transform: translate属性实现SVG的拖拽移动与缩放

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
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值