//定義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) });