requestAnimationFrame 微信小程序
时间: 2023-10-15 11:25:29 浏览: 314
在微信小程序中,requestAnimationFrame方法的兼容性存在问题。微信小程序本身不提供requestAnimationFrame方法,而是将其实现放在了webgl canvas的上下文中。因此,只有2.7.0版本以后的机型才能使用requestAnimationFrame方法。如果你想在使用普通的canvas时,也使用requestAnimationFrame来控制画面渲染刷新,可以使用setInterval或者setTimeout来实现降级处理。以下是降级处理的代码:
```javascript
(function() {
var lastTime = 0;
// 兼容各种浏览器
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; x++) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
// 降级处理
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback, element) {
// 保证如果重复执行callback的话,callback的执行起始时间相隔16ms
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
}());
```
这段代码可以使得在微信小程序中使用requestAnimationFrame方法进行画面渲染刷新。所以在微信小程序中,要使用requestAnimationFrame方法,需要进行降级处理。同时,需要注意的是,requestAnimationFrame和setTimeout不是一回事,根据其定义,可以在不同场景下使用。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [微信小程序webgl+Three.js初试水(一)](https://blog.csdn.net/sinat_33342614/article/details/99889762)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [从微信小程序重力感应API到requestAnimationFrame探索实现](https://blog.csdn.net/weixin_33747129/article/details/89175163)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文