先看頁面效果。下面四個按鈕分別表示開始、結束、暫停、繼續(xù)
下面是幀動畫圖片素材:
幀動畫的實現(xiàn),關鍵是Canvas API ctx.drawImage() (9個參數(shù))和 setInterval 定時器。
設置圖片的視圖窗口,每次執(zhí)行定時任務,位移展示下一幀圖片。
直接上代碼,Ctrl+C/V 即插即用
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>幀動畫</title> </head> <body> <canvas id="canvas" width="400" height="300"></canvas> <div class=""> <button class="start-btn" type="button">重新吃</button> <button class="end-btn" type="button">不吃了</button> <button class="pause-btn" type="button">歇一歇</button> <button class="continue-btn" type="button">繼續(xù)吃</button> </div> <script type="text/javascript"> const canvas = document.getElementById("canvas") canvas.style.border = "1px solid black" const ctx = canvas.getContext("2d") const img = new Image() // 創(chuàng)建圖片對象 let timer // 定時器標識符 let millisec = 300 // 執(zhí)行時間間隔 let colIndex = 0 // 列數(shù) let rowIndex = 0 // 行數(shù) const timerFun = () => { // 聲明定時器執(zhí)行函數(shù) console.log("設置定時器"); ctx.clearRect(0, 0, canvas.style.width, canvas.style.height) // 清除畫布 if (rowIndex < 3) { // 如果是前5幀 ctx.drawImage(img, colIndex * 240, rowIndex * 240, 200, 200, 50, 50, 200, 200) // 圖片對象,x坐標,y坐標(注:圖片上定位的坐標),width,height(圖片上截取的大?。瑇坐標,y坐標(注:圖片在畫布上的起點,即左上角),width,height(縮放,不是裁剪) colIndex++ // 下一幀 if (colIndex > 4) { colIndex = 0 rowIndex++ } } else { colIndex = 0 rowIndex = 0 } } img.onload = () => { timer = setInterval(timerFun, millisec) } img.src = "image/apple.jpg" const startBtn = document.getElementsByClassName('start-btn')[0] const endBtn = document.getElementsByClassName('end-btn')[0] const pauseBtn = document.getElementsByClassName('pause-btn')[0] const continueBtn = document.getElementsByClassName('continue-btn')[0] startBtn.addEventListener('click', () => { console.log("點擊開始", timer) clearInterval(timer) colIndex = 0 // 列數(shù) rowIndex = 0 // 行數(shù) timer = setInterval(timerFun, millisec) }) endBtn.addEventListener('click', () => { console.log("點擊結束", timer) clearInterval(timer) colIndex = 0 rowIndex = 0 ctx.drawImage(img, colIndex * 240, rowIndex * 240, 200, 200, 50, 50, 200, 200) timer = 0 }) pauseBtn.addEventListener('click', () => { console.log("點擊暫停", timer) clearInterval(timer) timer = 0 }) continueBtn.addEventListener('click', () => { if (timer) { alert('吃著呢,別催') return } console.log("點擊繼續(xù)", timer) timer = setInterval(timerFun, millisec) }) </script> </body> </html>
到此這篇關于Canvas 幀動畫吃蘋果小游戲的文章就介紹到這了,更多相關Canvas 幀動畫內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持腳本之家!