HTML Canvas Bezier curve draw flower

Description

HTML Canvas Bezier curve draw flower

View in separate window

<html>
    <head>
        <script>
            // define Flower constructor
            function Flower(context, centerX, centerY, radius, numPetals, color){
                this.context = context;/*  ww  w  .  j a v  a 2  s .  c  o m*/
                this.centerX = centerX;
                this.centerY = centerY;
                this.radius = radius;
                this.numPetals = numPetals;
                this.color = color;
            }
            
            // Define Flower draw method
            Flower.prototype.draw = function(){
                var context = this.context;
                context.beginPath();
                
                // draw petals
                for (var n = 0; n < this.numPetals; n++) {
                    var theta1 = ((Math.PI * 2) / this.numPetals) * (n + 1);
                    var theta2 = ((Math.PI * 2) / this.numPetals) * (n);
                    
                    var x1 = (this.radius * Math.sin(theta1)) + this.centerX;
                    var y1 = (this.radius * Math.cos(theta1)) + this.centerY;
                    var x2 = (this.radius * Math.sin(theta2)) + this.centerX;
                    var y2 = (this.radius * Math.cos(theta2)) + this.centerY;
                    
                    context.moveTo(this.centerX, this.centerY);
                    context.bezierCurveTo(x1, y1, x2, y2, this.centerX, this.centerY);
                }
                
                context.closePath();
                context.fillStyle = this.color;
                context.fill();
                
                // draw yellow center
                context.beginPath();
                context.arc(this.centerX, this.centerY, this.radius / 5, 0, 2 * Math.PI, false);
                context.fillStyle = "yellow";
                context.fill();
            };
            
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
                
                // define an array of colors
                var colorArray = [];
                colorArray.push("red"); // 0
                colorArray.push("orange"); // 1
                colorArray.push("blue"); // 2
                colorArray.push("purple"); // 3

                var centerX = 120;
                var centerY = 200;
                var radius = 50;
                var colorIndex = Math.round(Math.random() * (colorArray.length - 1));
                    
                var thisFlower = new Flower(context, centerX, centerY, radius, 5, colorArray[colorIndex]);
                thisFlower.draw();

            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>



PreviousNext

Related