How to draw a smiley face as shown below using html5 canvas.
Well, it's not as complicated as it looks. The picture includes below parts:
1. outer face circle
2. two circular eyes
3. one straight line nose
4. a smile arc
The above basic parts can be drawn using arc and moveTo methods of context object and it involves a little calculation as to where to place the sub parts so as to sync the whole face symmetrically.
Code:
I know the face looks a little out of place but you can do it better I know ;)
Click here for a demo.
Well, it's not as complicated as it looks. The picture includes below parts:
1. outer face circle
2. two circular eyes
3. one straight line nose
4. a smile arc
The above basic parts can be drawn using arc and moveTo methods of context object and it involves a little calculation as to where to place the sub parts so as to sync the whole face symmetrically.
Code:
<canvas id="smiley" width="800" height="600">
<script>
    drawSmiley();
    function drawSmiley() {
        var canvas = document.getElementById("smiley");
        var context = canvas.getContext("2d");
        // Draw outer face circle
        context.beginPath();
        context.arc(300, 300, 100, 0, degreesToRadians(360), true);
        context.fillStyle = "#ffffcc";
        context.fill();
        context.stroke();
        // Draw left eye circle
        context.beginPath();
        context.arc(250, 270, 15, 0, degreesToRadians(360), true);
        context.stroke();
        // Draw right eye circle
        context.beginPath();
        context.arc(350, 270, 15, 0, degreesToRadians(360), true);
        context.stroke();
        // Draw straight line nose
        context.beginPath();
        context.moveTo(300, 285);
        context.lineTo(300, 330);
        context.stroke();
        // Draw smile arc
        context.beginPath();
        context.arc(300, 330, 55, degreesToRadians(20), degreesToRadians(160), false);
        context.stroke();
    }
    function degreesToRadians(degrees) {
        return (degrees * Math.PI) / 180;
    }
</script>
I know the face looks a little out of place but you can do it better I know ;)
Click here for a demo.

Thank you so much for your post. This post really help me a lot and I have learnt some new things from your blog.
ReplyDeleteMobile Development
Glad to help, Victoria :)
Delete