<template>
  <div ref="ruler" >
    <canvas id="canvas_ruler" ref="canvas_ruler" class="canvas" :width="canvasWidth" :height="canvasHeight"></canvas>
  </div>
</template>
<script>
import elementResizeDetectorMaker from 'element-resize-detector'
import {getRatio} from './utils/tools'

export default {
  name: 'MapRuler',
  props: {
    interval: {
      type: Number,
      default: 1
    },
    mapWidth: {
      type: Number,
      default: 0
    },
    mapHeight: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      ctx: '',
      observer: '',
      ratio: getRatio()
    }
  },
  computed: {
    fontSize () {
      return 13 * this.ratio
    },
    canvasWidth () {
      return this.mapWidth * this.ratio
    },
    canvasHeight () {
      return this.mapHeight * this.ratio
    }
  },
  mounted () {
    this.observer = elementResizeDetectorMaker()
    this.observer.listenTo(this.$refs.ruler, this.render)
  },
  beforeDestroy () {
    this.observer.removeListener(this.$refs.ruler, this.render)
  },
  watch: {
    interval () {
      this.render()
    }
  },
  methods: {
    // 渲染标尺
    render () {
      const elRuler = this.$refs.canvas_ruler
      const ctxRuler = elRuler.getContext('2d') || {}
      this.ctx = ctxRuler
      const interval = this.interval
      ctxRuler.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
      ctxRuler.lineWidth = this.ratio
      ctxRuler.strokeStyle = '#393F50'
      ctxRuler.fillStyle = '#ffffff'
      ctxRuler.font = `${this.fontSize}px '微软雅黑'`
      ctxRuler.save()
      Array.from({length: Math.ceil(this.canvasWidth / (50 * this.ratio)) / interval}, (item, index) => {
        const x1 = index * 50 * interval * this.ratio
        const x2 = x1
        const y1 = 0
        const y2 = this.canvasHeight
        this.renderSolidLine(ctxRuler, {x1, y1, x2, y2})
        index !== 0 && this.renderText(ctxRuler, index * 50, (index * 50 * interval - 10) * this.ratio, 25 * this.ratio)
      })
      Array.from({length: Math.ceil(this.canvasHeight / (50 * this.ratio)) / interval}, (item, index) => {
        const x1 = 0
        const x2 = this.canvasWidth
        const y1 = index * 50 * interval * this.ratio
        const y2 = y1
        this.renderSolidLine(ctxRuler, {x1, y1, x2, y2})
        index !== 0 && this.renderText(ctxRuler, index * 50, 10 * this.ratio, (index * 50 * interval + 10) * this.ratio)
      })
      ctxRuler.restore()
    },
    renderSolidLine (ctx, {x1, y1, x2, y2}) {
      ctx.beginPath()
      ctx.moveTo(x1, y1)
      ctx.lineTo(x2, y2)
      ctx.stroke()
      ctx.closePath()
    },
    // 绘制文字
    renderText (ctx, text, textX, textY) {
      ctx.beginPath()
      ctx.strokeText(text, textX, textY)
      ctx.fillText(text, textX, textY)
      ctx.closePath()
    }
  }
}
</script>
<style scoped lang="less">
.canvas{
  width: 100%;
  height: 100%;
}
</style>
