三角函数形成简单的波浪
//定义canvas var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var a = 1;//弧度 var b = 1;//弧度正反的按钮 setInterval(function(){ context.clearRect(0, 0, canvas.width, canvas.height);//清除画布 context.beginPath();//开始画坐标 context.moveTo(0, canvas.height/2)//初始化线的位置 if(b===1){a++}else{a--} if(a>10){b=0}//弧度范围 if(a<-10){b=1}//弧度范围 for (let x = 0; x < canvas.width; x++) { const y = Math.sin(x*0.01)*a+canvas.height/2//sin控制弧度 context.lineTo(x, y)//画坐标 } context.stroke()//根据坐标画线 context.closePath()//结束画坐标 },100)
1、上面是根据a的左右替换来变化,并不像波浪
2、下面是根据波浪的滑动的变化
//定义canvas var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var a = 10;//弧度 var m = 0; //变化初始化 setInterval(function(){ context.clearRect(0, 0, canvas.width, canvas.height);//清除画布 context.beginPath();//开始画坐标 m++; //变化的速度 for (let x = 0; x < canvas.width; x++) { const y = Math.sin(x*0.01+m)*a+canvas.height/2//sin控制弧度 context.lineTo(x, y)//画坐标 } context.stroke()//根据坐标画线 context.closePath()//结束画坐标 },100)
3、前面都是用定时器的方法,现在用requestAnimationFrame
//定义canvas var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var a = 10;//弧度 var m = 0; //移动变化 var timer = requestAnimationFrame(function fn(){ context.clearRect(0, 0, canvas.width, canvas.height);//清除画布 context.beginPath();//开始画坐标 m=m+0.05 for (let x = 0; x < canvas.width; x++) { const y = Math.sin(x*0.01+m)*a+canvas.height/2//sin控制弧度 context.lineTo(x, y)//画坐标 } context.stroke()//根据坐标画线 context.closePath()//结束画坐标 requestAnimationFrame(fn) });