我正在创建这个代码,其中有两个矩形:红色的是固定的正方形。青色矩形应该在红色矩形上旋转。旋转角度应使用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" />
发布于 2019-06-09 15:37:05
我已经在您的代码中添加了一个函数step:您需要清除画布。您可以使用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" />
https://stackoverflow.com/questions/56509657
复制相似问题