Reputation: 121
I'm attempting to make a responsive canvas game(using some code found here to keep width height 100%). In order to get the text responsive I'm using VW for the size. The problem is that even though I am calling the draw function on a resize, JavaScript still seems to be taking the VW dimension from the original size.(Although reloading the page does correctly size it).
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Game</title>
<style>
html body{
margin:0;
padding:0;
border:0;
}
#canvas{
display:block;
background-color: rgb(102,0,102);
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//change canvas size
function canvasSize(){
canvas.style.width = window.innerWidth + 'px';
canvas.style.height = window.innerHeight + 'px';
canvas.width = window.innerWidth * window.devicePixelRatio;
canvas.height = window.innerHeight * window.devicePixelRatio;
ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
}
//draw function
function mainDraw(){
//changing coordinate x,y to centre of canvas
ctx.translate(canvas.width/2,canvas.height/2);
//drawing text;
ctx.font = "2vw Arial";
ctx.textAlign="center";
ctx.fillText("RoundCloud Christmas adventure",0,0);
// draw circle
ctx.beginPath();
ctx.arc(0,0,canvas.width / 100,0,Math.PI*2);
ctx.closePath();
ctx.fill();
}
window.onload = function(){
canvasSize();
mainDraw();
window.addEventListener('resize', canvasSize);
window.addEventListener('resize', mainDraw);
}
</script>
</body>
</html>
Upvotes: 1
Views: 3833
Reputation: 32889
Canvas doesn't support css vw
unit.
SO, you should use ...
ctx.font = 2 * window.innerWidth + "px Arial";
instead of ...
ctx.font = "2vw Arial";
Here is the working demo on jsFiddle
Upvotes: 2