reactjs - 绘制画布并使用反应钩子动态更改其大小
问题描述
我想测量画布父元素的尺寸 - 重新测量画布元素然后绘制。这可以使用单个钩子吗?我不想使用任何外部包。
useLayoutEffect 钩子在固定宽度和高度下工作正常。
我尝试过的事情:
- 单独使用 useEffect 钩子和这两者的组合。
- 将宽度和高度作为道具传递
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>
);
};
结果,我得到了正确调整大小的空白画布。
解决方案
这似乎工作正常 - 不知道它是否是最佳答案,如果不是,请发表评论。
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>
);
};
推荐阅读
- javascript - loadable-components:无法异步加载组件
- macos - 无法在另一台 MacBook 上运行 QT macOS 应用程序
- html - CSS使div填充2行
- html - 中心分区盒
- single-spa - SSPA:我们如何在每个单水疗应用程序中拥有具有两个不同版本的相同 npm 包
- vb.net - TRY CATCH VB.NET 上的 PUT 请求 JSON 异常
- java - chilkatsoft Java 数字签名
- javascript - 如何在nodejs中调用该存储类型和过程的参数?
- highcharts - 图例在饼图高图中显示顺序
- batch-file - 批处理 - 获取包含特殊字符的参数