1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 7 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 <title>Canvas</title> 9 <style> 10 canvas { 11 display: block; 12 margin: 0 auto; 13 border: 1px solid #eee; 14 } 15 </style> 16 </head> 17 18 <body> 19 <canvas height="500" width="500" id="canvas"></canvas> 20 21 <script> 22 var canvas = document.querySelector("#canvas"); 23 var ctx = canvas.getContext("2d"); 24 var w = canvas.width; 25 var h = canvas.height; 26 27 function animation() { 28 var fno = 0; 29 var timer = setInterval(function() { 30 fno++; 31 ctx.clearRect(0, 0, w, h); 32 ctx.fillText(fno, 10, 20); 33 ctx.drawImage(fno % 2 ? imageSorce.boy : imageSorce.pokemon, 100, 100); 34 if (fno == 10) { 35 clearInterval(timer); 36 } 37 }, 500) 38 } 39 40 var imageSorce = {}; 41 var imageLoadNum = 0; 42 var xhr = new XMLHttpRequest(); 43 xhr.open("get", "../json/loadImage.json", true); 44 xhr.send(null); 45 xhr.onreadystatechange = function() { 46 if (xhr.readyState == 4) { 47 var obj = JSON.parse(xhr.responseText); 48 for (var i = 0; i < obj.images.length; i++) { 49 imageSorce[obj.images[i].name] = new Image(); 50 imageSorce[obj.images[i].name].src = obj.images[i].url; 51 imageSorce[obj.images[i].name].onload = function() { 52 imageLoadNum++; 53 ctx.clearRect(0, 0, w, h); 54 ctx.fillText("正在加载第" + imageLoadNum + "/" + 55 obj.images.length + "张图片,请稍后...", 100, 100); 56 if (imageLoadNum == obj.images.length) { 57 animation() 58 } 59 } 60 } 61 } 62 } 63 64 /* 65 loadImage.json: 66 { 67 "images": [{ 68 "name": "pokemon", 69 "url": "../static/images/pokemon.png" 70 }, 71 { 72 "name": "boy", 73 "url": "../static/images/boy.png" 74 } 75 ] 76 } 77 */ 78 </script> 79 80 </body> 81 82 </html>