<template>
  <div ref="dom">
    <div ref="parentDom" style="position: relative;">
     <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: "ElWaterMark",
  props: {
    text: {
      type: String,
      default: ''
    },
    url: {
      type: String,
      default: ''
    },
    width: {
      type: Number,
      default: 200
    },
    height: {
      type: Number,
      default: 200
    },
    opacity: {
      type: Number,
      default: 0.15
    },
    fontColor: {
      type: String,
      default: 'black'
    },
    fontSize: {
      type: String,
      default: '14'
    },
    fontWeight: {
      type: String,
      default: '400'
    },
    rotate: {
      type: Number,
      default: 0
    },
    x: {
      type: Number,
      default: 180
    },
    y: {
      type: Number,
      default: 120
    }
  },
  updated() {
    this.init()
  },
  mounted() {
    const that = this
    window.onresize = () => {
      that.init()
    }
    this.init()
  },
  methods: {
    init() {
      const canvas = document.createElement('canvas')
      canvas.width = document.body.clientWidth
      canvas.height = document.body.clientHeight
      canvas.style.position = 'absolute'
      const ctx = canvas.getContext('2d')
      ctx.globalAlpha = this.opacity
      ctx.rotate(Number(this.rotate) * Math.PI / 180)
      if (this.text !== '') {
        this.drawText(canvas, ctx)
      }
      if (this.url !== '') {
        this.drawImage(canvas, ctx)
      }  
    },
    drawText(canvas, ctx) {
      ctx.font = `${this.fontWeight} ${this.fontSize}px Verdana`
      ctx.fillStyle = this.fontColor
      for (let i = 0; i < document.body.clientWidth / this.width; i++) {
        for(let j = 0; j < document.body.clientHeight / this.height; j++) {
          ctx.fillText(this.text, i * this.x - 80, j * this.y + (i * (this.y / 2) + 30))
        }
      }
      ctx.textAlign = 'left'
      ctx.textBaseline = 'top'
      const base64Url = canvas.toDataURL()
      this.$refs.dom.style.background = `url(${base64Url}) no-repeat`
    },
    drawImage(canvas, ctx) {
      const img = new Image()
      img.setAttribute('crossorigin', 'anonymous')
      img.src = this.url
      img.onload = () => {
        for (let i = 0; i < document.body.clientWidth / this.width; i++) {
          for(let j = 0; j < document.body.clientHeight / this.height; j++) {
            ctx.drawImage(img, i * this.x - 80, j * this.y + (i * (this.y / 2) + 30))
          }
        }
        const base64Url = canvas.toDataURL()
        this.$refs.dom.style.background = `url(${base64Url}) no-repeat`
      }
    }
  },
  destroyed() {
    window.onresize = null
  },
}
</script>

