4

sine curveキャンバスで描画するプログラムを書いています。
HTML:

<canvas id="mycanvas" width="1000" height="100">
    Your browser is not supported.
</canvas>

JavaScript:

var canvas = document.getElementById("mycanvas");
if (canvas.getContext) {
    var ctx = canvas.getContext("2d");
    ctx.lineWidth = 3;
    var x = 0,
        y = 0;
    var timeout = setInterval(function() {
        ctx.beginPath();
        ctx.moveTo(x, y);
        x += 1;
        y = 50 * Math.sin(0.1 * x) + 50;
        ctx.lineTo(x, y);
        ctx.stroke();
        if (x > 1000) {
            clearInterval(timeout);
        }
    }, 10);
}

これは本当にうまく機能します: http://jsfiddle.net/HhGnb/

ただし、キャンバスの幅は 100px しか指定できないため、曲線の左端の 100px しか表示されません。http://jsfiddle.net/veEyM/1/
この効果をアーカイブしたい: 曲線の右点がキャンバスの幅よりも大きい場合、曲線全体が左に移動する可能性があるため、曲線、それは曲線が左に流れているようなものです。それをしてもいいですか?

4

1 に答える 1

11

この要素の基本的な考え方の 1 つは<canvas>、コンピューターが描画コマンドを「忘れ」、ビットマップのようにピクセルのみを保存するというものです。したがって、すべてを左に移動するには、キャンバスをクリアして、すべてを再度描画する必要があります。

また、アドバイスしたいことが 1 つあります。常に x = 0 および y = 0 から始めますが、明らかに x = 0 の場合、y も必ずしも 0 に等しいとは限りません。編集:これを実装しました。

とにかく、私はこのコードで終わった: http://jsfiddle.net/veEyM/5/

var canvas = document.getElementById("mycanvas");
var points = {}; // Keep track of the points in an object with key = x, value = y
var counter = 0; // Keep track when the moving code should start

function f(x) {
    return 50 * Math.sin(0.1 * x) + 50;
}

if (canvas.getContext) {
    var ctx = canvas.getContext("2d");
    ctx.lineWidth = 3;
    var x = 0,
        y = f(0);
    var timeout = setInterval(function() {
        if(counter < 100) { // If it doesn't need to move, draw like you already do
            ctx.beginPath();
            ctx.moveTo(x, y);
            points[x] = y;
            x += 1;
            y = f(x);
            ctx.lineTo(x, y);
            ctx.stroke();
            if (x > 1000) {
                clearInterval(timeout);
            }
        } else { // The moving part...
            ctx.clearRect(0, 0, 100, 100); // Clear the canvas
            ctx.beginPath();
            points[x] = y;
            x += 1;
            y = f(x);
            for(var i = 0; i < 100; i++) {
                // Draw all lines through points, starting at x = i + ( counter - 100 )
                // to x = counter. Note that the x in the canvas is just i here, ranging
                // from 0 to 100
                ctx.lineTo(i, points[i + counter - 100]);
            }
            ctx.stroke();
        }
        counter++;
    }, 10);
}
于 2011-05-17T15:57:21.920 に答える