I have x,y dynamic array values...
Using x,y values generate moving sine ,triangular,square,sawtooth waves in HTML5 canvas....
The unaltered sine wave is obvious--Math.sin(x), but here are the others...
Given:
p = period
o = oscillation
x = x coordinate
Find y (the y coordinate):
// 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) );
}
In sample plots:
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();
[ Added example animation ]
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 );
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.