Canvas size to viewport

by mvasilkov

HTML

<div id=a>
    <canvas id=c></canvas>
</div>

CSS

html, body {
    height: 100%;
    margin: 0;
    overflow: hidden;
}

#a {
    left: 50%;
    position: absolute;
    top: 50%;
}

#c {
    background: #303030;
    display: block;
    height: 100%;
    position: relative;
    width: 100%;
}

JavaScript

var $ = document.getElementById.bind(document)

function css(x, property, value) {
    x.style[property] = (0|value) + 'px'
}

var cwidth = 960, cheight = 540
var aspect = 16 / 9


var $a = $('a')
var $c = $('c')

$c.width = cwidth
$c.height = cheight


function resize() {
	var iw = innerWidth, ih = innerHeight

    if (iw / ih > aspect) iw = ih * aspect
    else ih = iw / aspect

    css(a, 'width', iw)
    css(a, 'height', ih)
    css(c, 'left', -0.5 * iw)
    css(c, 'top', -0.5 * ih)
}

addEventListener('resize', resize)
addEventListener('orientationchange', resize)
resize()


var canvas = $c.getContext('2d')
canvas.fillStyle = '#fbfbfb'

function render() {
	requestAnimationFrame(render)
    
    canvas.clearRect(0, 0, cwidth, cheight)
    canvas.fillRect(cwidth * Math.random(), cheight * Math.random(),
                    100, 100)
}

//requestAnimationFrame(render)