上個星期順便也學習了cavans的操作,本就想做一個小h5遊戲來豐富簡歷。只是想做一個非常簡單的,類似google斷網後的小恐龍遊戲。
cavans有很豐富的畫圖函數,要實現動畫,其實就是利用cavans的繪畫函數,一步一步地將一張張圖畫出來,就好像我們以前在書頁的小角上畫的“火柴人”一樣。繪製動畫的原理是明白了,只是函數的定義和原理還不明白。
據瞭解,目前在html上實現動畫函數的有三種方法,setTimeout , setinterval, requestAnimationFrame,這三個有什麼區別就自行百度了,但最好的應該是requestAnimationFrame。
===============================以下是百度出來的================================
requestAnimationFrame的優勢,在於充分利用顯示器的刷新機制,比較節省系統資源。顯示器有固定的刷新頻率(60Hz或75Hz),也就是說,每秒最多隻能重繪60次或75次,requestAnimationFrame的基本思想就是與這個刷新頻率保持同步,利用這個刷新頻率進行頁面重繪。此外,使用這個API,一旦頁面不處於瀏覽器的當前標籤,就會自動停止刷新。這就節省了CPU、GPU和電力。
不過有一點需要注意,requestAnimationFrame是在主線程上完成。這意味着,如果主線程非常繁忙,requestAnimationFrame的動畫效果會大打折扣。
===============================================================================
// requestNextAnimationFrame 動畫兼容問題
window.requestNextAnimationFrame =
(function() {
var originalWebkitRequestAnimationFrame = undefined,
wrapper = undefined,
callback = undefined,
geckoVersion = 0,
userAgent = navigator.userAgent,
index = 0,
self = this;
// Workaround for Chrome 10 bug where Chrome
// does not pass the time to the animation function
if (window.webkitRequestAnimationFrame) {
// Define the wrapper
wrapper = function(time) {
if (time === undefined) {
time = +new Date();
}
self.callback(time);
};
// Make the switch
originalWebkitRequestAnimationFrame = window.webkitRequestAnimationFrame;
window.webkitRequestAnimationFrame = function(callback, element) {
self.callback = callback;
// Browser calls the wrapper and wrapper calls the callback
originalWebkitRequestAnimationFrame(wrapper, element);
}
}
// Workaround for Gecko 2.0, which has a bug in
// mozRequestAnimationFrame() that restricts animations
// to 30-40 fps.
if (window.mozRequestAnimationFrame) {
// Check the Gecko version. Gecko is used by browsers
// other than Firefox. Gecko 2.0 corresponds to
// Firefox 4.0.
index = userAgent.indexOf('rv:');
if (userAgent.indexOf('Gecko') != -1) {
geckoVersion = userAgent.substr(index + 3, 3);
if (geckoVersion === '2.0') {
// Forces the return statement to fall through
// to the setTimeout() function.
window.mozRequestAnimationFrame = undefined;
}
}
}
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback, element) {
var start,
finish;
window.setTimeout(function() {
start = +new Date();
callback(start);
finish = +new Date();
self.timeout = 1000 / 60 - (finish - start);
}, self.timeout);
};
})
();
==================以上也是百度出來的,用於解決並不支持requestAnimationFrame的瀏覽器=================
順便提一下,不支持requestAnimationFrame的方法,就是用setTimeout來代替了,主要是刷新率問題而已。
但在做引擎時,我還是沒搞得清楚,在網頁刷新之後,就會輸出同一個動畫編號,導致了經過一段時間後,網頁會變得很慢,即使動畫不播放的時候也會疊加。這個問題暫時未解決。記錄一下。
也希望有這方面經驗的大神給我一點指點~!
2020.02.28