2019-07-21
scale html canvas (html / reactjs)
stackoverflow
Question

I am trying to scale a 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>
    );
  }
}

The code compiles but the canvas scaling is not applied, i've tried different values for the scaling.

As you can see I also tried putting this.setState({}) to force a re-render but the canvas is still not scaled.

I am pretty sure that componentDidMount() is the right method to use because i have to make sure the scaling is applied after the HTML is loaded: Cannot read property 'getContext' of null, using canvas

How can i apply the scaling for the canvas?

Answer
1

Try setting a width and height attribute on the <canvas> element:

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>
    );
  }
};

By the way: I'm not really sure, but shouldn't that <canvas> element in your JSX have a closing tag? Or does JSX handle that different? Not using JSX that much myself.

scale html canvas (html / reactjs)
See more ...