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>