HTML5 Game - Canvas Shape Logo

Drawing a simple logo and randomizing its position, rotation, and scale

The following code shows how to use of transformations to transform a complex shape.

We can draw shape at the origin, and then use transforms to move it somewhere on the screen.

Demo

ResultView the demo in separate window

<html>
    <head>
        <script>
            function drawShape(context){
                // draw Hello Logo! text
                context.beginPath();//from   w  ww  . j  ava 2s . c o m
                context.font = "10pt Calibri";
                context.textAlign = "center";
                context.textBaseline = "middle";
                context.fillStyle = "red";
                context.fillText("Hello java2s.com!", 0, 0);
                context.closePath();
                
                // define style for both waves
                context.lineWidth = 2;
                context.strokeStyle = "blue";
                
                // draw top wave
                context.beginPath();
                context.moveTo(-30, 10);
                context.bezierCurveTo(-5, 5, 5, 15, 30, 10);
                context.stroke();
                
                // draw bottom wave
                context.beginPath();
                context.moveTo(-30, 15);
                context.bezierCurveTo(-5, 10, 5, 20, 30, 15);
                context.stroke();
            }
            
            function getRandomX(canvas){
                return Math.round(Math.random() * canvas.width);
            }
            
            function getRandomY(canvas){
                return Math.round(Math.random() * canvas.height);
            }
            
            function getRandomSize(){
                return Math.round(Math.random() * 5);
            }
            
            function getRandomAngle(){
                return Math.random() * Math.PI * 2;
            }
            
            window.onload = function(){
                let canvas = document.getElementById("myCanvas");
                let context = canvas.getContext("2d");
                
                for (let n = 0; n < 50; n++) {
                    context.save();
                    context.translate(getRandomX(canvas), getRandomY(canvas));
                    context.rotate(getRandomAngle());
                    let randSize = getRandomSize();
                    context.scale(randSize, randSize);
                    drawShape(context);
                    context.restore();
                }
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Note

The code draw a shape with function called drawShape().

Related Topics