在Javascript中设置画布大小

时间:2016-07-20 10:35:21

标签: javascript html css html5 html5-canvas

我正在尝试使用Javascript设置HTML5 canvas元素的宽度和高度。高度需要基于父div容器的高度,并且是整个页面的宽度。正在设置高度,但宽度不是。任何人都可以解释我哪里出错了以及如何解决它?

HTML

<div id="main">
    <div id="navigation">
        <div id="portholeContainer">
            <div class="porthole"></div>
        </div>
        <ul>
            <li>About</li>
            <li>Portfolio</li>
            <li>Contact Me</li>
        </ul>
    </div>
    <div id="first" class="container">
        <canvas id="background"></canvas>
    </div>
    <div id="second" class="container"></div>
</div>

CSS

.container{
    display: block;
    float: left;
    width: 100%;
    margin-left: 0;
    border-bottom: 2px solid rgba(255, 255, 255, 0.75);
}

JS

window.addEventListener("load", function(){
    var container = document.getElementsByClassName("container");
    var first = document.getElementById("first");
    var canvas = document.getElementById("background");
    var ctx = canvas.getContext("2d");

    for(var i = 0; i < container.length; i++){
        container[i].style.height = (this.innerHeight / 1.24) +"px";
    }

    ctx.fillStyle = "#000000";
    ctx.fillRect(0, 0, this.innerWidth, first.style.height);
})

1 个答案:

答案 0 :(得分:1)

您需要设置canvas对象的宽度和高度属性。目前,您只在画布中绘制一个矩形而不更改其尺寸,默认值保持为300x150。

您应该使用:

canvas = document.getElementById("background");
canvase.width = 500; //or other value
canvase.height = 500; //or other value

window.addEventListener("load", function(){
    var container = document.getElementsByClassName("container");
    var first = document.getElementById("first");
    var canvas = document.getElementById("background");
    var ctx = canvas.getContext("2d");

    for(var i = 0; i < container.length; i++){
        container[i].style.height = (this.innerHeight / 1.24) +"px";
    }
  
  
    canvas.width = window.innerWidth;
    canvas.height = parseInt( first.style.height );

    ctx.fillStyle = "#000000";
    ctx.fillRect(0, 0, this.innerWidth,first.style.height );
})
.container{
    display: block;
    float: left;
    width: 100%;
    margin-left: 0;
    border-bottom: 2px solid rgba(255, 255, 255, 0.75);
}

#first
{
  background-color: #ddd;
}

#first canvas
{
  outline: thick solid red;
}
<div id="main">
    <div id="navigation">
        <div id="portholeContainer">
            <div class="porthole"></div>
        </div>
        <ul>
            <li>About</li>
            <li>Portfolio</li>
            <li>Contact Me</li>
        </ul>
    </div>
    <div id="first" class="container">
        <canvas id="background"></canvas>
    </div>
    <div id="second" class="container"></div>
</div>