1

在此处输入图像描述

我有 x,y 动态数组值...

使用 x,y 值在 HTML5 画布中生成移动正弦波、三角波、方波、锯齿波......

4

1 回答 1

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 );
    }
于 2013-10-02T18:58:33.913 回答