I’m working in SolidJs and using HopeUi for some components.
I use the grid component from HopeUi, and I want to fill one of the grids with a canvas component.
The code for my App currently looks like this:
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
The resulting page looks like this:
I’ve tried setting the height and width to both 100% and 100vw/vh, but to no luck.
How can I make the canvas fill the parent grid without hardcoding the size?
3
Answers
The
width
andheight
attributes of a canvas represent the number of pixels for drawing and should be integers. To visually fill the canvas within its positioned parent, you can use a function like this:According to specification,
width
andheight
properties ofcanvas
will take values inpx
only (not vm or %).You can change its
width
andheight
with css or inline styling:CSS
HTML
Note that this doesn’t help with canvas
width
andheight
which they are real sizes that canvas API uses to determine your canvas dimensions and accordingly all shapes that it draws inside this canvas.You must use javascript for solving this:
If you’re interested why canvas
width
andheight
properties not behave the same as csswidth
andheight
, that’s because they are not for styling and actually not same as csswidth
andheight
properties except for their names.They are just properties of canvas object like
name
is a property offoo
object in:As it is stated in the other answers, you need to need to use pixel value with the canvas element.
If you need to interact with the underlying element imperatively, it is best to use a ref:
You can find a working demo: https://www.solidjs.com/tutorial/bindings_forward_refs