码迷,mamicode.com
首页 > Web开发 > 详细

js学习之地图生成

时间:2015-12-07 13:57:34      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

首先,上地图图片

技术分享

接着,js,我们可以把图片看成一块块32*32像素的

技术分享

var i;
var j;

window.onload = function () {
    gamemap(15, 10, 10, "map.jpg");
}

var mapimg = new Image();
var map = [
    [18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 55, 55, 18],
    [18, 18, 18, 17, 17, 17, 17, 17, 17, 17, 17, 17, 55, 55, 18],
    [18, 18, 17, 17, 17, 17, 18, 18, 17, 17, 17, 17, 55, 55, 18],
    [18, 17, 17, 17, 18, 18, 18, 18, 18, 17, 17, 55, 55, 17, 18],
    [18, 17, 17, 18, 22, 23, 23, 23, 24, 18, 17, 55, 55, 17, 18],
    [18, 17, 17, 18, 25, 28, 26, 79, 27, 18, 55, 55, 17, 17, 18],
    [18, 17, 17, 17, 17, 10, 11, 12, 18, 18, 55, 55, 17, 17, 18],
    [18, 18, 17, 17, 10, 16, 16, 16, 11, 55, 55, 17, 17, 17, 18],
    [18, 18, 17, 17, 77, 16, 16, 16, 16, 21, 21, 17, 17, 17, 18],
    [18, 18, 18, 18, 18, 18, 18, 18, 18, 55, 55, 18, 18, 18, 18]
];
//创建构成地图的二维数组  

function gamemap(x, y, num, url) {  //长个数,宽个数,一行个数,图片路径
    var canvas = document.getElementById("map");
    var context = canvas.getContext("2d");

    mapimg.src = url;

    mapimg.onload = function () {
        context.fillRect(0, 0, x * 32, y * 32);
        //画一个长480,宽320的矩形  

        for (i = 0; i < x; i++) {
            for (j = 0; j < y; j++) {
                drawTile(i * 32, j * 32, map[j][i], num);
            }
        }
        //循环调用绘制地图的函数,直到画完为止  
    }
}

function drawTile(x, y, type, num) {
    var canvas = document.getElementById("map");
    var context = canvas.getContext("2d");
    context.drawImage(mapimg, type % num * 32, parseInt(type / num) * 32, 32, 32, x, y, 32, 32);
} 

最后,页面调用

<!DOCTYPE html>
<html>
<head>
    <title>地图生成</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" />
    <script type="text/javascript" src="map.js"></script>
</head>
<body>
    <canvas id="map" width="480px" height="320px" style="border: 1px solid gray;"></canvas>
</body>
</html>

效果图:

技术分享

js学习之地图生成

标签:

原文地址:http://www.cnblogs.com/margin-gu/p/5025675.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!