首页 > 解决方案 > 缩放 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

如何为画布应用缩放?

标签: javascripthtmlreactjshtml5-canvasscaling

解决方案


尝试在元素上设置一个widthandheight属性:<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。


推荐阅读