我试图在画布上用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>
我的结果应该看起来像+
最佳答案
循环波浪,然后在内部循环(即反转两个循环)。
目标是在移动到下一波之前绘制出波浪的所有圆。这样,您可以确保将波浪的圆圈绘制在前一个圆圈的上方。
另外,您可能要考虑使用基于时间的增量而不是帧数。不能保证动画帧是规则的,并且动画帧的速率取决于用户的系统。
//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>