MapZoom.vue 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <template>
  2. <div :id="id" class="map-zoom">
  3. <svg :view-box.camel="viewBox">
  4. <g :transform="transform">
  5. <slot name="default" />
  6. </g>
  7. </svg>
  8. <button-zoom
  9. v-bind="{ minZoom, maxZoom, value: scale }"
  10. @zoom="onZoom"
  11. />
  12. </div>
  13. </template>
  14. <script>
  15. import { select, zoom, zoomIdentity } from 'd3'
  16. export default {
  17. name: 'MapZoom',
  18. props: {
  19. id: { type: String, required: true },
  20. minZoom: { type: Number, default: 0.3 },
  21. maxZoom: { type: Number, default: 1 },
  22. initialZoom: { type: Number, default: 1 },
  23. center: { type: Object, default: null }
  24. },
  25. data () {
  26. return {
  27. zoom: zoom().scaleExtent([this.minZoom, this.maxZoom]),
  28. svg: undefined, // d3 select(svg)
  29. width: undefined,
  30. height: undefined,
  31. scale: this.initialZoom,
  32. transform: zoomIdentity.translate(0, 0).scale(this.initialZoom)
  33. }
  34. },
  35. computed: {
  36. viewBox () {
  37. const { width, height } = this
  38. if (width === undefined) return
  39. return `-${width / 2} -${height / 2} ${width} ${height}`
  40. }
  41. },
  42. watch: {
  43. center (val, prevVal) {
  44. this.transform = this.transform.translate(prevVal.x - val.x, prevVal.y - val.y)
  45. }
  46. },
  47. methods: {
  48. updateSize () {
  49. const { width, height } = this.$el.getBoundingClientRect()
  50. Object.assign(this.$data, { width, height })
  51. this.$emit('input', { width, height })
  52. },
  53. onZoom (direction) {
  54. this.zoom.scaleBy(this.svg, direction === 1 ? 1.3 : 1 / 1.3, [0, 0])
  55. },
  56. reset () {
  57. this.transform = zoomIdentity.translate(0, 0).scale(this.initialZoom)
  58. this.svg.call(this.zoom.transform, this.transform)
  59. }
  60. },
  61. mounted () {
  62. window.addEventListener('resize', () => this.updateSize())
  63. this.zoom.on('zoom', ({ transform }) => {
  64. this.transform = this.center ? transform.translate(-this.center.x, -this.center.y) : transform
  65. this.scale = transform.k
  66. })
  67. this.updateSize()
  68. this.svg = select('#' + this.id + ' svg')
  69. this.svg.call(this.zoom).call(this.zoom.transform, this.transform)
  70. }
  71. }
  72. </script>
  73. <style lang="scss" scoped>
  74. .map-zoom {
  75. position: relative;
  76. width: 100%;
  77. height: 100%;
  78. cursor: grab;
  79. svg {
  80. width: 100%;
  81. height: 100%;
  82. }
  83. }
  84. </style>