0

我有一个带有一些工具的画布,它在一个 div 中。如何根据用户输入的画布宽度和高度自动调整 div?

<div id="container">
    <canvas id="theCanvas" width="<?php echo $_POST['inputwidth'] ?>" height="<?php echo $_POST['inputheight'] ?>"></canvas>
<div class="tools">
<span class="icon"> 
    <button id="brushTool"></button>
</span>
</div>
</div>

我试过设置 min-height 和 min-width 但没有用。容器的边框跟随浏览器的大小。如果我将最大高度/宽度设置为 php + 一定的边距,是否有可能?多谢你们!=)

#container{
    border-right: dotted black 5px;
    border-left: dotted black 5px;
    border-top: dotted black 5px;
    border-bottom: dotted black 5px;
    margin: auto;
}

#theCanvas {
    border: solid black 5px;
    border-radius: 10px;
    background: #ffffff;
    margin-left: 20%;
    margin-top: 20px;
    margin-bottom: 20px;
    cursor: crosshair;
}
4

1 回答 1

0

很抱歉这么久才回复,希望您已经找到答案。

一旦您知道画布的宽度和高度(以像素为单位),您就可以使用

CVW=document.getElementById("theCanvas").width;
CVH=document.getElementById("theCanvas").height;

CNW=CVW/0.6 //(for a 20% left and right margin given to the canvas)
CNH=CVH+40  //(for a 20px top and bottom margin given to the canvas)
document.getElementById("container").style.width=CNW+"px";
document.getElementById("container").style.height=CNH+"px";

您需要将它放在一个函数中,并且只有在您知道画布的宽度和高度时才调用它。

请注意,容器的宽度和高度是使用 css 样式设置的,但不是为画布设置的。

下面是一个完整的简化版本

<html>
    <head>
        <style>
            #container{
                border-right: dotted black 5px;
                border-left: dotted black 5px;
                border-top: dotted black 5px;
                border-bottom: dotted black 5px;
                margin: auto;
            }

            #theCanvas {
                border: solid black 5px;
                border-radius: 10px;
                background: #ffffff;
                margin-left: 20%;
                margin-top: 20px;
                margin-bottom: 20px;
                cursor: crosshair;
            }
        </style>
        <script>

            function set() {
                CVW=document.getElementById("theCanvas").width;
                CVH=document.getElementById("theCanvas").height;

                CNW=CVW/0.6; //(for a 20% left and right margin given to the canvas)
                CNH=CVH+40;  //(for a 20px top and bottom margin given to the canvas)
                document.getElementById("container").style.width=CNW+"px";
                document.getElementById("container").style.height=CNH+"px";
            }
        </script>
    </head>
    <body onload="set()">
        <div id="container">
            <canvas id="theCanvas" width=200 height="300"></canvas>
        </div>
    </body>
</html>
于 2013-06-02T16:29:52.227 回答