javascript - requestAnimationFrame の速度を変更する
私はこのコードを持っています、キャンバス上で画像をある位置から別の位置に移動するための:
class Target {
constructor(img, x_init, y_init, img_width = 100, img_height = 100) {
this.img = img;
this.x = x_init;
this.y = y_init;
this.img_width = img_width;
this.img_height = img_height;
}
get position() {
return this.x
}
move(canvas, x_dest, y_dest) {
ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(this.img, this.x, this.y, this.img_width, this.img_height);
if (this.x != x_dest) {
if (this.x > x_dest) {
this.x -=1;
} else {
this.x +=1;
}
}
if (this.y != y_dest) {
if (this.y > y_dest) {
this.y -=1;
} else {
this.y +=1;
}
}
if (this.x != x_dest || this.y != y_dest) {
//setTimeout(this.move.bind(target, canvas, x_dest, y_dest), 0);
window.requestAnimationFrame(this.move.bind(target, canvas, x_dest, y_dest));
}
}
}
このコードの問題は、速度を制御できないことで、結構遅いということです… どうやって速度を制御しつつ、到着位置を選択するというこのアイデアを保つことができるでしょうか? その件についてのトピックは見つけたのですが、私のケースで動作するものは何も見つかりませんでした。おそらく1ピクセルのステップでは小さすぎるからでしょうが、どうやってそれを作れば良いのか分かりません。
[編集] 私がやりたかったことはこれです(赤い円が縮んでいる間の2秒間、レコードを追加する必要があります)。もちろん、PIDの指示に従って行いました。彼に改めて感謝します。
(function() {
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
var canvas = document.getElementById("calibrator");
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const points = [{
"x": 0,
"y": 0
},
{
"x": canvas.width / 2 - 100,
"y": 0
},
{
"x": canvas.width - 100,
"y": 0
},
{
"x": 0,
"y": canvas.height / 2 - 100
},
{
"x": canvas.width / 2 - 100,
"y": canvas.height / 2 - 100
},
{
"x": canvas.width - 100,
"y": canvas.height / 2 - 100
},
{
"x": 0,
"y": canvas.height - 100,
},
{
"x": canvas.width / 2 - 100,
"y": canvas.height - 100
},
{
"x": canvas.width - 100,
"y": canvas.height - 100
}
]
function generateLinear(x0, y0, x1, y1, dt) {
return (t) => {
let f0, f1;
f0 = t >= dt ? 1 : t / dt; // linear interpolation (aka lerp)
f1 = 1 - f0;
return {
"x": f1 * x0 + f0 * x1, // actually is a matrix multiplication
"y": f1 * y0 + f0 * y1
};
};
}
function generateShrink(x0, y0, x1, y1, r0, dt) {
return (t) => {
var f0 = t >= dt ? 0 : dt - t;
var f1 = t >= dt ? 1 : dt / t;
var f2 = 1 - f1;
return {
"x": f2 * x0 + f1 * x1,
"y": f2 * y0 + f1 * y1,
"r": f0 * r0
};
};
}
function create_path_circle() {
var nbPts = points.length;
var path = [];
for (var i = 0; i < nbPts - 1; i++) {
path.push({
"duration": 2,
"segment": generateShrink(points[i].x, points[i].y, points[i].x, points[i].y, 40, 2)
});
path.push({
"duration": 0.5,
"segment": generateShrink(points[i].x, points[i].y, points[i + 1].x, points[i + 1].y, 0, 0.5)
});
}
path.push({
"duration": 2,
"segment": generateShrink(points[nbPts - 1].x, points[nbPts - 1].y, points[nbPts - 1].x, points[nbPts - 1].y, 40, 2)
})
return path;
}
function create_path_target() {
var nbPts = points.length;
var path = [];
for (var i = 0; i < nbPts - 1; i++) {
path.push({
"duration": 2,
"segment": generateLinear(points[i].x, points[i].y, points[i].x, points[i].y, 2)
});
path.push({
"duration": 0.5,
"segment": generateLinear(points[i].x, points[i].y, points[i + 1].x, points[i + 1].y, 0.5)
});
}
path.push({
"duration": 2,
"segment": generateLinear(points[nbPts - 1].x, points[nbPts - 1].y, points[nbPts - 1].x, points[nbPts - 1].y, 2)
})
return path;
}
const path_target = create_path_target();
const path_circle = create_path_circle();
function renderImage(img, img_width, img_height) {
return (pos) => {
ctx = canvas.getContext('2d');
ctx.drawImage(img, pos.x, pos.y, img_width, img_height);
}
}
function renderCircle() {
return (pos) => {
ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(pos.x + 50, pos.y + 50, pos.r, 0, 2 * Math.PI);
ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.stroke();
}
}
function generatePath(path) {
let i, t;
// fixup timing
t = 0;
for (i = 0; i < path.length; i++) {
path[i].start = t;
t += path[i].duration;
path[i].end = t;
}
return (t) => {
while (path.length > 1 && t >= path[0].end) {
path.shift(); // remove old segments, but leave last one
}
return path[0].segment(t - path[0].start); // time corrected
};
}
var base_image = new Image();
base_image.src = 'https://www.pngkit.com/png/full/17-175027_transparent-crosshair-sniper-scope-reticle.png';
const sprites = [
{
"move": generatePath(path_circle),
"created": performance.now(),
"render": renderCircle()
},
{
"move": generatePath(path_target),
"created": performance.now(),
"render": renderImage(base_image, 100, 100)
}
];
const update = () => {
let now;
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// put aside so all sprites are drawn for the same ms
now = performance.now();
for (var sprite of sprites) {
sprite.render(sprite.move((now - sprite.created) / 1000));
}
window.requestAnimationFrame(update);
};
window.requestAnimationFrame(update);
})();<!DOCTYPE html>
<html>
<head>
<title>Calibration</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<canvas id="calibrator"></canvas>
<video id="stream"></video>
<canvas id="picture"></canvas>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="calibration.js"></script>
</body>
</html>撮影のために、もし私が写真を返す takeSnapshot() 関数を持っていると仮定すると、私は次のようにします:
function film(dt) {
return (t) => {
if (t >= dt) {
return false;
} else {
return true;
}
}
}
function create_video_timeline() {
var nbPts = points.length;
var path = [];
for (var i = 0 ; i < nbPts - 1; i++) {
path.push(
{
"duration": 2,
"segment": film(2)
}
);
path.push(
{
"duration":0.5,
"segment": film(0)
}
);
}
path.push(
{
"duration": 2,
"segment": film(2)
}
)
return path;
}
const video_timeline = create_video_timeline();
function getSnapshot() {
return (bool) => {
if (bool) {
data.push(takepicture());
}
}
}
const sprites = [
{
"move": generatePath(path_circle),
"created": performance.now(),
"render": renderCircle()
},
{
"move": generatePath(path_target),
"created": performance.now(),
"render": renderImage(base_image, 100, 100)
},
{
"render": getSnapshot(),
"move": generatePath(video_timeline),
"created": performance.now()
}
];
回答 #1
編集:別の動きの例を追加しました(シアンの四角を見てください)
「一定の時間で『どこかに』到達するにはどうすればよいか」というあなたのコメントへの答えとして、ほとんどの関数を線形化し、時間を固定して方程式を解くことができます。これは直線的な移動では簡単ですが、非線形関数に沿った移動(例えば対数螺旋)のような複雑な場合ではかなり困難です。
一定速度(加速/減速なし)で (x0, y0) から (x1, y1) まで時間 dt で線形移動する場合、線形補間を使用できます:
function generateLinear(x0, y0, x1, y1, dt)
{
return (t) => {
let f0, f1;
f0 = t >= dt ? 1 : t / dt; // linear interpolation (aka lerp)
f1 = 1 - f;
return {
"x": f0 * x0 + f1 * x1, // actually is a matrix multiplication
"y": f0 * y0 + f1 * y1
};
};
}
この関数は、パスを「組み立てる」ために使用できるようになりました。まず、セグメントを生成してパスを定義します。
const path = [
{
"duration": dt1,
"segment": generateLinear(x0, y0, x1, y1, dt1)
},
{
"duration": dt2,
"segment": generateLinear(x1, y1, x2, y2, dt2)
},
{
"duration": dt3,
"segment": generateLinear(x2, y2, x3, y3, dt3)
}
];
総移動時間がどのように扱われ(duration を使用)セグメントのローカル時間に変換されるかに注目してください:
function generatePath(path)
{
let t;
// fixup timing
t = 0;
for (i = 0; i < path.length; i++)
{
path[i].start = t;
t += path[i].duration;
path[i].end = t;
}
return (t) => {
while (path.length > 1 && t >= path[0].end)
{
path.shift(); // remove old segments, but leave last one
}
return path[0].segment(t - path[0].start); // time corrected
};
}
編集:動作例
私はちょうどあなたのためにこの動作する例をさっと作りました。キャンバスやコンテキストを再作成せずに同じものに何度も描く様子を見てください。そして、動きがフレームレートに依存せず、リサジュー関数で定義されていることも見てください。
"use strict";
const cvs = document.querySelector("#cvs");
const ctx = cvs.getContext("2d");
function generateLissajous(dx, dy, tx, ty)
{
return (t) => {
return {
"x": 150 + dx * Math.sin(tx * t),
"y": 75 + dy * Math.cos(ty * t)
};
};
}
function generateLinear(x0, y0, x1, y1, dt)
{
return (t) => {
let f0, f1;
f0 = t >= dt ? 1 : t / dt; // linear interpolation (aka lerp)
f1 = 1 - f0;
return {
"x": f1 * x0 + f0 * x1, // actually is a matrix multiplication
"y": f1 * y0 + f0 * y1
};
};
}
function generatePath(path)
{
let i, t;
// fixup timing
t = 0;
for (i = 0; i < path.length; i++)
{
path[i].start = t;
t += path[i].duration;
path[i].end = t;
}
return (t) => {
let audio;
while (path.length > 1 && t >= path[0].end)
{
path.shift(); // remove old segments, but leave last one
}
if (path[0].hasOwnProperty("sound"))
{
audio = new Audio(path[0].sound);
audio.play();
delete path[0].sound; // play only once
}
return path[0].segment(t - path[0].start); // time corrected
};
}
function generateRenderer(size, color)
{
return (pos) => {
ctx.fillStyle = color;
ctx.fillRect(pos.x, pos.y, size, size);
};
}
const path = [
{
"duration": 3,
"segment": generateLinear(20, 20, 120, 120, 3)
},
{
"sound": "boing.ogg",
"duration": 3,
"segment": generateLinear(120, 120, 120, 20, 3)
},
{
"sound": "boing.ogg",
"duration": 2,
"segment": generateLinear(120, 20, 20, 120, 2)
}
];
const sprites = [
{
"move": generateLissajous(140, 60, 1.9, 0.3),
"created": performance.now(),
"render": generateRenderer(10, "#ff0000")
},
{
"move": generateLissajous(40, 30, 3.23, -1.86),
"created": performance.now(),
"render": generateRenderer(15, "#00ff00")
},
{
"move": generateLissajous(80, 50, -2.3, 1.86),
"created": performance.now(),
"render": generateRenderer(5, "#0000ff")
},
{
"move": generateLinear(10, 150, 300, 20, 30), // 30 seconds
"created": performance.now(),
"render": generateRenderer(15, "#ff00ff")
},
{
"move": generatePath(path),
"created": performance.now(),
"render": generateRenderer(25, "#00ffff")
}
];
const update = () => {
let now, sprite;
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 300, 150);
// put aside so all sprites are drawn for the same ms
now = performance.now();
for (sprite of sprites)
{
sprite.render(sprite.move((now - sprite.created) / 1000));
}
window.requestAnimationFrame(update);
};
window.requestAnimationFrame(update);canvas
{
border: 1px solid red;
}<canvas id="cvs"></canvas>このような動きには requestAnimtionFrame() に頼るべきではありません。
あなたがすべきことはこれです。
- リアルタイム(
t)に基づく移動関数を持ち、この例ではリサジュー軌道です:
function orbit(t)
{
return { "x": 34 * Math.sin(t * 0.84), "y": 45 * Math.cos(t * 0.23) };
}
それらの数字は単なる表示用です。これらはパラメータ化して、カリー化を使って固定し、次のような「orbit()」関数を得ることができます:
function generateLissajousOrbit(dx, tx, dy, ty)
{
return (t) => { // this is the orbit function
return { "x": dx * Math.sin(t * tx), "y": dy * Math.cos(t * ty) };
};
}
この方法で、任意のリサジュー軌道を生成できます:
let movement = generateLissajousOrbit(34, 0.84, 45, 0.23);
明らかに、どんな動作機能も有効です。唯一の制約は次の通りです:
- リアルタイムを表す
tで呼び出す; t時間にxおよびy座標を持つオブジェクトを受け取る。
より簡単な動きは、どのように実装するかは今や明らかであるはずです。また、この方法では、どんな動きも簡単にプラグインできることに注意してください。
- アニメーション/動きのどの時点にいるかを確認してください:
開始時に現在のリアルタイムのミリ秒を、次のように取っておきます:
let mymovingobject = {
"started": performance.now(),
"movement": generateLissajousOrbit(34, 0.84, 45, 0.23)
};
任意の時点でxとyを取得するには、次のように行うことができます。
let now = performance.now();
let pos = mymovingobject.movement(now - mymovingobject.started);
// pos.x and pos.y contain the current coordinates
あなたは、リアルタイムのみに依存するリフレッシュ(アニメーションフレーム)独立の動きを得ることになります。それはあなたの主観的な知覚空間です。
もしマシンに一時的なトラブルが発生したり、何らかの理由でリフレッシュレートが変わった場合(ユーザーがモニターを再キャリブレーションした直後、ウィンドウを120Hzのモニターから60Hzのモニターに移動した場合、その他何であれ)… 動きは依然としてリアルタイムに制約され、フレームレートとは完全に独立しています。
- これで、任意の時点でポールの位置を取得し、レンダリングに使用できるようになりました
requestAnimationFrame() を処理する関数では、上で示したように単に位置をポーリングし、その後オブジェクトを pos.x と pos.y に描画するだけで、実際のリフレッシュレートについて考える必要はありません。
フレームをスキップしてフレームレートを下げることもでき、フレームを数えることでユーザーが頻度を決めるようにすることもできます。例えば次のように:
let frame = 0;
function requestAnimationFrameHandler()
{
if (frame % 2 === 0)
{
window.requestAnimationFrame();
return; // quick bail-out for this frame, see you next time!
}
// update canvas at half framerate
}
フレームレートを下げられることは、特に高周波数モニターが普及している今日では重要です。モニターを変更するだけで、アプリの速度が1秒あたり60ピクセルから120ピクセルにジャンプしてしまいます。これは望む状態ではありません。
requestAnimationFrame() 機能はスムーズなスクロールの万能薬のように見えますが、実際には完全に未知のハードウェアの制約に自分を縛り付けることになります(2035年の最新モニターについて考えてみてください…どうなるか誰にも分かりません)。
この技術は、物理的なフレーム周波数を論理的(ゲームプレイ)速度の要求から分離します。
なんとか意味が通じるといいのですが。
回答 #2
const run() {
requestAnimationFrame (run);
lete elens [8];
const ax (Math.cos(3 frm) rad width) / height; (Math.sin(4 frm) rad height) / width;
const ay
e.x + (ax pointer.xe.x) / 10;
e.y+ (ay pointer.ye.y) / 10;
for (let 11; i < N; i++) {
let e= elems[1];
let ep elems[i-1];
(ep.xe.x e.x (Math.cos(a) (1001))/5)/4;
const a Math.atan2(e.yep.y, e.x ep.х);
e.y + (ep.ye.y (Math.sin(a) (1001))/5)/4;
consts e.use.setAttributeNS(
(1624 (11))/50;
null,
"transfore",
translate($((ep.x + e.x) / 2),$((ep.ye.y) / 2)) rotate($(
(188/ Math.PI) a
1 ) translate(${0},$(0)) scale($(s),$(s))
