canvas 植物大战僵尸——背景图片的拖动

1.创建背景图片

function Map() {
    //地图的大小
    var mapW = 1400;
    var mapH = 600;
    //地图的位置
    var mapLeft = 0;
    var mapTop = 0;
    //创建地图图片
    var map;
    //X轴移动的距离
    var disX;
    this.init = function () {
        //创建图片元素
        map = new Image();
        //设置图片的地址
        map.src = "./img/background.jpg";

        document.onmousedown = this.onMousedown;
    }

    this.run = function (paint) {
        paint.drawImage(map,mapLeft,mapTop,mapW,mapH);
    }


    this.onMousedown = function (ev) {
        disX = ev.clientX - map.offsetLeft;
        document.onmousemove = function (ev) {
            if((ev.clientX - disX)>=0) {
                mapLeft = 0;
            }
            else if((ev.clientX - disX)<=-280) {
                mapLeft = -280;
            }
            else {
                mapLeft = ev.clientX - disX;
            }
        }
        document.onmouseup = function () {
            document.onmousemove = null;
            document.onmouseup = null;
        }
    }
}

2.在游戏Game.js中初始化

function Game() {
    var paint;

    //地图
    var map;
    this.init = function () {
        this.initGame();

        //初始化地图
        this.initMap();
    }

    this.initGame = function () {
        //获得游戏画布
        var myCanvas = document.getElementById('myCanvas');
        paint = myCanvas.getContext("2d");
    }

    //初始化游戏地图
    this.initMap = function () {
        map = new Map();
        map.init();
    }

    this.run = function () {
        map.run(paint);
    }
}

3.在index.html界面运行

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js1/Game.js"></script>
    <script src="js1/Map.js"></script>
</head>
<body>
<div id="box" style="width: 1120px;height: 600px; margin: auto;overflow: hidden">
    <canvas id="myCanvas" width="1400" height="600" style="border:1px solid #d3d3d3;">
    </canvas>
</div>
</body>

<script>
    game = new Game();
    game.init();

    setInterval('game.run()',200);
</script>

</html>

猜你喜欢

转载自blog.csdn.net/qq_34607371/article/details/81121971
今日推荐