代码如下:
1 <!DOCTYPE html> 2 3 <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> 4 <head> 5 <meta charset="utf-8" /> 6 <title></title> 7 </head> 8 <body style="text-align:center;"> 9 <canvas id="myCanvas" width="800" height="800" onclick="savedata()" onmousemove="showmouse()" style="background:#808080;margin-left:10px; "></canvas> 10 <img src="801.png" /> 11 <script> 12 //墙 13 var img = new Image(); 14 img.src = "801.png"; 15 16 //画布宽 17 var canWidth = 400; 18 //画布高 19 var canHeight = 800; 20 //墙块宽度 21 var canStoreWidth = 80; 22 //画布 23 var ctx; 24 //图片数据 25 var imageData; 26 //地图map 27 var mapJson = new Array(); 28 29 window.onload = function () 30 { 31 var canvas = document.getElementById('myCanvas'); 32 ctx = canvas.getContext('2d'); 33 savedata(); 34 } 35 36 //获取到坐标所在的索引 37 function inlocation(x, y) 38 { 39 var xx = x / canStoreWidth; 40 var yy = y / canStoreWidth; 41 42 return { 43 x1: parseInt(xx) == xx ? xx : parseInt(xx) + 1, 44 y1: parseInt(xx) == yy ? yy : parseInt(yy) + 1 45 }; 46 } 47 48 //1,将屏幕平均分割成分[10,20] 49 //2,每块大小40*40 50 51 //得到块区域 52 function getStore(indexX, indexY) 53 { 54 var x = 0; 55 var y = 0; 56 x = (indexX - 1) * canStoreWidth; 57 y = (indexY - 1) * canStoreWidth; 58 return { X: x, Y: y }; 59 } 60 61 //绘制事件 62 function showmouse() 63 { 64 if (ctx) 65 { 66 setdata(); 67 var e = event; 68 //绘制块 69 var xy1 = inlocation(e.offsetX, e.offsetY); 70 var location = getStore(xy1.x1, xy1.y1); 71 72 ctx.drawImage(img, location.X, location.Y, canStoreWidth, canStoreWidth); 73 //人物不可存在不可以移动的元素上面 74 } 75 } 76 //保存每次绘制的地图 77 function savedata() 78 { 79 if (ctx) 80 { 81 imageData = ctx.getImageData(0, 0, canWidth, canHeight); 82 //纪录当前点击的模块 83 var e = event; 84 if (e.type == "click") 85 { 86 //绘制块 87 var xy1 = inlocation(e.offsetX, e.offsetY); 88 mapJson.push(new Array(xy1.x1, xy1.y1)); 89 } 90 } 91 } 92 //重绘保存好的图片 93 function setdata() 94 { 95 if (imageData) 96 { 97 ctx.putImageData(imageData, 0, 0); 98 } 99 } 100 //绘图太快有bug,不知道什么情况 101 </script> 102 </body> 103 </html>
801.png图片