我有x,y动态数组值......
使用x,y值在HTML5画布中生成移动的正弦波,三角波,方波,锯齿波....
答案 0 :(得分:4)
未改变的正弦波是显而易见的 - Math.sin(x),但这里是其他的......
假设:
p = period
o = oscillation
x = x coordinate
找到y(y坐标):
// squared sine
function squareY(x) {
return( (x%p)<o?o:0 );
}
// sawtooth sine
function sawY(x){
return( x%p );
}
// triangular sine
function triY(x){
return( Math.abs((x%p)-o) );
}
在样本图中:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var p=30; // period
var o=15; // oscillation
// plot sawtooth sine wave
ctx.beginPath();
for(var x=0;x<120;x++){
var y=sawY(x);
ctx.lineTo(x,y);
}
ctx.stroke();
// plot squared sine wave
ctx.beginPath();
for(var x=0;x<60;x++){
var y=squareY(x);
y+=75; // just offsetting so drawings don't overlap
ctx.lineTo(x,y);
}
ctx.stroke();
// plot triangular sine wave
ctx.beginPath();
for(var x=0;x<60;x++){
var y=triY(x);
y+=150; // just offsetting so drawings don't overlap
ctx.lineTo(x,y);
}
ctx.stroke();
[已添加示例动画]
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.lineWidth=3;
var p=30; // period
var o=15; // oscillation
var fps = 60;
var n=0;
animate();
function animate() {
setTimeout(function() {
requestAnimationFrame(animate);
// Drawing code goes here
n+=1.5;
if(n>300){
n=0;
}
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
for(var x=0;x<n;x++){
var y=sawY(x);
ctx.lineTo(x,y+50);
}
ctx.stroke();
}, 1000 / fps);
}
// sawtooth sine
function sawY(x){
return( x%p );
}