线合同并在html中扩展

时间:2018-09-11 20:06:58

标签: javascript html5 html5-canvas

我想制作一条沿x轴随机收缩和扩展的线,该线应从canvas的中间开始。我只能以一种方式移动生产线,而不能以两种方式移动!我有代码,如果可以的话请帮助我,我将非常感谢!

<!DOCTYPE html>

<style>
    canvas {
        border: solid;
        border-color: black; }
</style>

<canvas id="canvas">
</canvas>
<script>

    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    ctx.strokeStyle = "black";
    var posX = 0;
    var lineLength = 50;
    var speed = 2;

    function drawLine() {
        ctx.beginPath();
        ctx.moveTo(posX, 50);
        ctx.lineTo(posX + lineLength, 50);
        ctx.stroke();
    }

    function moveLine() {
        posX += speed;
        if (posX < 0 || posX > canvas.width - 50) {
            speed = speed * -1;
        }
    }

    function loop() {
        // clear old frame;
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        moveLine();
        drawLine();
        requestAnimationFrame(loop);
    }
    requestAnimationFrame(loop);
</script>

1 个答案:

答案 0 :(得分:2)

您要在循环中修改lineLength的值,而不是posX。像这样:

function moveLine() {
    lineLength += speed;
    if (lineLength < 0 || lineLength > canvas.width - 50) {
        speed = speed * -1;
    }
}

然后,您只需要将行居中:

function drawLine() {
    var center = canvas.width/2;
    ctx.beginPath();
    ctx.moveTo(center - (lineLength/2), 50);
    ctx.lineTo(center + (lineLength/2), 50);
    ctx.stroke();
}

由于行的X位置不变,因此根本不需要posX