簡體   English   中英

如何根據某些數據更改畫布元素內的顏色?

[英]How can I change the color inside a canvas element according to some data?

我有一個畫布元素。 我想讓里面的顏色根據一些數據改變? 有人可以幫我嗎?

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;

這是一個基於 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM