react中实现水印效果

实现的是如下效果,使用的是用户的登录名生成的水印
在这里插入图片描述

代码如下:(只贴了有关代码)

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' }}>
        )}
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值