首页 > 解决方案 > 绘制画布并使用反应钩子动态更改其大小

问题描述

我想测量画布父元素的尺寸 - 重新测量画布元素然后绘制。这可以使用单个钩子吗?我不想使用任何外部包。

useLayoutEffect 钩子在固定宽度和高度下工作正常。

我尝试过的事情:

  1. 单独使用 useEffect 钩子和这两者的组合。
  2. 将宽度和高度作为道具传递
import React, { useState, useRef, useLayoutEffect } from 'react';

export default props => {
  const [width, setWidth] = useState(0);
  const [height, setHeight] = useState(0);
  const pixelRatio = window.devicePixelRatio;
  const ref = useRef(null);
  const canvas = useRef(null);

  useLayoutEffect(() => {
    setWidth(ref.current.clientWidth);
    setHeight(ref.current.clientHeight);
    const context = canvas.current.getContext('2d');

    // some canvas stuff..
    context.beginPath()
    context.moveTo(0,height/2)
    context.lineTo(width, height/2)
    context.stroke()
  }, []);

  const displayWidth = Math.floor(pixelRatio * width);
  const displayHeight = Math.floor(pixelRatio * height);
  const style = { width, height };

return (
    <div style={{ width: '100%', height: '100%' }} ref={ref}>
      <canvas
        ref={canvas}
        width={displayWidth}
        height={displayHeight}
        style={style}
      />
    </div>
  );
};

结果,我得到了正确调整大小的空白画布。

标签: reactjs

解决方案


这似乎工作正常 - 不知道它是否是最佳答案,如果不是,请发表评论。

import React, { useState, useRef, useEffect, useLayoutEffect } from 'react';

export default props => {
  const [width, setWidth] = useState(0);
  const [height, setHeight] = useState(0);
  const pixelRatio = window.devicePixelRatio;
  const ref = useRef(null);
  const canvas = useRef(null);

  // responsive width and height
  useEffect(() => {
    setWidth(ref.current.clientWidth);
    setHeight(ref.current.clientHeight > 400 ? ref.current.clientHeight : 400);
  }, []);

  useLayoutEffect(() => {
    const context = canvas.current.getContext('2d');

    // some canvas stuff..
    context.beginPath()
    context.moveTo(0,height/2)
    context.lineTo(width, height/2)
    context.stroke()
  }, [width, height]);

  const displayWidth = Math.floor(pixelRatio * width);
  const displayHeight = Math.floor(pixelRatio * height);
  const style = { width, height };

return (
    <div style={{ width: '100%', height: '100%' }} ref={ref}>
      <canvas
        ref={canvas}
        width={displayWidth}
        height={displayHeight}
        style={style}
      />
    </div>
  );
};

推荐阅读