实现的是如下效果,使用的是用户的登录名生成的水印
代码如下:(只贴了有关代码)
export default class Forum extends React.Component {
componentWillMount() {
// 调用的时候传dom的id名,随便起一个,不重名就行!!!!!
this.getbg('forum')
}
getbg = (data) => {
const watchCanvas = document.createElement('canvas'); // 创建canvas标签
watchCanvas.id = data; // 设置canvas id名
watchCanvas.width = '200'; // 设置画布大小
watchCanvas.height = '150';
watchCanvas.style.display = 'none'; // 删除画布
document.documentElement.appendChild(watchCanvas); // 将画布插入到document中
// 创建 画布内容
const c = document.getElementById(data); // 获取画布
// 获取画布上下文
const ctx = c.getContext('2d');
ctx.clearRect(0, 0, 200, 150);
ctx.fillStyle = "#FFFFFF"
ctx.fillRect(0, 0, 200, 150);
// 设置字体文字大小及字体类型
ctx.font = '15px Arial';
// 设置旋转角度 格式 (-45 * Math.PI) / 180
ctx.rotate((-45 * Math.PI) / 180);
// ctx.strokeStyle = "#fff";
ctx.fillStyle = "#F5F7FA"
// 设置水印实心文字及偏移量 fillText(text, x, y) strokeText(text,x,y) 说明 text | 在画布上出现的值(此处用的用户名), x 在x方向上的值(相对于画布), y 在y方向上的值(相对于画布);
// 这里是背景显示的内容!!!
ctx.fillText(cookie.get('nickName'), -40, 70);
// 生成base64格式的图片路径
const curl = c.toDataURL('image/png');
this.setState({
curl,
})
}
render() {
return (
// 作为背景图使用,其他省略
<div style={{ background: this.state.curl ? `url(${this.state.curl})` : '#FFFFFF' }}>
)}
}