畫布具有不同的尺寸:
爲了避免失真,並獲得一個像素的大小 - 完美的圖形,你需要確保他們最終平等...例如:
function redraw() {
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
...
}
對於單頁HTML遊戲中你只是想畫的一切在畫布上簡單的方法是:
<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
* {
margin: 0;
padding: 0;
border: none;
}
body,html {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<script>
var canvas = document.createElement('canvas');
canvas.style.position = 'absolute';
var body = document.body;
body.insertBefore(canvas, body.firstChild);
var context = canvas.getContext('2d');
var devicePixelRatio = window.devicePixelRatio || 1;
var backingStoreRatio = context.webkitBackingStorePixelRatio
|| context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio
|| context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
var ratio = devicePixelRatio/backingStoreRatio;
redraw();
window.addEventListener('resize', redraw, false);
window.addEventListener('orientationchange', redraw, false);
function redraw() {
width = (window.innerWidth > 0 ? window.innerWidth : screen.width);
height = (window.innerHeight > 0 ? window.innerHeight : screen.height);
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
width *= ratio;
height *= ratio;
if (canvas.width === width && canvas.height === height) {
return;
}
canvas.width = width;
canvas.height = height;
}
//draw things
</script>
</body>
</html>
您還需要檢查的變化innerWidth
/innerHeight
如果你的應用程序有部分在其中只是在等待用戶交互(不呼叫呼叫redraw
),用戶改爲調整瀏覽器窗口大小或傾斜電話/標籤。