You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SolidJs中让Canvas填充父级Grid容器?

让Canvas填充HopeUI GridItem容器的解决方案

要实现Canvas无需硬编码尺寸即可填充父级GridItem容器,核心要区分Canvas的原生像素尺寸属性和CSS显示尺寸,同时结合SolidJS的DOM操作能力动态同步两者。以下是具体实现方案:

关键步骤说明

  1. 给GridItem设置相对定位,作为Canvas绝对定位的参考上下文
  2. 用CSS让Canvas在显示层面占满父容器
  3. 通过JS动态同步Canvas的原生宽高与容器尺寸,避免绘制内容模糊

修改后的完整代码

import './App.css'
import { Grid, GridItem } from "@hope-ui/solid"
import { onMount } from 'solid-js'

function App() {
  let canvasRef;
  let containerRef;

  // 初始化画布尺寸 + 监听窗口 resize
  onMount(() => {
    const updateCanvasSize = () => {
      if (canvasRef && containerRef) {
        const { width, height } = containerRef.getBoundingClientRect();
        // 同步画布的原生像素尺寸,避免拉伸模糊
        canvasRef.width = Math.floor(width);
        canvasRef.height = Math.floor(height);
      }
    }

    updateCanvasSize();
    window.addEventListener('resize', updateCanvasSize);
    return () => window.removeEventListener('resize', updateCanvasSize);
  });

  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 
          ref={containerRef} 
          colSpan={5} 
          bg="tomato" 
          position="relative"
        >
          <canvas 
            ref={canvasRef}
            style="position:absolute; top:0; left:0; width:100%; height:100%; border:1px solid #000000;"
          />
        </GridItem>
      </Grid>
    </>
  )
}

export default App

细节解释

  • GridItem添加position="relative":让Canvas的绝对定位以该容器为基准,不会超出父容器范围
  • Canvas的CSS样式:通过position:absolute和width/height:100%实现显示层面完全填充父容器
  • 动态同步尺寸:利用getBoundingClientRect()获取容器的实际显示尺寸,赋值给Canvas的原生width和height属性,保证画布的像素分辨率与显示尺寸匹配,避免绘制图形时出现拉伸模糊
  • 监听窗口resize:确保窗口尺寸变化时,画布能自动适配新的容器尺寸

内容的提问来源于stack exchange,提问作者Vetle Hofsøy-Woie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 21:53:25