vue背景图片及背景纯色加水印

1、背景图片

在main.js写

Vue.prototype.drawAndShareImage = async (width, height, url, text, callback) => {
var canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
var context = canvas.getContext('2d')

context.rect(0, 0, canvas.width, canvas.height)

var myImage = new Image()
myImage.src = url.replace(/ /g, '').replace(/"/g, '')
myImage.crossOrigin = 'Anonymous'

myImage.onload = () => {
context.drawImage(myImage, 0, 0, width, height)
let text1 = ''
for (let i = 0; i < 30; i++) {
text1 += (' ' + text)
}
for (let i = 0; i < 2000; i++) {
context.rotate((-45 * Math.PI) / 180) // 水印初始偏转角度
context.font = '20px microsoft yahei'
context.fillStyle = 'rgba(255,255,255,0.15)'
context.fillText(text1, -1000, i * 90)
context.rotate((45 * Math.PI) / 180) // 把水印偏转角度调整为原来的,不然他会一直转
}
// varbase64=
// dom.style.backgroundImage = 'url(\'' + base64 + '\')'
callback(canvas.toDataURL('image/png'))
}
}

在组件中调用

let img = document.getElementsByClassName('className')[0]
let style = img.currentStyle || window.getComputedStyle(img, false)
let bi = style.backgroundImage.replace('url(', '').replace(')', '')
this.drawAndShareImage(img.offsetWidth, img.offsetHeight, bi, '文字内容', (url) => {
img.setAttribute('style', 'background:url("' + url + '")')
})

2、纯色背景水印

Vue.prototype.watchCanvs = (width, height, text, classname) => {
let canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
let context = canvas.getContext('2d')
let text1 = ''
for (let i = 0; i < 30; i++) {
text1 += (' ' + text)
}
for (let i = 0; i < 2000; i++) {
context.rotate((-45 * Math.PI) / 180) // 水印初始偏转角度
context.font = '20px microsoft yahei'
context.fillStyle = 'rgba(0,0,0,0.1)'
context.fillText(text1, -1000, i * 90)
context.rotate((45 * Math.PI) / 180) // 把水印偏转角度调整为原来的,不然他会一直转
}

// 生成base64格式的图片路径
let curl = canvas.toDataURL('image/png')
// 将图片作为背景样式插入
classname.style.background =
'#ffffff url(' + curl + ')'
}

在组件中调用

let div = document.getElementsByClassName('className')[0]
this.watchCanvs(div.offsetWidth, div.offsetHeight, '文字内容', div)

 

posted @ 2020-02-26 11:44  sosolucky  阅读(2417)  评论(0编辑  收藏  举报