gpt4 book ai didi

javascript - 使形状在 Canvas 上向上移动

转载 作者:行者123 更新时间:2023-11-30 20:16:12 24 4
gpt4 key购买 nike

目前,我有一个 Canvas ,它是您浏览器的宽度和高度。使用此代码:

var requestAnimationFrame = window.requestAnimationFrame || 
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;

var canvas = document.getElementById("canvas");
var width = window.innerWidth;
var height = window.innerHeight;
var circle = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;


for(var i = 0; i < numofcirc; i++)
{
name = "circleno" + i;
var name = new Array(3);
name = [height, rndwidth, rndradius, vel]
circles[i] = name;
}


var vel = 2;
var circles = [];
var numofcirc = 1;
var name;

function DrawCircle()
{
rndwidth = Math.floor((Math.random() * width) + 1);
height = height - 13;
rndradius = Math.floor((Math.random() * 15) + 5);

circle.beginPath();
circle.arc(rndwidth, height, rndradius, 0, 2*Math.PI);
circle.fillStyle = "white";
circle.fill();
circle.translate(0,6);
}

function Move()
{
circle.translate(0,6);
requestAnimationFrame(Move);
}

Move();
DrawCircle();

我可以创建一个随机放置在屏幕底部的圆圈。不起作用的代码是这样的:

function Move() 
{
circle.translate(0,6);
requestAnimationFrame(Move);
}
Fireworks();

DrawCircle(); 被调用时,圆被绘制在 Canvas 上。然后 Move(); 被调用。因为它使用 requestAnimationFrame 函数 Move(); 一遍又一遍地重复。我希望此代码将之前绘制的圆圈向上移动 6,因此看起来圆圈向上移动。如果我将 circle.translate(0,6); 添加到 DrawCircle(); 函数并将 DrawCircle(); 函数更改为这个:

function DrawCircle()
{
rndwidth = Math.floor((Math.random() * width) + 1);
height = height - 13;
rndradius = Math.floor((Math.random() * 15) + 5);
circle.beginPath();
circle.arc(rndwidth, height, rndradius, 0, 2*Math.PI);
circle.fillStyle = "white";
circle.fill();
circle.translate(0,6);
requestAnimationFrame(Move);
}
DrawCircle();

然后它继续在屏幕上画出一排排圆圈,圆圈之间的距离都是 6。

有什么办法可以让一个圆圈在绘制时在屏幕上向上移动?

感谢@HelderSepu 的帮助!

最佳答案

您应该查看示例并从中构建...

这是一个简单的例子:

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.width = canvas.height = 170;

var circles = []
circles.push({color:"red", x:120, y:120, r:15, speed:{x: 0, y: -0.5}})
circles.push({color:"blue", x:80, y:120, r:20, speed:{x: -0.5, y: -2.5}})
circles.push({color:"green", x:40, y:120, r:5, speed:{x: -1.5, y: -1.0}})

function DrawCircle() {
context.clearRect(0, 0, canvas.width, canvas.height);
circles.forEach(function(c) {
c.x += c.speed.x;
c.y += c.speed.y;

context.beginPath();
context.arc(c.x, c.y, c.r, 0, 2 * Math.PI);
context.fillStyle = c.color;
context.fill();

if (c.x + c.r < 0) c.x = canvas.width + c.r
if (c.y + c.r < 0) c.y = canvas.height + c.r
});

window.requestAnimationFrame(DrawCircle);
}

DrawCircle();
<canvas id="canvas"></canvas>

但是如果你要制作更多的动画,你应该考虑使用游戏引擎,
有很多很棒的开源引擎:
https://github.com/collections/javascript-game-engines

关于javascript - 使形状在 Canvas 上向上移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51895893/

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