Javascript图像放置

时间:2015-03-04 19:40:41

标签: javascript jquery css image

所以我正在构建一个益智管道游戏,并希望每个级别都有不同的背景。背景是从img src唯一的问题加载的,当时的图像随着屏幕尺寸移动...我总是希望它居中,这样你就可以看到图像的中间。

例如,在13"屏幕上的27"看起来一团糟......有没有一种简单的方法可以将图像保存在同一个地方?我知道我可以设置一个css规则但是想知道是否有办法将它添加到js脚本中?

到目前为止,我的js脚本看起来像这样(对于一个级别):

var levels = {
level1: {
            level: [[["0","1","0","1"],["0","0","0","0"],["0","0","0","0"],["0","0","0","0"],["0","0","0","0"],["0","0","0","0"]],[["0","0","1","1"],["0","1","1","0"],["0","0","0","0"],["0","0","0","0"],["0","0","0","0"],["0","0","0","0"]],[["0","0","0","0"],["0","0","1","1"],["1","1","0","0"],["0","0","0","0"],["0","0","0","0"],["0","0","0","0"]],[["0","0","0","0"],["0","0","0","0"],["0","0","1","1"],["1","0","1","0"],["1","0","1","0"],["1","1","0","0"]]],
            backgroundURL : "http://website.co.uk/client_files/level1.jpg"
        },

谢谢

1 个答案:

答案 0 :(得分:0)

如果您希望您的游戏始终位于屏幕中间, 请关注这篇文章: https://css-tricks.com/positioning-offset-background-images/

假设您的画布为<div id="game"></div>

设置基本css以使元素背景居中

#game{
    background-color: lightgray;
    background-position: center center;
    background-repeat: no-repeat;
    width: 80%;
    height: 80%;
    position:absolute;
}

javascript代码将非常简单 只需获取主要元素并仅更新图像URL

var canvas = document.querySelector('#game');

canvas.style.backgroundImage = " url('"+levels.level1.backgroundURL+"')";

// simulate a level change after 3 seconds
setTimeout(function(){
    canvas.style.backgroundImage = "url('"+levels.level2.backgroundURL+"')";
}, 3000);

在这里查看正在运行的代码: http://jsfiddle.net/zw7dv9at/2/