我试图在画布上用Javascript制作水波,但是出了点问题。
我的想法是制作3种不同颜色的波浪,但是它们相互透支。 我无法弄清楚问题出在哪里。
<!DOCTYPE HTML>
<html>
<style>
<!-- 100% area -->
body, html {
height: 100%;
width: 100%;
}
</style>
<body>
<canvas id="myCanvas" ></canvas>
<script>
//get window size
var canvas = document.getElementById( "myCanvas" );
canvas.width = window.innerWidth; /// equal to window dimension
canvas.height = window.innerHeight;
// get the context
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext('2d');
// VARIABLES
var frameCount=0;
var N = 30;
var positionXTeiler= Math.floor(canvas.width/(N-N/2));
var size = 50;
var xOffset = 200;
var colors = [];
var amplitude = 200;
var wavesCount = 3;
var init = function()
{
colors.push("rgba(0,0,128,1)");
colors.push("rgba(0,0,255,1)");
colors.push("rgba(47,86,233,1)");
}
var draw = function() {
context.clearRect (0, 0, canvas.width, canvas.height);
for (i=0; i<N; i++) {
for (n=0; n<wavesCount; n++) {
var x = amplitude*Math.sin (frameCount*0.02+n*Math.PI/2);
context.save();
context.fillStyle = colors[n];
context.beginPath();
context.arc(positionXTeiler*i+x-xOffset,canvas.height-n*20,size,0,Math.PI*2,true);
context.closePath();
context.fill();
context.restore();
}
}
// count the frame and loop the animation
frameCount = frameCount+1;
requestAnimationFrame(draw);
};
// start the loop
init();
draw();
</script>
</body>
</html>
&#13;
我的结果应该像移动
那样答案 0 :(得分:5)
循环波浪,在里面循环圆圈(即反转两个循环)。
目标是在移动到下一个之前画出波浪的所有圆圈。通过这种方式,您可以确保将波的圆绘制在前一个圆的顶部。
此外,您可能需要考虑使用基于时间的增量而不是帧数。动画帧不保证是常规的,它们的速率取决于用户的系统。
//get window size
var canvas = document.getElementById( "myCanvas" );
canvas.width = window.innerWidth; /// equal to window dimension
canvas.height = window.innerHeight;
// get the context
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext('2d');
// VARIABLES
var frameCount=0;
var N = 30;
var positionXTeiler= Math.floor(canvas.width/(N-N/2));
var size = 50;
var xOffset = 200;
var colors = [];
var amplitude = 200;
var wavesCount = 3;
var init = function()
{
colors.push("rgba(0,0,128,1)");
colors.push("rgba(0,0,255,1)");
colors.push("rgba(47,86,233,1)");
}
var draw = function() {
context.clearRect (0, 0, canvas.width, canvas.height);
for (n=wavesCount-1; n>=0; n--) {
for (i=0; i<N; i++) {
var x = amplitude*Math.sin (frameCount*0.02+n*Math.PI/2);
context.save();
context.fillStyle = colors[n];
context.beginPath();
context.arc(positionXTeiler*i+x-xOffset,canvas.height-n*20,size,0,Math.PI*2,true);
context.closePath();
context.fill();
context.restore();
}
}
// count the frame and loop the animation
frameCount = frameCount+1;
requestAnimationFrame(draw);
};
// start the loop
init();
draw();
<!-- 100% area -->
body, html {
height: 100%;
width: 100%;
}
<!DOCTYPE HTML>
<html>
<body>
<canvas id="myCanvas" ></canvas>
</body>
</html>