Html5 canvas requestAnimationFrame用于动画的基本用法

Html5 canvas requestAnimationFrame用于动画的基本用法,html5-canvas,css-animations,requestanimationframe,Html5 Canvas,Css Animations,Requestanimationframe,我正在创建这个代码,其中有两个矩形:红色的是固定正方形。青色矩形应在红色矩形上旋转。 旋转角度应使用requestAnimationFrame可变。所以,我想要的是角度在0到360之间变化。我该怎么做 这是我的代码: const canvas=document.getElementById(“canvas”) const ctx=canvas.getContext('2d') const width=canvas.width const height=canvas.height 常量背景色=“

我正在创建这个代码,其中有两个矩形:红色的是固定正方形。青色矩形应在红色矩形上旋转。 旋转角度应使用requestAnimationFrame可变。所以,我想要的是角度在0到360之间变化。我该怎么做

这是我的代码:

const canvas=document.getElementById(“canvas”)
const ctx=canvas.getContext('2d')
const width=canvas.width
const height=canvas.height
常量背景色=“#c35033”
const overlycolor='#bcddda'
fillStyle=背景色
圆角矩形(ctx、背景色、0、0、宽度、高度)
const angle=Math.PI
填充半透明覆盖(角度、宽度、覆盖颜色)
//window.requestAnimationFrame(步骤)
函数Fill半透明覆盖(角度、宽度、覆盖颜色){
ctx.save()
ctx.translate(宽度/2,宽度/2)
ctx.旋转(角度)
ctx.translate(-width/2,-width/2)
ctx.fillStyle=叠加颜色
ctx.fillRect(-width*(3/2),-width/2,width*2,width*2)
ctx.restore()
}
函数fillRectangle(上下文、颜色、x、y、宽度、高度){
context.fillStyle=颜色
context.fillRect(x,y,宽度,高度)
}

我在您的代码中添加了一个函数
步骤
: 你需要清理画布。您可以使用clearRect来实现这一点。在本例中,我没有使用clearRect,而是重新绘制背景 接下来需要增加角度:
angle+=.01对于不同的速度,使用不同的增量。最后,再次绘制覆盖层

我希望有帮助

function step(){
  //use requestAnimationFrame with the step function as a callback
  window.requestAnimationFrame(step);
  //fill the background
  fillRectangle(ctx, backgroundColor, 0, 0, width, height);
  //increase the angle
  angle+= .01;
  //paint the overlay
  fillSemiTransparentOverlay(angle, width, overlayColor)
}

//call the function step()
step()
const canvas=document.getElementById(“canvas”)
const ctx=canvas.getContext('2d')
const width=canvas.width
const height=canvas.height
常量背景色=“#c35033”
const overlycolor='#bcddda'
fillStyle=背景色
圆角矩形(ctx、背景色、0、0、宽度、高度)
设angle=Math.PI
填充半透明覆盖(角度、宽度、覆盖颜色)
///////////////////////////
函数步骤(){
//将requestAnimationFrame与step函数一起用作回调函数
window.requestAnimationFrame(步骤);
//填充背景
圆角矩形(ctx,背景色,0,0,宽度,高度);
//加大角度
角度+=.01;
//涂上覆盖层
填充半透明覆盖(角度、宽度、覆盖颜色)
}
步骤(
/////////////////////////
函数Fill半透明覆盖(角度、宽度、覆盖颜色){
ctx.save()
ctx.translate(宽度/2,宽度/2)
ctx.旋转(角度)
ctx.translate(-width/2,-width/2)
ctx.fillStyle=叠加颜色
ctx.fillRect(-width*(3/2),-width/2,width*2,width*2)
ctx.restore()
}
函数fillRectangle(上下文、颜色、x、y、宽度、高度){
context.fillStyle=颜色
context.fillRect(x,y,宽度,高度)
}