首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >缩放html画布(html / reactjs)

缩放html画布(html / reactjs)
EN

Stack Overflow用户
提问于 2018-11-30 00:07:56
回答 2查看 1.3K关注 0票数 1

我正试着爬上画布:

代码语言:javascript
运行
复制
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()是正确使用的方法,因为我必须确保在加载了Cannot read property 'getContext' of null, using canvas之后应用了缩放。

如何将缩放应用于画布?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-11-30 01:26:45

尝试在width元素上设置<canvas>height属性:

代码语言:javascript
运行
复制
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>
    );
  }
};

顺便问一句:我不太确定,但是你的JSX中的<canvas>元素不应该有一个结束标记吗?或者JSX处理的方式有那么不同?我自己也没这么多地使用过JSX。

票数 2
EN

Stack Overflow用户

发布于 2019-07-19 12:25:45

尝试将属性画布设置为组件状态,并在componentDidMount中生成setState({width:600,heigth:500})

代码语言:javascript
运行
复制
    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>
    );
  }
};

这个必须找到

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53549401

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档