我想使用HTML5 Canvas创建一个可点击的6 * 6调色板。我应该可以单击调色板上的每个颜色网格,背景颜色应该更改为所选颜色。
答案 0 :(得分:0)
使用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>