HTML5 Game - Drawing Cubic Bezier Curves

Introduction

The bezierCurveTo method draws a curve from the end of the previous sub-path to the point specified by the 5th and 6th method arguments.

There are two controls points specified by the first four arguments.

The following code shows the use of this method.

It also has some additional paths to make it easier to understand the relationship between the argument values and the curve that is produced.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <style>
            canvas {border: thin solid black}
            body > * {float:left;}
        </style>
    </head>
    <body>
        <canvas id="canvas" width="500" height="140">
            Your browser doesn't support the <code>canvas</code> element
        </canvas>
        <script>
            let canvasElem = document.getElementById("canvas");
            let ctx = canvasElem.getContext("2d");

            let startPoint = [50, 100];/*from   w  w  w  .j  a  va 2s.c om*/
            let endPoint = [400, 100];
            let cp1 = [250, 50];
            let cp2 = [350, 50];
            
            canvasElem.onmousemove = function(e) {
                if (e.shiftKey) {
                    cp1 = [e.clientX, e.clientY];
                } else if (e.ctrlKey) {
                    cp2 = [e.clientX, e.clientY];
                }
                ctx.clearRect(0, 0, 500, 140);
                draw();
            }
            
            draw();

            function draw() {
                ctx.lineWidth = 3;
                ctx.strokeStyle = "black";                  
                ctx.beginPath();
                ctx.moveTo(startPoint[0], startPoint[1]);
                ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], 
                    endPoint[0], endPoint[1]);
                ctx.stroke();
    
                ctx.lineWidth = 1;
                ctx.strokeStyle = "red";            
                let points = [startPoint, endPoint, cp1, cp2];
                for (let i = 0; i < points.length; i++) {
                    drawPoint(points[i]);    
                }
                drawLine(startPoint, cp1);
                drawLine(endPoint, cp2);
            }

            function drawPoint(point) {
                ctx.beginPath();

                ctx.strokeRect(point[0] -2, point[1] -2, 4, 4);
            }
            
            function drawLine(from, to) {
                ctx.beginPath();
                ctx.moveTo(from[0], from[1]);
                ctx.lineTo(to[0], to[1]);
                ctx.stroke();
            }
        </script>
    </body>
</html>

Related Topic