requestAnimationFrame 动画的基本使用

Basic use of requestAnimationFrame for animation

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

这是我的代码:

const canvas = document.getElementById("canvas")
const ctx = canvas.getContext('2d')

const width = canvas.width
const height = canvas.height

const backgroundColor = '#c35033'
const overlayColor = '#bcddda'

fillStyle = backgroundColor

fillRectangle(ctx, backgroundColor, 0, 0, width, height)

const angle = Math.PI
fillSemiTransparentOverlay(angle, width, overlayColor)
// window.requestAnimationFrame(step)

function fillSemiTransparentOverlay(angle, width, overlayColor) {
  ctx.save()
  ctx.translate(width / 2, width / 2)
  ctx.rotate(angle)
  ctx.translate(-width / 2, -width / 2)
  ctx.fillStyle = overlayColor
  ctx.fillRect(-width * (3 / 2), -width / 2, width * 2, width * 2)
  ctx.restore()
}

function fillRectangle(context, color, x, y, width, height) {
  context.fillStyle = color
  context.fillRect(x, y, width, height)
}
<canvas id="canvas" width="500" height="500" />

我已经在您的代码中添加了一个函数 step: 您需要清除 canvas。您可以使用 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

const backgroundColor = '#c35033'
const overlayColor = '#bcddda'

fillStyle = backgroundColor

fillRectangle(ctx, backgroundColor, 0, 0, width, height)

let angle = Math.PI
fillSemiTransparentOverlay(angle, width, overlayColor)


///////////////////////////
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)
}
step()
/////////////////////////

function fillSemiTransparentOverlay(angle, width, overlayColor) {
  ctx.save()
  ctx.translate(width / 2, width / 2)
  ctx.rotate(angle)
  ctx.translate(-width / 2, -width / 2)
  ctx.fillStyle = overlayColor
  ctx.fillRect(-width * (3 / 2), -width / 2, width * 2, width * 2)
  ctx.restore()
}

function fillRectangle(context, color, x, y, width, height) {
  context.fillStyle = color
  context.fillRect(x, y, width, height)
}
<canvas id="canvas" width="500" height="500" />