react添加水印

import React, { Component } from 'react';
import request from '$src/services';
import APIS from '$src/services/api';
import { Toast } from 'antd-mobile';
import './index.scss';

export default class AppRoot extends Component {
  constructor(props) {
    super(props);
    this.state = {
      curl: '',
      userInfo: ''
    };
  }

  componentDidMount() {
    this.fetchCurrentUser();
  }

  fetchCurrentUser = async () => {
    const res = await request(APIS.currentUser, {
      method: 'GET',
    });
    if (res.success) {
      const realName = res.data.realName && res.data.realName || '';
      const userName = res.data.userName && res.data.userName || '';
      const userInfo = realName + '(' + userName + ')';
      this.setState({
        userInfo
      }, () => {
        this.getbg('forum', this.state.userInfo);
      });
    } else {
      Toast.fail(res.error.msg, 1);
    }
  }

  getbg = (data, userInfo) => {
    const watchCanvas = document.createElement('canvas'); // 创建canvas标签
    watchCanvas.id = data; // 设置canvas id名
    watchCanvas.width = '200'; // 设置画布大小
    watchCanvas.height = '300';
    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 = 'rgba(255, 255, 255, 0.2)';
    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 = '#d6d6d6';
    // 设置水印实心文字及偏移量 fillText(text, x, y) strokeText(text,x,y)  说明 text | 在画布上出现的值(此处用的用户名), x 在x方向上的值(相对于画布), y 在y方向上的值(相对于画布);
    // 这里是背景显示的内容!!!
    ctx.fillText(userInfo, -40, 70);
    // 生成base64格式的图片路径
    const curl = c.toDataURL('image/png');
    this.setState({
      curl,
    });
  }

  render() {
    const { curl } = this.state;
    return (
      
{this.props.children} ); } }
.water-mark{
    display: block;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
    background: transparent;
    pointer-events: none;
    z-index: 100;
  }

 

你可能感兴趣的:(React)