Vue 中给图片添加时间水印
Vue 中给图片添加时间水印,可以通过在图片上叠加一层带有日期时间的透明图层来实现。具体的实现方式及步骤如下:
-
在 Vue 的 template 中加载原始图片和水印图片。
-
在 Vue 的 script 中计算日期时间字符串,并根据需要生成对应的日期时间图片(可以借助
Canvas
API 来绘制)。 -
在 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
属性来改变水印图片的透明度。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律