Created
February 6, 2014 22:26
-
-
Save digitalicarus/8853779 to your computer and use it in GitHub Desktop.
center and expand canvas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var D = document | |
, body = D.body | |
, canvas = D.body.appendChild(D.createElement('canvas')) | |
, ctx = canvas.getContext('2d') | |
, width = 480 | |
, height = 272 | |
; | |
function vendorStyle (ele, prop, val) { | |
var caps = prop.charAt(0).toUpperCase() + prop.slice(1) | |
, vendors = ['', 'webkit', 'moz', 'ms', 'o'] | |
, tmp = '' | |
, i | |
; | |
for (i=0; i<vendors.length; i++) { | |
tmp = vendors[i] + ((vendors[i]==='') ? prop : caps); | |
if (ele.style.hasOwnProperty(tmp)) { | |
ele.style[tmp] = val; | |
} | |
} | |
} | |
function resize (container) { | |
var width = container.clientWidth || container.innerWidth | |
, height = container.clientHeight || container.innerHeight | |
, ratioFlip = (width / height < canvas.width / canvas.height) | |
, percent = ratioFlip ? width / canvas.width : height / canvas.height | |
; | |
if (ratioFlip) { | |
canvas.style.top = '50%'; | |
canvas.style.marginTop = '-' + ((canvas.height >> 1) * percent) + 'px'; | |
} | |
else { | |
canvas.style.top = 'auto'; | |
canvas.style.marginTop = 'auto'; | |
} | |
vendorStyle(canvas, 'transform', 'scale(' + percent + ', ' + percent + ')'); | |
console.log(percent); | |
} | |
function clearBoard () { | |
ctx.clearRect(0,0,canvas.width,canvas.height); | |
// draw board | |
} | |
function game() { | |
clearBoard(); | |
} | |
// ~_..-==- Base CSS -==-.._~ | |
body.style.padding = '0'; | |
body.style.margin = '0'; | |
canvas.setAttribute('width', width); | |
canvas.setAttribute('height', height); | |
canvas.style.position = 'absolute'; | |
canvas.style.left = '50%'; | |
canvas.style.marginLeft = '-' + (canvas.width >> 1) + 'px'; | |
vendorStyle(canvas, 'transformOrigin', '50% 0%'); | |
resize(window); | |
clearBoard(); | |
window.addEventListener('resize', function (e) { resize(e.target); }); | |
game(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment