Vue 中给图片添加时间水印

发布时间 2023-03-29 14:45:29作者: 技术杨

Vue 中给图片添加时间水印,可以通过在图片上叠加一层带有日期时间的透明图层来实现。具体的实现方式及步骤如下:

  1. 在 Vue 的 template 中加载原始图片和水印图片。

  2. 在 Vue 的 script 中计算日期时间字符串,并根据需要生成对应的日期时间图片(可以借助 Canvas API 来绘制)。

  3. 在 Vue 的 style 中设置相应的样式,使得日期时间图片覆盖在原始图片之上。

下面是一个简单的 Vue 组件示例,使用 Canvas 绘制日期时间图片并将其叠加到原图片上:

<template>
  <div class="watermark-img-wrapper">
    <img class="watermark-img" :src="source" alt="">
    <div class="watermark-overlay" :style="{ backgroundImage: `url(${watermark})`, opacity }"></div>
  </div>
</template>

<script>
export default {
  props: {
    source: {
      type: String,
      required: true,
    },
    name: {
      type: String,
      default: '',
    },
    opacity: {
      type: Number,
      default: 0.5,
    },
  },
  data() {
    return {
      watermarkUrl: '',
    }
  },
  mounted() {
    const img = new Image()
    img.crossOrigin = 'anonymous'
    img.onload = () => {
      const canvas = document.createElement('canvas')
      const context = canvas.getContext('2d')
      canvas.width = img.width
      canvas.height = img.height

      // draw the original image on canvas
      context.drawImage(img, 0, 0)

      // draw the name or datetime on canvas
      const text = this.name || new Date().toLocaleString()
      context.font = '16px sans-serif'
      context.fillStyle = 'white'
      context.fillText(text, 10, canvas.height - 10)

      this.watermarkUrl = canvas.toDataURL()

      // update the position of the overlay
      const wrapper = this.$el.querySelector('.watermark-img-wrapper')
      const position = wrapper.getBoundingClientRect()
      const overlay = this.$el.querySelector('.watermark-overlay')
      overlay.style.left = `${position.left}px`
      overlay.style.top = `${position.top}px`
      overlay.style.width = `${position.width}px`
      overlay.style.height = `${position.height}px`
    }
    img.src = this.source
  },
}
</script>

<style scoped>
.watermark-img-wrapper {
  position: relative;
}

.watermark-img {
  display: block;
  max-width: 100%;
  height: auto;
}

.watermark-overlay {
  position: absolute;
  background-repeat: no-repeat;
  background-size: contain;
}
</style>

这个组件接受三个属性:

  • source: 原始图片的地址。
  • name: 名字水印的内容,如果不传则会默认显示日期时间水印。
  • opacity: 时间或名字水印图片的透明度,取值范围为 0 到 1,默认值为 0.5。

使用这个组件,我们可以在 Vue 实例中这样调用:

<template>
  <div>
    <NameOrDateTimeWatermarkImage source="https://example.com/image.jpg" name="John"></NameOrDateTimeWatermarkImage>
  </div>
</template>

<script>
import NameOrDateTimeWatermarkImage from '@/components/NameOrDateTimeWatermarkImage'

export default {
  components: { NameOrDateTimeWatermarkImage },
}
</script>

当加载完成后,这个组件会自动计算出时间或名字水印图片的大小和位置,覆盖在原始图片上。可以通过调整 opacity 属性来改变水印图片的透明度。