Limiting (clamping) canvas size
I want to make moveable world for my HTML game so I put 1600x1200 canvas inside my 800x600 div element and using left and top to move the world. I expected that div will clamp size of my canvas, but instead my canvas overlaps borders of my div. The div doesn't stretch, the canvas is scaled independently from the div.
I tried !important, max-width and 开发者_运维问答max-height, different displays, nothing works. Using CSS for width and height just scales the canvas. I also tried putting my canvas into SVG as foreign object, but I get error "getContext is not a function".
So, how can I limit size of my canvas?
The div
is going to expand to the size of your canvas
unless the div
has overflow: hidden;
set in its CSS. The child element is larger than the parent element, and you haven't strictly told the browser to limit the sizing of the parent element.
The max-width
and max-height
attributes won't help you here because you aren't placing "wrappable" content within the div
. If you put text in a div
with max-width
set, the value will be respected. If you put an element with an unchanging size, like an image
or a canvas
element, the browser can't dynamically wrap it like a bunch of floating divs
or some text. In this case, you have overflow
, which needs to be handled differently.
You can achieve what you're looking for by playing with the position
and/or margin
attributes for the canvas
element once you set the parent div
to hide the overflow.
精彩评论