Robert Robert - 4 months ago 36
CSS Question

Setting Canvas size in Javascript

I am trying to set the width and height of an HTML5 canvas element using Javascript. The height needs to be based on the height of a parent div container and be the width of the entire page. The height is being set, but the width isn't. Can anyone explain where I'm going wrong and how to fix it?

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);
})

Answer

You need to set width and height properties of your canvas object. Currently, you are only drawing a rectangle inside your canvas without changing its dimensions which remain at default value of 300x150.

You should use:

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>