canvas_14 行走的口袋妖怪
效果图:
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 var image = new Image(); 28 image.src = "../static/01/pokemon.png"; 29 var step = 5; 30 var x = 0; 31 var y = 0; 32 var stepX = 0; 33 // 只演示图片第三行的动作 34 var stepY = 2; 35 36 image.onload = function() { 37 setInterval(function() { 38 ctx.clearRect(0, 0, w, h); 39 40 stepX++; 41 if (stepX > 3) { 42 stepX = 0; 43 } 44 45 // 图片长宽 192*192 图片内元素是 4*4 46 // 前4个坐标参数是图片内截取的位置,后四个是在canvas上显示的位置 47 ctx.drawImage(image, 48 * stepX, 48 * stepY, 48, 48, x, y, 48 * 2, 48 * 2); 48 x += step; 49 if (x > w) { 50 x = 0; 51 } 52 53 }, 200) 54 } 55 </script> 56 </body> 57 58 </html>
素材: