Tagor
Tagor

Reputation: 1006

scale html canvas (html / reactjs)

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?

Upvotes: 1

Views: 2062

Answers (2)

Enrikisimo Lopez Ramos
Enrikisimo Lopez Ramos

Reputation: 393

try to set a property canvas in a state of component and in the componentDidMount makes setState({width:600,heigth:500})

    class DungeonMap extends Component {
  constructor(props) {
    super(props);
this.state={
        width:200,
        height:300
}
  }
  componentDidMount() { 
    const canvas = this.refs.canvas;

    // to scale the <canvas> element itself
    canvas.width = this.state.widht;
    canvas.height = this.state.height;

    // to scale the drawings, use the context
    const ctx = canvas.getContext('2d');
    ctx.scale(2, 2);
  this.setState({widht:1000,height:800})
  }
  render() {
    console.log("render")
    return (   
      <div className="DungeonMap">             
        <canvas ref="canvas" style={canvasStyle}/>
      </div>
    );
  }
};

this must found

Upvotes: 0

Davi
Davi

Reputation: 4147

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.

Upvotes: 2

Related Questions