Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

javascript - 使用setInverval调用函数以创建动画形状(Calling a function with setInverval to create animated shapes)

I'm learning JavaScript and I would like to know how to create multiple animated circles in the same canvas.(我正在学习JavaScript,并且想知道如何在同一画布上创建多个动画圆。)

I've created this function so I don't have to repeat the code for all the different circles:(我已经创建了此函数,因此不必重复所有不同圈子的代码:) const canvas = document.querySelector("canvas").getContext("2d"); balls = (color, x, y, dx, dy) => { setInterval (() => { canvas.clearRect(0, 0, 600, 600); canvas.fillStyle = color; canvas.beginPath(); canvas.arc(x, y, 20, 0, Math.PI * 2); canvas.fill(); if (x >= 600 || x <= 0) { dx = -dx; } if (y >= 600 || y <= 0) { dy = -dy; } x = x + dx; y = y + dy; }, 20); } balls("#00f", 35, 35, 5, 5); balls("#f00", 400, 35, 5, 5); However it's not working correctly.(但是,它不能正常工作。) Only the second ball appears in the screen, and the first ball keeps blinking.(屏幕上仅出现第二个球,第一个球保持闪烁。) I hope someone can help me.(我希望有一个人可以帮助我。) Thanks.(谢谢。)   ask by Jo?o Mira translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Welcome to the StackOverflow Mira!(欢迎来到StackOverflow Mira!)

The problem with your code is calling canvas.clearRect(0, 0, 600, 600).(您代码的问题是调用canvas.clearRect(0,0,600,600)。) Try to animate both balls within the same interval handler.(尝试在同一间隔处理程序中为两个球设置动画。) Concept is simple, draw the positions of all the objects within the same frame.(概念很简单,绘制同一框架内所有对象的位置。) const canvas = document.querySelector("canvas").getContext("2d"); let myBalls=[]; //animation handler setInterval (() => { canvas.clearRect(0, 0, 200, 200); myBalls.forEach(ball=>{ canvas.fillStyle = ball.color; canvas.beginPath(); canvas.arc(ball.x, ball.y, 5, 0, Math.PI * 2); canvas.fill(); if (ball.x >= 200 || ball.x <= 0) { ball.dx = -ball.dx; } if (ball.y >= 200 || ball.y <= 0) { ball.dy = -ball.dy; } ball.x = ball.x + ball.dx; ball.y = ball.y + ball.dy; }); }, 20); balls = (color, x, y, dx, dy) => { myBalls.push({color, x, y, dx, dy}); } balls("black", 35, 35, 5, 5); balls("red", 100, 35, 5, 5); <canvas width="200" height="200"></canvas>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...