javascript - 如何根据某些数据更改画布元素内的颜色?
问题描述
我有一个画布元素。我希望它里面的颜色根据一些数据而改变?有人可以帮我吗?
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;
推荐阅读
- excel - Excel 到 Outlook:.Send 返回运行时错误
- javascript - 在 HTML Blob 中保留元标记的字符集属性?
- ios - MvvmCross 无法解析类型
- teamcity - 如何设置未版本化的设置文件并在 TeamCity 中读取
- message-queue - Google Pub/Sub 性能(低负载下的延迟)?
- python - 通过 RSA 解密时 Python 接收 MAC 检查失败
- c# - 精简模型以查看翻译
- sql-server - 添加名称列并为每个名称分配 5 个会话 ID
- excel - 如果两列的行中的值相等,我如何实现对话框消息?
- angular - 需要我的 Angular 应用程序连接到 nodemailer