首先,上地图图片
接着,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>
效果图:
时间: 2024-11-10 13:51:07