HTML5 Game - Moving and Rotating an Image

Description

Moving and Rotating an Image

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <style>
        #canvas {/*from   w  w  w  .  ja  va  2 s . com*/
            border: 1px solid #03F;
        }
    </style>
    <script>
        let canvas;
        let context;

        let gear = new Image();

        let xpos;

        let stepCounter; // counter for the current step 
        let stepDegrees; // how much to rotate each step 
        let stepDistance; // how far to move image each step 
        let stepSpeed; // how fast to rotate and move the image 
        let stepsFullRevolution; // how many steps in a full rotation 

        function init() {
            canvas = document.getElementById('canvas');
            context = canvas.getContext('2d');

            // Initialize our step counter for the rotation 
            stepCounter = 0;
            stepDegrees = 2;
            stepDistance = 2;
            stepSpeed = 5;
            stepsFullRevolution = parseInt(360 / stepDegrees);

            gear.addEventListener('load', initGear, false);

            gear.src = 'http://java2s.com/style/demo/jet.png';
        }
        function initGear() {
            xpos = -(gear.width / 2);
            moveGear();
        };

        function moveGear() {
            context.clearRect(0, 0, canvas.width, canvas.height);
            context.save();
            xpos += stepDistance;
            context.translate(xpos, canvas.height - (gear.width / 2));
            context.rotate(Math.PI * stepDegrees * stepCounter / 180);
            context.drawImage(gear, -(gear.width / 2), -(gear.height / 2), gear.width, gear.height);
            context.restore();
            if ((xpos - (gear.width / 2)) < canvas.width) {
                stepCounter++;
                if (stepCounter >= (stepsFullRevolution - 1)) {
                    stepCounter = 0;
                }
                setTimeout('moveGear() ', stepSpeed);
            }
        }
        window.addEventListener('load', init, false);
    </script>
</head>

<body>
    <h1>The Rolling Cog</h1>
    <canvas id="canvas" width="600" height="100">
        The Canvas element is not supported in this browser.
    </canvas>
</body>

</html>

Related Topic