【问题标题】:Why canvas is not shown correct fill in react component?为什么画布没有显示正确填充反应组件?
【发布时间】:2019-08-12 18:12:29
【问题描述】:

我正在尝试在 react 组件中创建一个非常简单的画布。但是画布没有以正确的颜色显示。

import React, { Component } from 'react'

export default class Home extends Component {
  constructor(props) {
    super(props)
    this.canvasRef = React.createRef();


  }

  componentDidMount() {
    const canvas = this.canvasRef.current;
    const ctx = canvas.getContext('2d')
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    ctx.fillStyle = 'blue'

  }
  render() {
    return (
      <div>
        Welcome to Home Page!
        <div className="clearfix"></div>
        <canvas ref={this.canvasRef} />
      </div>
    )
  }
}

我刚刚看到一个默认的 150*300 默认画布填充黑色。我想我把它设计成蓝色。为什么会这样?

【问题讨论】:

    标签: reactjs canvas html5-canvas


    【解决方案1】:

    你应该在fillRect之前使用fillStyle之前

    你的代码应该是:

    ctx.fillStyle = "blue";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    

    演示:

    【讨论】:

    【解决方案2】:

    @Kareem 解决方案有效,但由于没有解释,这里是:

    当您调用fillRect() 方法时,您是在告诉画布要绘制,因此您需要在绘制之前设置它的属性。

    如documentation:

    fillRect() 方法绘制一个填充矩形,其起点为 在 (x, y) 处,其大小由宽度和高度指定。填充物 样式由当前的fillStyle 属性决定。

    所以,如果你在设置fillStyle之前绘制它,它会显示为黑色。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多