gpt4 book ai didi

javascript - HTML5 Canvas requestAnimationFrame() 不起作用

转载 作者:行者123 更新时间:2023-12-01 03:45:25 25 4
gpt4 key购买 nike

我正在尝试使用 window.requestAnimationFrame() 来做一个简单的动画。不知何故,该函数没有被递归调用,也没有给出正确的代码。我文件的 javascript 代码是:

function OilPainting(){
this.initialize=function(){
var x=100;
var canvas=document.getElementById("canvas");
canvas.width=window.innerWidth;
canvas.height=window.innerHeight;

var context=canvas.getContext('2d');
animate(canvas,context);
}
}

var x=100;
var animate=function(canvas,context){
window.requestAnimationFrame(animate);
console.log("a");
//console.log("a");
/*for(var i=0;i<1;i++){
var x=Math.random()*window.innerWidth;
var y=Math.random()*window.innerHeight;
context.beginPath();
context.arc(x,y,30,0,2*Math.PI);
context.stroke();
//console.log("here");
x+=1;*/

context.beginPath();
context.arc(x,100,30,0,2*Math.PI);
context.clearRect(0,0,innerWidth,innerHeight);
//console.log(x);
context.stroke();
x+=100;
// console.log(x);
}
var app=new OilPainting();
app.initialize();

在这里,虽然控制台 a 正在递归打印,但圆圈并未形成。我的 Codepen 的链接是 Here .requestAnimationFrame()到底是如何使用的?

最佳答案

您的代码有太多问题...

这是应该如何完成的

var x = 100;

function OilPainting() {
this.initialize = function() {
var canvas = document.getElementById("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var context = canvas.getContext('2d');
animate(canvas, context);
}
}

var animate = function(canvas, context) {
//console.log("a");
context.clearRect(0, 0, innerWidth, innerHeight);
context.beginPath();
context.arc(x, 100, 30, 0, 2 * Math.PI);
context.stroke();
x += 1;

requestAnimationFrame(function() {
animate(canvas, context);
});
}

var app = new OilPainting();
app.initialize();
body{margin:0;overflow:hidden}canvas{border:1px solid #d3d3d3}
<canvas id="canvas"></canvas>

为没有给出任何解释而道歉

关于javascript - HTML5 Canvas requestAnimationFrame() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43607912/

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