我不确定,我怎样才能更具体,但我正在尽我最大的努力来解释它。我试图理解,我应该寻找什么更具体,所以这就是我所拥有的此时此刻。
我正在探索 HTML5 JavaScript 游戏,我注意到,将 Canvas 的高度和宽度设置为 100% 会扭曲其中的动画。 a simple example我从here得到的. 如果我将 Canvas 大小更改为 100%(在我提供的示例中),它会破坏游戏的动画(例如小行星)。
我想知道,HTML5 的哪个属性导致了这种行为,我应该寻找什么才能使 HTML5 动画适合整个屏幕尺寸?
编辑
我尝试运行 cordova 将游戏构建到本地平台,但我遇到的第一个问题是 Canvas 不适合屏幕尺寸。 (这就是为什么我希望它完全适合浏览器屏幕,但是当使用 cordova 将为浏览器屏幕制作的 Canvas 呈现给 native 时,我发现完全不适合)。
我探索了phaser,他们是如何解决这个问题的,并且found this game它使用了一种叫做 ScalingManager 的东西.
所以,我的问题是
1.什么是缩放游戏?
2. Phaser 的 scaling-manager 是如何工作的
3.在不使用缩放管理器的情况下,即使 Canvas 高度和宽度被正确提及,为什么游戏不适合 moile 屏幕尺寸?
4.有没有我可以做的小实验(不使用任何移相器或类似的 javascript 游戏框架)来理解使用简单的 HTML5 javasctipt 和 cordova 进行扩展的必要性?
最佳答案
Canvas 有两种不同的尺寸:
- 页面上元素的大小
- Canvas 的大小(以像素为单位)
为了避免失真并获得像素完美的图形,您需要确保它们最终相等......例如:
function redraw() {
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
...
}
对于您只想在 Canvas 中绘制所有内容的单页 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>
如果您的应用有一些您只是在等待用户交互的部分(而不是循环调用 redraw
) 并且用户改为调整浏览器窗口的大小或倾斜手机/标签。
关于javascript - HTML5 Canvas 高宽100%扭曲游戏动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33565332/