How to make a HTML5 canvas fit dynamic parent/flex box container

前端 未结 4 1090
死守一世寂寞
死守一世寂寞 2021-02-07 04:30

Is there a way I can create a canvas inside a dynamic re-sizing flex-box container?

Preferably a CSS only solution but I think JavaScript is required for redraw?

<
4条回答
  •  庸人自扰
    2021-02-07 05:08

    Think of canvas as an image. If you scale it to a different size than the original it will appear blurry at some point, and perhaps early on depending on interpolation algorithm chosen by the browser. For canvas the browser tend to chose bi-linear over bi-cubic so there is higher risk of blur than with an actual image.

    You will want to have things in canvas rendered as sharp as possible and the only way to this is to adapt the size to the parent using JavaScript, and avoid CSS (the latter is good for things like printing, or when you need "retina resolutions").

    To get the parent container size in pixels you can use getComputedStyle() (see update below):

    var parent = canvas.parentNode,
        styles = getComputedStyle(parent),
        w = parseInt(styles.getPropertyValue("width"), 10),
        h = parseInt(styles.getPropertyValue("height"), 10);
    
    canvas.width = w;
    canvas.height = h;
    

    Fiddle

    (Note: Chrome seem to have some issues with computed flex at the moment)

    Update

    Here's a simpler way:

    var rect = canvas.parentNode.getBoundingClientRect();
    canvas.width = rect.width;
    canvas.height = rect.height;
    

    Fiddle

提交回复
热议问题