使用html5画布创建6*6调色板

To create a 6 * 6 color palette using html5 canvas

本文关键字:调色板 创建 html5 布创建 使用      更新时间:2023-09-26

我想使用HTML5 Canvas创建一个可点击的6*6调色板。我应该能够点击调色板上的每个颜色网格,背景颜色应该变为选定的颜色。

使用React,我做到了这一点。也许在看完这个之后,你会知道你需要做什么。

class Palette extends React.Component {
  constructor(props) {
    super(props);
    this.state = { color: '#FFFFFF' };
  }
  
  setColor(row, col) {
    const color = this.getColor(row, col);
    this.setState({ color });
    document.body.style.backgroundColor = color;
  }
  
  getColor(row, col) {
    const hue = Math.floor(col / this.props.height * 360);
    const sat = 100;
    const lit = Math.floor((1 - (row + 1) / (this.props.width + 1)) * 100);
    
    return `hsl(${hue},${sat}%,${lit}%)`;
  }
  
  render() {
    const rows = [];
    
    for (let i = 0; i < this.props.height; i++) {
      const cols = [];
      
      for (let j = 0; j < this.props.width; j++) {
        
        cols.push(
          <div
            className="col"
            onClick={
              () => this.setColor(j, i)
            }
            style={{
              backgroundColor: this.getColor(j, i)
            }} />
        );
      }
  
      rows.push(
        <div className="row">
          {cols}
        </div>
      );
    }
    
    return (
      <div className="palette">
        {rows}
      </div>
    );
  }
}
ReactDOM.render(<Palette width={6} height={6} />, document.body);
.palette {
  display: flex;
  flex: 1;
  flex-direction: column;
  cursor: pointer;
}
.row {
  display: flex;
  flex: 1;
  flex-direction: row;
}
.col {
  width: 20px;
  height: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>