HTML5 Game - Drawing a shape from a series of Bezier curve

Introduction

The following code shows how to draw a shape from a series of Bezier curve.

Demo

ResultView the demo in separate window

<html>
    <head>
        <script>
            window.onload = function(){
                let canvas = document.getElementById("myCanvas");
                let context = canvas.getContext("2d");
                /*from ww  w  .  ja v a  2s .  co  m*/
                let startX = 200;
                let startY = 100;
                
                context.beginPath();
                context.moveTo(startX, startY);
                context.bezierCurveTo(startX - 20, startY + 20, startX - 140, startY + 170, startX + 160, startY + 170);
                context.bezierCurveTo(startX + 30, startY + 10, startX + 150, startY + 100, startX + 170, startY + 170);
                context.bezierCurveTo(startX + 50, startY + 70, startX + 250, startY + 140, startX + 220, startY + 120);
                context.bezierCurveTo(startX + 20, startY - 40, startX + 200, startY - 150, startX + 170, startY - 130);
                context.bezierCurveTo(startX + 10, startY - 75, startX + 180, startY - 160, startX + 180, startY - 130);
                context.bezierCurveTo(startX + 30, startY - 75, startX - 120, startY - 110, startX, startY);
                context.closePath();
                
                // add a radial gradient
                let grdCenterX = 260;
                let grdCenterY = 80;
                let grd = context.createRadialGradient(grdCenterX, grdCenterY, 10, grdCenterX, grdCenterY, 200);
                grd.addColorStop(0, "#8ED6FF"); // light blue
                grd.addColorStop(1, "#004CB3"); // dark blue
                context.fillStyle = grd;
                context.fill();
                
                // set the line width and stroke color
                context.lineWidth = 5;
                context.strokeStyle = "#0000ff";
                context.stroke();
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Related Topic