HTML5 Game - Canvas Shape Heart

Creating custom draw heart shape

The following code uses bezierCurveTo() method to draw custom shape.

Demo

ResultView the demo in separate window

<html>
    <head>
        <script>
            function draw(context, x, y, width, height){
                context.save();//from w ww . j  a  v  a2s .  c  o m
                context.beginPath();
                let topCurveHeight = height * 0.3;
                context.moveTo(x, y + topCurveHeight);
                // top left curve
                context.bezierCurveTo(x, y, 
                                      x - width / 2, y, 
                                      x - width / 2, y + topCurveHeight
                 );
                
                // bottom left curve
                context.bezierCurveTo(x - width / 2, y + (height + topCurveHeight) / 2, 
                                      x, y + (height + topCurveHeight) / 2, 
                                      x, y + height
                 );
                
                // bottom right curve
                context.bezierCurveTo(x, y + (height + topCurveHeight) / 2, 
                                      x + width / 2, y + (height + topCurveHeight) / 2, 
                                      x + width / 2, y + topCurveHeight
                 );
                
                // top right curve
                context.bezierCurveTo(x + width / 2, y, 
                                      x, y, 
                                      x, y + topCurveHeight
                 );
                
                context.closePath();
                context.fillStyle = "red";
                context.fill();
                context.restore();

            }
            
            window.onload = function(){
                let canvas = document.getElementById("myCanvas");
                let context = canvas.getContext("2d");
        
                draw(context, canvas.width * 0.2, 70, 75, 100);
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Related Topics