HTML5 canvas元素不继承父级的宽度和高度?为什么?

时间:2014-12-01 18:15:41

标签: css html5-canvas

canvas1和canvas2没有像我期望的那样从css继承父宽度和高度。我可以通过使用javascript明确指定canvas1和canvas2的宽度和高度来解决这个问题,但我希望用一种不那么强硬的方法来解决这个问题,即纯css。

`

<!DOCTYPE HTML>
<html>
    <head>
        <style>
            #parent {
                width: 1000px;
                height: 600px;
            }

            #div1 {
                position: absolute;
                z-index:0;
            }

            #div2 {
                position: absolute;
                z-index:1;
            }
        </style>
    </head>
    <body>
        <div id="parent">
            <div id="div1">
                <canvas id="canvas1">
                </canvas>
            </div>
            <div id="div2">
                <canvas id="canvas2">
                </canvas>
            </div>
        </div>
        <script>
            var parent = document.getElementById("parent");
            var parentWidth = parent.offsetWidth;
            var parentHeight = parent.offsetHeight;

            alert("parentWidth = " + parentWidth);
            alert("parentHeight = " + parentHeight);

            var div1 = document.getElementById("div1");
            var div1Width = div1.offsetWidth;
            var div1Height = div1.offsetHeight;

            alert("div1Width = " + div1Width);
            alert("div1Height = " + div1Height);

            var canvas1 = document.getElementById("canvas1");
            var canvas1Width = canvas1.offsetWidth;
            var canvas1Height = canvas1.offsetHeight;

            alert("canvas1Width = " + canvas1Width);
            alert("canvas1Height = " + canvas1Height);

            var div2 = document.getElementById("div2");
            var div2Width = div2.offsetWidth;
            var div2Height = div2.offsetHeight;

            alert("div2Width = " + div2Width);
            alert("div2Height = " + div2Height);

            var canvas2 = document.getElementById("canvas2");
            var canvas2Width = canvas2.offsetWidth;
            var canvas2Height = canvas2.offsetHeight;

            alert("canvas2Width = " + canvas2Width);
            alert("canvas2Height = " + canvas2Height);
        </script>
    </body>
</html>      `

0 个答案:

没有答案