請耐心等待...我正在學習如何使用 requestAnimationFrame 進行簡單影片(例如:在螢屏上移動球。)我得到了使用 javscript 函式的示例。現在我想使用 javascript 類和方法來做同樣的事情。我這樣做是因為接下來我想多次實體化類,運行并控制多個球在螢屏上移動。問題:
不確定我的類語法是否理想。(這有點駭人聽聞)
requestAnimationFrame 運行影片太快。
...animationRequest = window.requestAnimationFrame(this.moveBall());
它作為 javascript 函式作業 https://jsfiddle.net/tjqbpv1e/
但是當我創建一個類時速度太快(或根本沒有)。 https://jsfiddle.net/68vys0hL/
uj5u.com熱心網友回復:
您有一些未宣告的和額外的變數以及 missing this,但除此之外,它看起來像一個不錯的類。沒有影片(又名太快)的原因是因為您this.moveBall()直接執行而不是this.moveBall作為回呼發送到requestAnimationFrame. 此外,您根本沒有任何可以控制速度的東西。requestAnimationFrame您必須檢查自上次回呼以來經過了多長時間,就像您在原始代碼中作為未使用的變數diff一樣。
說到回呼,用范圍發送回呼有點棘手this,通常你可能需要.bind(this)回呼函式:
class AnimatedCircle {
output;
animated_circle;
number;
xpos;
multiplier;
animationRequest;
myContainer;
screen_width;
prevTime;
speed;
constructor(val_1, val_2) {
this.val_1 = val_1; // example of passing values
this.val_2 = val_2;
this.animated_circle = document.getElementById('animated_circle');
this.number = 0;
this.xpos = 1; // new horizontal position
this.multiplier = 1;
this.animationRequest = null;
this.myContainer = document.querySelector('#container');
this.screen_width = this.myContainer.offsetWidth - 50;
this.prevTime = 0;
this.speed = Math.random() * 10; //random speed
}
// test method
test_method() {
return `${this.val_1} says hello.`;
}
moveBall(time) {
this.animationRequest = window.requestAnimationFrame(this.moveBall.bind(this));
if (time - this.prevTime < this.speed) //speed control
return;
this.prevTime = time;
// if on screen
console.log("got here!");
if (this.xpos < this.screen_width && this.xpos > 0) {
this.number ;
}
else {
// when we get to end of screen , then exit function
return;
}
this.xpos = this.xpos (5); // horizontal position
// move on X-Axis
this.animated_circle.style.transform = `translateX(${this.xpos}px)`;
console.log("loop");
}
}
// instantiate class
myAnimatedCircle = new AnimatedCircle('Bob', 'Level22');
// call method
console.log(myAnimatedCircle.test_method());
console.log(myAnimatedCircle.moveBall());
#container{
border: 1px solid gray;
background-color: rgb(236, 225, 225);
height:60px;
padding:0px;
}
#animated_circle{
height: 35px;
width: 35px;
margin:10px;
background-color: rgb(103, 74, 184);
border-radius: 50%;
display: inline-block;
}
<p id="output"></p>
<div id="container" >
<p id="animated_circle"></p>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/452232.html
標籤:javascript 班级 请求动画帧
下一篇:盡管存在Python類屬性錯誤?
