我正在尝试缩放 Canvas :
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>
);
}
}
代码编译但未应用 Canvas 缩放,我尝试了不同的缩放值。
如您所见,我也尝试过放置 this.setState({})
以强制重新渲染,但 Canvas 仍未缩放。
我非常确定 componentDidMount()
是正确的使用方法,因为我必须确保在加载 HTML 后应用缩放:Cannot read property 'getContext' of null, using canvas
如何为 Canvas 应用缩放?
最佳答案
尝试设置一个 width
和 height
<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。
关于javascript - 缩放 html Canvas (html/reactjs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53549401/