<template>
  <div
    class="svga-container"
    ref="svga-container"
    v-bind="$props"
    v-on="$listeners"
  >
    <canvas ref="svga-canvas"></canvas>
  </div>
</template>

<script>
import { Parser, Player } from 'svga'
import { getPureNumber } from '@/utils'
export default {
  name: 'AdSvga',
  props: {
    // 文件地址
    svgaLink: {
      required: true,
      type: String
    }
  },
  mounted() {
    console.log('svag moi')
    try {
      this.init()
    } catch (e) {
      this.$emit('error')
    }
  },
  methods: {
    async init() {
      const parser = new Parser()
      const svga = await parser.load(this.svgaLink)
      const player = new Player(this.$refs['svga-canvas'])

      const scaleX =
        getPureNumber(this.$refs['svga-container'].style.width) /
        svga.size.width
      const scaleY =
        getPureNumber(this.$refs['svga-container'].style.height) /
        svga.size.height
      const scaleRatio = Number((scaleX > scaleY ? scaleX : scaleY).toFixed(3))

      this.$refs['svga-canvas'].style[
        '-webkit-transform'
      ] = `scale(${scaleRatio}, ${scaleRatio})`
      this.$refs[
        'svga-canvas'
      ].style.transform = `scale(${scaleRatio}, ${scaleRatio})`

      await player.mount(svga)
      player.start()
      this.$emit('load')
    }
  }
}
</script>
<style lang="scss" scoped>
.svga-container {
  width: 100%;
  height: 100%;
  canvas {
    transform-origin: 0 0;
  }
}
</style>
