Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove the extra height of html5 canvas?

Tags:

html

canvas

I was testing html5 canvas element, and wish my canvas to be full screen in the display area. But I found if I set the canvas height to window.innerHeight, the scroll bar will be shown up. I tried and found need to set the height to 5 pixel less, the scroll bar will disappear, but unfortunately it left a white border below the canvas. If it's a div element, everything is fine.

The code I'm using to test is:

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function load() {
    var o = document.getElementById('canvas');
    if (o) {
        o.width = window.innerWidth;
        o.height = window.innerHeight - 5;
    }
    o = document.getElementById('div');
    if (o) {
        o.style.width = window.innerWidth + 'px';
        o.style.height = window.innerHeight + 'px';
    }
}
</script>
<style type="text/css">
* {
    margin: 0;
    padding: 0;
}
body {
    background-color: white;
}
#canvas {
    background-color: blue;
}
#div {
    background-color: green;
}
</style>
</head>
<body onload="load();">
<canvas id="canvas"></canvas>
<!--div id="div"></div-->
</body>
</html>

I've cleared the body margin and padding.

I test it on Chrome 8.0.552, and also it acts same on Firefox 3.6.13 but 4 pixel less is fine.

Anything I missed? Any suggestions will be really appreciated. Thanks a lot.

like image 799
tiefeng Avatar asked Jan 24 '11 18:01

tiefeng


1 Answers

By default canvas, unlike div, is display: inline; so it gets set to vertical-align: baseline;. You can take either of the following approaches to make things naturally fill the window.innerHeight:

#canvas {
    background-color: blue;
    vertical-align: top;
}

Or:

#canvas {
    background-color: blue;
    display: block;
}
like image 63
robertc Avatar answered Oct 26 '22 06:10

robertc