javascript - 缩放 html 画布(html / reactjs)
问题描述
我正在尝试缩放画布:
class DungeonMap extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const canvas = this.refs.canvas;
const ctx = canvas.getContext('2d');
ctx.scale(2, 2)
this.setState({})
}
render() {
console.log("render")
return (
<div className="DungeonMap">
<canvas ref="canvas" style={canvasStyle}/>
</div>
);
}
}
代码编译但未应用画布缩放,我尝试了不同的缩放值。
如您所见,我也尝试this.setState({})
强制重新渲染,但画布仍未缩放。
我很确定这componentDidMount()
是正确的使用方法,因为我必须确保在加载 HTML 后应用缩放:Cannot read property 'getContext' of null, using canvas
如何为画布应用缩放?
解决方案
尝试在元素上设置一个width
andheight
属性:<canvas>
class DungeonMap extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const canvas = this.refs.canvas;
// to scale the <canvas> element itself
canvas.width = 500;
canvas.height = 500;
// to scale the drawings, use the context
const ctx = canvas.getContext('2d');
ctx.scale(2, 2);
}
render() {
console.log("render")
return (
<div className="DungeonMap">
<canvas ref="canvas" style={canvasStyle}/>
</div>
);
}
};
顺便说一句:我不太确定,但是<canvas>
JSX 中的那个元素不应该有一个结束标签吗?还是 JSX 处理的不同?我自己没有那么多使用 JSX。
推荐阅读
- c# - 在 listview winform c# 中列出 S3 Bucket 键
- javascript - 在下拉列表中的 0 索引上插入值
- java - OnTouchListener webview 总是循环
- javascript - React-Native Javascript 搜索过滤功能
- python - 如何在数据框中纠正拼写错误的单词?
- r - 以最小距离连接矩阵的两个坐标
- visual-studio-code - VSCode,Intellisense C++ 自动完成功能不起作用,ubuntu 20.04
- wordpress - WooCommerce 如果订单状态正在处理,则该特定订单中的产品将从商店隐藏
- python - pygetwindow 模块是做什么用的?
- javascript - CSS:创建流程步骤样式