【问题标题】:With flex box, setting canvas's width and height with parent node's clientWidth and Height hides sticky footer使用 flex box,使用父节点的 clientWidth 和 Height 设置画布的宽度和高度隐藏粘性页脚
【发布时间】:2020-04-21 11:34:28
【问题描述】:

我正在尝试在下面创建列布局,即页眉、内容和粘性页脚。 我希望画布的宽度和高度使用 JavaScript 跟随其内容的 clientWidth 和 clientHeight。

<style>
body {
;   margin          : 0
;   height          : 100%
;   display         : flex
;   flex-direction  : column
}

header,
footer {
;   flex    : 0
}

#content {
;   flex    : 1
}
</style>

<header>header</header>
<div id=content>
    <canvas id=canvas></canvas>
</div>
<footer>footer</footer>

<script>
    canvas = document.getElementById( 'canvas' )
    ctx = canvas.getContext( '2d' )
    const
    FitCanvas = () => {
        canvas.width = canvas.parentNode.clientWidth
        canvas.height = canvas.parentNode.clientHeight
        ctx.beginPath()
        ctx.moveTo( 0, 0 )
        ctx.lineTo( canvas.width, canvas.height )
        ctx.stroke()
    }
    window.addEventListener(
        'resize'
    ,   FitCanvas
    )
    FitCanvas()
</script>

展开窗口时看起来不错。但是当缩小窗口时,页脚不会粘住。

首字母:

扩展:

缩小:

我想让缩小的图像与初始图像匹配。

请帮忙,提前谢谢。

【问题讨论】:

    标签: javascript html css canvas flexbox


    【解决方案1】:

    当您扩展视口时,FitCanvas 使画布更大,从而使&lt;div id=content&gt; 更大。当您缩小视口时,&lt;div id=content&gt; 会保持适合其子级的大小,即canvas

    您应该重写您的 FitCanvas 函数,不要将其计算基于父级的大小。

    canvas.width = canvas.parentNode.clientWidth
    canvas.height = canvas.parentNode.clientHeight
    

    应该变成类似于

    的东西
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight - header.offsetHeight - footer.offsetHeight
    

    这不是最有效的做事方式,但希望它能为您指明正确的方向,并且您会明白为什么 'resize' 处理程序似乎只能以一种方式工作。

    【讨论】:

    • 谢谢,这是完美的答案。
    猜你喜欢
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 2016-11-08
    • 2014-06-15
    • 1970-01-01
    • 2015-03-18
    • 2020-03-29
    • 2017-12-14
    相关资源
    最近更新 更多