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>
謝謝,真是棒極了! – Dalek
歡迎! –