vue2 ,移动端实现SVG拖拽缩放,保持缩放中心点svg-pan-zoom + hammerjs ( 二 )

文章介绍了如何在Vue项目中利用svg-pan-zoom和hammerjs库实现SVG图形的拖拽缩放功能,同时保持屏幕中心点不变,并详细说明了如何添加特定坐标点的聚焦效果。主要代码包括事件处理和坐标计算,以保证缩放和移动的平滑性。

功能介绍 :

使用vue,实现SVG的拖拽缩放,
1.缩放的同时保持屏幕的中心点不会变,
2.同时增加某坐标点的聚焦。
使用的库
svg-pan-zoom + hammerjs

实现的代码片段

你的svg

<svg ref="svg" class="svg-content" width="380" height="840" id="svggroup" xmlns="http://www.w3.org/2000/svg"
      xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 13270 7475"
      style="enable-background:new 0 0 13270.2 7475.1;" xml:space="preserve">
      ////svg内部元素
 </svg>

引入

import svgPanZoom from 'svg-pan-zoom';
import Hammer from 'hammerjs';

data() {
    return {
      svgGroups: null,
      viewBox: "0 0 13270 7475",
      centerCoord: {x: 10104, y: 5008},
      //测试的坐标系数  viewbox是我svg的系数
      // centerCoord: {x: 4301, y: 2004},
      // centerCoord: {x: 4180, y: 4329},
      // centerCoord: {x: 3760, y: 2054},
      
    };
  },

主要的代码片段
initZoomPan() {
      const eventsHandler = {
        haltEventListeners: ['touchstart', 'touchend', 'touchmove', 'touchleave', 'touchcancel']
        , init: function (options) {
          var instance = options.instance
            , initialScale = 1
            , pannedX = 0
            , pannedY = 0
          this.hammer = Hammer(options.svgElement, {
            inputClass: Hammer.SUPPORT_POINTER_EVENTS ? Hammer.PointerEventInput : Hammer.TouchInput
          })
          this.hammer.get('pinch').set({ enable: true })
          this.hammer.on('doubletap', function (ev) {
            instance.zoomIn()
          })
          this.hammer.on('panstart panmove', function (ev) {
            if (ev.type === 'panstart') {
              pannedX = 0
              pannedY = 0
            }
            instance.panBy({ x: ev.deltaX - pannedX, y: ev.deltaY - pannedY })
            pannedX = ev.deltaX
            pannedY = ev.deltaY
          })
          this.hammer.on('pinchstart pinchmove', function (ev) {
            if (ev.type === 'pinchstart') {
              initialScale = instance.getZoom()
              instance.zoom(initialScale * ev.scale)
            }
            instance.zoom(initialScale * ev.scale)
          })
          options.svgElement.addEventListener('touchmove', function (e) { e.preventDefault(); });
        }
        , destroy: function () {
          this.hammer.destroy()
        }
      }
      const element = document.querySelector('#svggroup');
      this.svgGroups = svgPanZoom(element, {
        zoomEnabled: true,
        controlIconsEnabled: false,
        dblClickZoomEnabled: false,
        fit: 1,
        center: 1,
        minZoom: 1,
        maxZoom: 20,
        customEventsHandler: eventsHandler
      });
    }

如果想要某种情况的时候 svg某个坐标去聚焦

svg-pan-zoom_viewport是使用svg-pan-zoom的时候会在svg下创建一个子级g标签,你svg自带的内部元素
都在g下、
bbox 才是最后的容器,根据他的大小,结合svg的viewbox大小,去计算,1倍的的时候要到达的坐标中心,然后在去放大 多少倍

let bbox = document.querySelector('.svg-pan-zoom_viewport').getBoundingClientRect();
      let clientWidth = this.svgGroups.getSizes().width;
      let clientHeight = this.svgGroups.getSizes().height;
      let centerX = bbox.left + (this.centerCoord.x - this.viewBox.split(" ")[0]) * bbox.width / parseInt(this.viewBox.split(" ")[2]);
      let centerY = bbox.top + (this.centerCoord.y - this.viewBox.split(" ")[1]) * bbox.height / parseInt(this.viewBox.split(" ")[3]);
      let x = clientWidth / 2 - centerX
      let y = clientHeight / 2 - centerY
      this.svgGroups.panBy({x, y});
      this.svgGroups.zoom(5);

实现的效果

此功能一次一次的优化,这是最终版了就

svg-pan-zoom

<template> <div class="container"> <div ref="container" class="x6-graph"></div> <div class="controls"> <button @click="zoomIn">放大</button> <button @click="zoomOut">缩小</button> <button @click="resetZoom">重置</button> </div> </div> </template> <script setup> import { ref, onMounted } from 'vue' import { Graph, Shape } from '@antv/x6' import { Transform } from '@antv/x6-plugin-transform' const container = ref(null) let graph = null // 初始化画布 const initGraph = () => { graph = new Graph({ container: container.value, width: 800, height: 600, grid: true, mousewheel: { enabled: true, modifiers: 'ctrl' }, interacting: { nodeMovable: true }, background: { color: '#f5f7fa' } }) graph.use(new Transform({ resizing: true, rotating: true })) createEditableOctagon() createFixedScales() graph.on('zoom', updateScaleLabels) } // 创建可编辑八边形 const createEditableOctagon = () => { // 计算正八边形顶点坐标 const points = [] const radius = 50 for (let i = 0; i < 8; i++) { const angle = (i * Math.PI) / 4 points.push({ x: 300 + radius * Math.cos(angle), y: 200 + radius * Math.sin(angle) }) } graph.addNode({ shape: 'polygon', x: 300, y: 200, width: 100, height: 100, attrs: { body: { fill: '#FEC55B', stroke: '#333', strokeWidth: 1, points: points.map(p => [p.x, p.y]) }, label: { text: '八边形', fill: '#333' } }, editable: true, transform: { enabled: true, preserveAspectRatio: false }, selectable: true }) } // 创建固定刻度系统 const createFixedScales = () => { // X轴刻度(顶部) for (let x = 0; x <= graph.width(); x += 40) { // 刻度线 graph.addNode({ id: `x-tick-${x}`, shape: 'rect', x, y: 0, width: 1, height: 5, attrs: { body: { fill: '#666' } }, selectable: false }) // 标签(仅显示关键刻度) if (x % 100 === 0) { graph.addNode({ id: `x-label-${x}`, shape: 'text', x: x + 5, y: 15, attrs: { label: { text: '' }, text: { fontSize: 10, fill: '#666' } }, selectable: false }) } } // Y轴刻度(右侧) for (let y = 0; y <= graph.height(); y += 40) { // 刻度线 graph.addNode({ id: `y-tick-${y}`, shape: 'rect', x: graph.width() - 5, y, width: 5, height: 1, attrs: { body: { fill: '#666' } }, selectable: false }) // 标签(仅显示关键刻度) if (y % 100 === 0) { graph.addNode({ id: `y-label-${y}`, shape: 'text', x: graph.width() - 15, y: y + 5, attrs: { label: { text: '' }, text: { fontSize: 10, fill: '#666' } }, selectable: false }) } } } // 动态更新刻度标签 const updateScaleLabels = () => { const zoom = graph.zoom() const base = Math.pow(10, Math.floor(Math.log10(zoom * 100))) const step = base * (zoom > 5 ? 1 : zoom > 1 ? 2 : 5) // 更新X轴标签 for (let x = 0; x <= graph.width(); x += 40) { if (x % 100 === 0) { const logicalValue = Math.round(x / (40 * step)) * step const node = graph.getCellById(`x-label-${x}`) node.attr('label/text', logicalValue || '') } } // 更新Y轴标签 for (let y = 0; y <= graph.height(); y += 40) { if (y % 100 === 0) { const logicalValue = Math.round(y / (40 * step)) * step const node = graph.getCellById(`y-label-${y}`) node.attr('label/text', logicalValue || '') } } } // 缩放控制 const zoomIn = () => graph.zoom(0.1) const zoomOut = () => graph.zoom(-0.1) const resetZoom = () => graph.zoomTo(1) onMounted(() => { initGraph() }) </script> <style scoped> .container { position: relative; width: 100vw; height: 100vh; } .x6-graph { width: 100%; height: 100%; border: 1px solid #e0e0e0; } .controls { position: absolute; top: 20px; left: 20px; z-index: 1000; } button { margin-right: 8px; padding: 4px 8px; background: #fff; border: 1px solid #ddd; cursor: pointer; } </style>,参考这个代码,这个可编辑多边形假设为八个点连接起来的封闭图形,在拖到这八个点时,多边形重新绘制形状,这个图形可以被拖拽,移动。底层画布可以自由拖动和缩放,且缩放时的X刻度线始终显示在画布的相对y为0的位置,,Y轴刻度线显示在画布的相对右侧位置,刻度线无法选中,给刻度线加上画布像素值的标签,类似1 2 3 4 6这样的,显示在刻度线缩放,一直到画布的宽高值,在缩放时,刻度线上的标签值也会动态变换,放大到最大显示 1,2 ,3这样显示,缩小时显示1 100 200这样
最新发布
06-19
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值