2017-07-14 70 views
0

我试图做一个响应式画布游戏(使用一些代码发现here保持宽度高度100%)。为了让文字响应,我使用大众的大小。问题是,即使我调用调整大小的绘图函数,JavaScript似乎仍然从原始大小采取VW维度(尽管重新加载页面的大小是正确的)。画布响应文本

<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> 

回答

2

画布不支持CSS vw单元。

所以,你应该用...

ctx.font = 2 * window.innerWidth + "px Arial"; 

的,而不是...

ctx.font = "2vw Arial"; 

这里是working demo on jsFiddle

+0

谢谢,真是棒极了! – Dalek

+0

欢迎! –