【发布时间】:2020-11-08 19:12:19
【问题描述】:
我想显示整个场景(静态大小)并将其居中,即我必须根据窗口大小缩放/缩放和移动 viewport。根据纵横比,我scale 要么适合宽度,要么适合高度。然后我centerOn现场
const heightScale = Crafty.viewport.height / staticSceneHeight
const widthScale = Crafty.viewport.width / staticSceneWidth
if (heightScale < widthScale) {
Crafty.viewport.scale(heightScale)
} else {
Crafty.viewport.scale(widthScale)
}
Crafty.viewport.centerOn(scene, 0)
缩放有效,但场景未正确居中。看这个例子:
const staticSceneWidth = 640
const staticSceneHeight = 960
Crafty.init()
Crafty.background('rgb(127,127,127)')
// grid of four rectangles
// top left
Crafty.e('2D, Canvas, Color, Fourway')
.attr({ x: 0, y: 0, w: 320, h: 480 })
.color('red')
// top right
Crafty.e('2D, Canvas, Color, Fourway')
.attr({ x: 320, y: 0, w: 320, h: 480 })
.color('green')
// bottom left
Crafty.e('2D, Canvas, Color, Fourway')
.attr({ x: 0, y: 480, w: 320, h: 480 })
.color('blue')
// bottom right
Crafty.e('2D, Canvas, Color, Fourway')
.attr({ x: 320, y: 480, w: 320, h: 480 })
.color('yellow')
// dummy for centering
const scene = Crafty.e('2D').attr({ x: 0, y: 0, w: 640, h: 960 })
function fitViewportToScene() {
const heightScale = Crafty.viewport.height / staticSceneHeight
const widthScale = Crafty.viewport.width / staticSceneWidth
if (heightScale < widthScale) {
Crafty.viewport.scale(heightScale)
} else {
Crafty.viewport.scale(widthScale)
}
Crafty.viewport.centerOn(scene, 0)
}
window.onresize = fitViewportToScene
fitViewportToScene()
body,
html {
margin: 0;
padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/crafty/0.9.0/crafty.js"></script>
为什么场景没有正确居中?如何正确居中?
Crafty.JS 0.9.0
【问题讨论】:
标签: javascript game-engine craftyjs