Moving Square

canvas moving square

by shryme

HTML

<p id="text">1</p>
<input type="button" value="+" id="btnAdd">
<input type="button" value="-" id="btnSub">
<body>
    <canvas id="ex1" width="525" height="200" style="border: 5px solid black;" </canvas>
        <p></p>

CSS

body {
          margin: 0px;
          padding: 0px;
      }

JavaScript

var x = 0;
    var y = 15;
    var speed = 10;
    //Will be use to know if we need to add or substract to the speed var
    var isRight = true;


    document.getElementById('text').innerText = speed;

    document.getElementById('btnAdd').addEventListener('click', function (event) {
        //if the square is going right, we do ++, if not (going left, we do -- because the speed is negative)
        if (isRight) speed++;
        else speed--;
        document.getElementById('text').innerText = speed;
    });

    document.getElementById('btnSub').addEventListener('click', function (event) {
        if (isRight) speed--;
        else speed++;
        document.getElementById('text').innerText = speed;
    });





    function animate() {

        reqAnimFrame = window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame;

        reqAnimFrame(animate);

        x += speed;

        if (x <= 0 || x >= 475) {
            speed = -speed;
            //We change the bool because the square is changing direction, if he was going right, the bool will become false, if he was going left, the bool will become true.
            isRight = !isRight;
        }
        document.getElementById('text').innerText = speed;

        draw();
    }


    function draw() {
        var canvas = document.getElementById("ex1");
        var context = canvas.getContext("2d");

        context.clearRect(0, 0, 600, 170);
        context.fillStyle = "#ff00ff";
        context.fillRect(x, y, 40, 40);
    }

    animate();