HTML5 Game - Canvas Bezier curves

Introduction

A Bezier curve is a path between two points which is shaped by control points.

The control points pull the line toward them.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>

<head>
    <script>
        window.onload = function() {
            canvas = document.getElementById("canvasArea");
            context = canvas.getContext("2d");

            //LAYOUT parameters.
            let xStart = 50;//  w w  w  .ja  va  2s .co m
            let yStart = 25;
            let xControl1 = 175;
            let yControl1 = 50;
            let xControl2 = 25;
            let yControl2 = 125;
            let xEnd = 125;
            let yEnd = 175;

            //ATTRIBUTES of curve.
            context.strokeStyle = "orange";
            context.lineWidth = 7;
            context.shadowOffsetX = 3;
            context.shadowOffsetY = 3;
            context.shadowBlur = 5;
            context.shadowColor = "gray";

            //STARTING point.
            context.beginPath();
            context.moveTo(xStart, yStart);

            //BEZIER curve.
            context.bezierCurveTo(xControl1, yControl1,
                xControl2, yControl2,
                xEnd, yEnd);
            //DRAW curve.
            context.stroke();

            //DISPLAY control points.
            displayPoint(xStart, yStart, "S");
            displayPoint(xControl1, yControl1, "1");
            displayPoint(xControl2, yControl2, "2");
            displayPoint(xEnd, yEnd, "E");

            //DISPLAY POINT function.
            function displayPoint(xPos, yPos, text) {
                //ATTRIBUTES.
                context.font = "10pt Arial";
                context.fillStyle = "black";
                context.textAlign = "center";
                context.textBaseline = "middle";
                context.shadowColor = "white";

                //DISPLAY text.
                context.fillText(text, xPos, yPos);
            }
        }
    </script>
</head>

<body>

    <div style="width:200px;height:200px;
                 margin:0 auto; padding:5px;">
        <canvas id="canvasArea" width="200" height="200" style="border:2px solid black">
            Your browser doesn't currently support HTML5 Canvas.
        </canvas>
    </div>
</body>

</html>

Related Topic