简体   繁体   English

如何在反应中获得正确的画布宽度和高度?

[英]How to get correct width and height for a canvas in react?

I am trying to use canvas in React. 我正在尝试在React中使用canvas。 the following code is supposed to give me a black 800x800 canvas, but for some reason it ignores my dimensions and shows a 300x150 canvas. 以下代码应该给我黑色的800x800画布,但是由于某种原因,它会忽略我的尺寸并显示300x150的画布。

import React, {Component} from "react";

class Sample extends Component {

    state = {
        canvasWidth: 800,
        canvasHeight: 800
    }
    canvasRef = React.createRef();

    componentDidMount() {
        const canvas = this.canvasRef.current;
        const context = canvas.getContext('2d');
        context.fillRect(0, 0, this.state.canvasWidth, this.state.canvasHeight);
    }

    render() {
        return (
            <div>
                <canvas ref={this.canvasRef} />
            </div>
        );
    }
}

export default Sample

您需要将width和height设置为html属性:

   <canvas ref={this.canvasRef} width={this.state.canvasWidth} height={this.state.canvasHeight}/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在渲染之前获取反应组件的大小(高度/宽度)? - How to get a react component's size (height/width) before render? 如何在不调用 window 的情况下在 React 中获取设备宽度/高度 object - How to get device width/height in React without calling the window object 如何使用 Hooks 在 React 中获取父级宽度/高度? - How to get parent width/height in React using Hooks? 如何从 React Native 上的 uri 获取图像高度和宽度? - How to get image height and width from uri on React Native? 如何使用本机反应在样式表文件中获取 window 宽度和高度? - How to get the window width and height in stylesheet file using react native? 在React中上传图片时如何获取图片的高度和宽度? - How to get image Height and Width while uploading image in React? 如何使用 React 使普通 Three.js Canvas 跨越网页的视图高度和宽度? - How to make a Plain Three.js Canvas span across the view height and width of a webpage using React? 如何在 react componentDidUpdate 中使用 ref 获得正确的元素宽度 - How to get correct width of element with ref in react componentDidUpdate 反应图表:防止图表的 canvas 随高度和宽度缩放 - React chart : prevent chart's canvas scaling with height and width 我无法在反应中获得画布宽度 - I can't get the canvas width in react
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM