Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript RequestAnimationFrame工作不正常_Javascript_Canvas - Fatal编程技术网

Javascript RequestAnimationFrame工作不正常

Javascript RequestAnimationFrame工作不正常,javascript,canvas,Javascript,Canvas,调用requestAnimationFrame后,正方形不会移动。 不过,预计广场会移动 这个代码有什么问题 //检查画布是否存在并获取画布的上下文 var canvas=document.getElementsByTagName('canvas')[0]; var ctx=canvas.getContext('2d'); //添加画布的宽度和高度 变量宽度=640,高度=480; //将画布宽度和高度作为变量 canvas.width=宽度,canvas.height=高度; 矩形={ x:

调用requestAnimationFrame后,正方形不会移动。 不过,预计广场会移动

这个代码有什么问题

//检查画布是否存在并获取画布的上下文
var canvas=document.getElementsByTagName('canvas')[0];
var ctx=canvas.getContext('2d');
//添加画布的宽度和高度
变量宽度=640,高度=480;
//将画布宽度和高度作为变量
canvas.width=宽度,canvas.height=高度;
矩形={
x:0,,
y:0,
宽度:100,
身高:100
}
ctx.fillStyle='红色';
ctx.fillRect(矩形x、矩形y、矩形宽度、矩形高度);
函数animate(){

如果(rect.x每个帧都必须重新绘制画布,并替换矩形。好的,这是一个解决方案,以防有人像我一样卡住。你应该这样做:但我认为这只是为了测试目的?是的,第一次尝试。你的解决方案似乎更好,因为我注意到在我的案例中,第一帧中没有出现红方块。我刚从我的本地文件在InternetExplorer中尝试了这个示例,它似乎结巴了,而在JSFIDLE中却没有。可能是什么问题?
    // Check if canvas exists and get the context of the canvas
var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');

// Add width and height of the canvas
var width = 640, height = 480;

// Make the canvas width and height as the variables
canvas.width = width, canvas.height = height;

rect = {
    x: 0,
    y: 0,
    width: 100,
    height: 100
}

ctx.fillStyle = 'red';
ctx.fillRect(rect.x,rect.y,rect.width,rect.height);

function animate(){

    if(rect.x <= 200){
        rect.x += 5;
    }
    requestID = requestAnimationFrame(animate);
}

requestAnimationFrame(animate);