gpt4 book ai didi

javascript - requestAnimationFrame 没有在 Canvas 上绘制任何东西

转载 作者:行者123 更新时间:2023-11-30 15:10:15 25 4
gpt4 key购买 nike

我有这段代码可以在屏幕上绘制正弦波,但由于某种原因, Canvas 上什么也没有出现。这很可能与 requestAnimFrame 完全无关,但我认为这是问题所在。draw 函数中的 var y 应该只是一个简单的正弦波函数 Asin(kx - omega*t),其中 k 是波数,它 = 2pi/波长。

Javascript:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cx = 0,
t = 0,
Amp1 = 200,
Wav1 = 100,
omega = 0.01;
function draw(x, t) {
var y = Amp1 * Math.sin(x(2 * Math.PI / Wav1) - omega * t) + 999;
ctx.beginPath();
ctx.moveTo(t + 100, y);
ctx.lineTo(t + 100, y + 1);
ctx.stroke();
ctx.closePath();
}
window.requestAnimFrame = (function (callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 100);
};
}());
function animate() {
setInterval(function () {
window.requestAnimFrame(animate);
var newX = cx,
newT = t;
cx += 0.5;
t += 0.5;
draw(newX, newT);
}, 50);
}
animate();

编辑:不太清楚为什么 Amp1Wav1 会变成青色?

最佳答案

首先,您产生了无数次对 animate 的调用,因为您在每个动画帧和每 50 毫秒调用它,因此请删除间隔或对 requestAnimFrame 的调用

然后,您的其余代码将正常运行。我不确定你为什么把 + 999 放到 y 上,但这就是你什么都看不到的原因,它只是从屏幕上消失了(canvas ).由于我不是数学家,我可能已经破坏了你的正弦曲线,但我只是想向你展示它确实有效。

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cx = 0,
t = 0,
Amp1 = 200,
Wav1 = 100,
omega = 0.01;

function draw(x, t) {
var y = Amp1 * Math.sin(x*(2 * Math.PI / Wav1) - omega * t);
ctx.beginPath();
ctx.moveTo(t + 100, y);
ctx.lineTo(t + 100, y + 1);
ctx.stroke();
ctx.closePath();
}
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
window.setTimeout(callback, 100);
};
}());

function animate() {
window.requestAnimFrame(animate);
var newX = cx,
newT = t;
cx += 0.5;
t += 0.5;
draw(newX, newT);
}
animate();
<canvas id="canvas"></canvas>

关于javascript - requestAnimationFrame 没有在 Canvas 上绘制任何东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45211482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com