import React, { Component } from 'react';

class CodeView extends Component {
  constructor(props) {
    super(props);
    let canDom = document.createElement('canvas');
    canDom.id = 'ksCanvas';
    canDom.setAttribute('width', '160px');
    canDom.setAttribute('height', '64px');
    canDom.style = 'display: none';
    document.body.appendChild(canDom);
    this.canvas = canDom;
  }
  componentWillUnmount() {
    document.body.removeChild(this.canvas);
  }
  renderImg = () => {
    const { value } = this.props;
    const ctx = this.canvas.getContext('2d');
    ctx.fillStyle = '#F0F0F0';
    ctx.fillRect(0, 0, 160, 64);
    ctx.font = '26px arial';
    // 创建渐变
    var gradient = ctx.createLinearGradient(0, 0, 160, 0);
    gradient.addColorStop('0', 'magenta');
    gradient.addColorStop('0.5', 'blue');
    gradient.addColorStop('1.0', 'red');
    // 用渐变填色
    ctx.strokeStyle = gradient;
    ctx.strokeText(value, 50, 40); //画布上添加验证码
    return this.canvas.toDataURL();
  };
  render() {
    return <img src={this.renderImg()} alt="" />;
  }
}

export default CodeView;
