我正在使用 SolidJs 并使用 HopeUi 来处理某些组件。
我使用 HopeUi 的 grid 组件,我想用画布组件填充其中一个网格。
我的应用程序的代码目前如下所示:
import './App.css'
import { Grid, GridItem } from "@hope-ui/solid"
function App() {
return (
<>
<Grid
h="90vh"
templateRows="repeat(2, 1fr)"
templateColumns="repeat(5, 1fr)"
gap="$4"
>
<GridItem rowSpan={1} colSpan={1} bg="black" />
<GridItem colSpan={2} bg="papayawhip" />
<GridItem colSpan={2} bg="papayawhip" />
<GridItem id='c' colSpan={5} bg="tomato">
<canvas id='c' width='100vw' height='100vh' style="border:1px solid #000000;"/>
</GridItem>
</Grid>
</>
)
}
export default App
我尝试将高度和宽度设置为 100% 和 100vw/vh,但没有成功。
如何在不硬编码大小的情况下让画布填充父网格?
画布的
width
和 height
属性表示绘制的像素数,应为整数。要在其定位的父级中直观地填充画布,您可以使用如下函数:
function fitToContainer(canvas) {
canvas.style.width = '100%';
canvas.style.height = '100%';
canvas.width = Math.floor(canvas.offsetWidth);
canvas.height = Math.floor(canvas.offsetHeight);
}
// Example usage
var canvas = document.querySelector('canvas');
fitToContainer(canvas);