首页 > 解决方案 > 如何根据某些数据更改画布元素内的颜色?

问题描述

我有一个画布元素。我希望它里面的颜色根据一些数据而改变?有人可以帮我吗?

import React from 'react';

class Canvas extends React.Component {

    componentDidMount() {
        this.updateCanvas();
    }
    updateCanvas() {
      const ctx = this.refs.canvas.getContext('2d');
      var grd=ctx.createLinearGradient(50,0,40,0);
      grd.addColorStop(0,"#A52A2A");
      grd.addColorStop(1/4,"#00597d");
      ctx.fillStyle = grd;
      ctx.fillRect(0,0, 100, 100);
    }
    render() {
        return (
            <canvas ref="canvas" width={this.props.width} height={this.props.height}/>
        );
    }
}

export default Canvas;

标签: javascriptcssreactjscanvasreact-redux

解决方案


这是一个基于 React 状态更改数据的快速示例。这应该提供以其他方式更改颜色所需的基础知识。(您可以用输入替换选择标签,或使用 fetch 从服务器获取一些数据。)

    class Canvas extends React.Component {
    // The constructor is used to set default values for your Colors (#A52A2A, #00597d).
      constructor(props) {
        super(props);
        this.state = {
            colorOne: "#A52A2A",
            colorTwo: "#00597d"
        };
        this.updateComponent = this.updateComponent.bind(this);
      }
    // Update the canvas on componentDidMount as the canvas is not present before mounting
      componentDidMount() {
        this.updateCanvas();
      }
    // Update the canvas on any changes to the React state.
      componentDidUpdate() {
        this.updateCanvas();
      }
    // Set new values for the React state based on the option selected.
      updateComponent(event) {
        this.setState({
            [event.target.name]: event.target.value
        });
      }   
    // Update the canvas.
      updateCanvas() {
        const ctx = this.refs.canvas.getContext('2d');
        var grd=ctx.createLinearGradient(50,0,40,0);
        grd.addColorStop(0,this.state.colorOne);
        grd.addColorStop(1/4,this.state.colorTwo);
        ctx.fillStyle = grd;
        ctx.fillRect(0,0, 100, 100);
      }
    // render the canvas and a way for the user to change the canvas color. 
      render() {
        return (
            <div>
                <canvas ref="canvas" width={this.props.width} height={this.props.height}/>
                <select type="select" onChange={this.updateComponent} name="colorOne">
                    <option value="#A52A2A">Original</option>
                    <option value="#ff0000">Red</option>
                    <option value="#bfff00">Green</option></select>
                <select type="select" onChange={this.updateComponent} name="colorTwo">
                    <option value="#00597d">Original</option>
                    <option value="#ff0000">Red</option>
                    <option value="#bfff00">Green</option></select>
            </div>
        );
      } 
  } export default Canvas;

推荐阅读