How to draw a curve that could move to left with canvas?

前端 未结 1 1406
悲&欢浪女
悲&欢浪女 2021-01-03 05:51

I\'m writing a program that will draw the sine curve with canvas.
HTML:


    Y         


        
相关标签:
1条回答
  • 2021-01-03 06:27

    One of the basic ideas of the <canvas> element is that the computer 'forgets' the drawing commands and only saves the pixels, like a bitmap. So to move everything to the left, you need to clear the canvas and draw everything again.

    There is also one thing I'd like to advise you - you always start with x = 0 and y = 0, but obviously at x = 0 then y is not necessarily equal to 0 as well. EDIT: implemented this.

    Anyway, I ended up with this code: 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);
    }
    
    0 讨论(0)
提交回复
热议问题