话不多说 直接贴代码
一、实现鼠标滚轮缩放画布
// 可以实现鼠标滚轮缩放 最小为原来的百分之一,最大为原来的20倍
canvas.on('mouse:wheel', function (opt) {
var delta = opt.e.deltaY
var zoom = canvas.getZoom()
zoom *= 0.999 ** delta
if (zoom > 20) zoom = 20
if (zoom < 0.01) zoom = 0.01
this.setZoom(zoom)
opt.e.preventDefault()
opt.e.stopPropagation()
})
使用说明,我的canvas画布定义为 canvas,替他均不用额外设置变量。canvas = new fabric.Canvas('editorCanvas', {...
二、实现鼠标按下变抓手,并可移动画布中内容
// 鼠标按下事件
canvas.on('mouse:down', function (e) {
this.panning = true
canvas.selection = false
})
// 鼠标抬起事件
canvas.on('mouse:up', function (e) {
this.panning = false
canvas.selection = true
})
// 移动画布事件
canvas.on('mouse:move', function (e) {
if (this.panning && e && e.e) {
var delta = new fabric.Point(e.e.movementX, e.e.movementY)
canvas.relativePan(delta)
}
})
使用说明:data中定义panning: false,用来标记鼠标按下状态(是否鼠标按下)。
原理,通过偏移量文章来源:https://www.toymoban.com/news/detail-703931.html
添加 鼠标为缩放原点:
文章来源地址https://www.toymoban.com/news/detail-703931.html
"mouse:wheel": (e) => {
this.zoom = (event.deltaY > 0 ? -0.1 : 0.1) + canvas.getZoom();
this.zoom = Math.max(0.1, this.zoom); //最小为原来的1/10
this.zoom = Math.min(3, this.zoom); //最大是原来的3倍
this.zoomPoint = new fabric.Point(e.pointer.x,e.pointer.y);
canvas.zoomToPoint(this.zoomPoint, this.zoom);
this.lastzoomPoint.x = this.lastzoomPoint.x + (this.zoomPoint.x - this.lastmousePoint.x - this.relativeMouseX) / this.lastzoom
this.lastzoomPoint.y = this.lastzoomPoint.y + (this.zoomPoint.y - this.lastmousePoint.y - this.relativeMouseY) / this.lastzoom
this.lastmousePoint.x = this.zoomPoint.x
this.lastmousePoint.y = this.zoomPoint.y
this.lastzoom = this.zoom
this.tempmouseX = this.relativeMouseX
this.tempmouseY = this.relativeMouseY
this.relativeMouseX = 0
this.relativeMouseY = 0
},
————————————————
版权声明:本文为CSDN博主「qq_38860536」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_38860536/article/details/104759042
到了这里,关于Fabric.js+vue 实现鼠标滚轮缩放画布+移动画布的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!