ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Internet & the Web

HTML5 Canvas - Creating a smiley face with the ARC API

Updated on June 13, 2012

In this article, I will share my experiment with HTML 5 canvas ARC API which I have been playing with to build basic compositions with circles and arcs.

First of all, to use the ARC API, you will need to have a very basic understanding of PI.

PI

In mathematics, PI is defined as a transendental number, that is the ratio of the circumference of a circle to its diameter. PI has an approximate value of 3.141 592 and is usually defined by this symbol π.

In HTML5 Canvas, PI is defined as MATH.PI

Read more about PI here

In mathematics, 2*PI will complete the full diameter of a circle. So if we divide a circle into 4 segments each segement will be equivalent to 0.5*PI

See the image below to visualise this

Starting your HTML 5 document

To begin with our HTML 5 experiment, first of all create a file called arc.html to whatever name you prefer in your project folder.

You will also need to include a jquery file somewhere in your project and call the jquery in your html document.

You can download the latest copy of jquery here

<!DOCTYPE html>
<html>
<head>
<title>Learning the basics of canvas</title>
<meta charset="utf-8">

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">
$(document).ready(function() { 
   // arc api code will go here to create the shapes
});
</script>
</head>

<body>
<p>Canvas Experiment</p>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #EEE">
  <!-- // Fallback text -- >
  <p>Browser does not support canvas</p>
</canvas>
</body>
</html>

Ok from the code you will see its pretty much basic stuff. I have added the <head> section with a call to the jquery file and within the body i have added a DIV with id myCanvas which will where the shapes will be displayed.

The code itself for creating the shapes will sit inside $(document).ready() in the head of the html document.

So now lets look at creating our first shape.

I will start by creating the smiley face outline with a basic yellow circle.

$(document).ready(function() { 
   var canvas = $("#myCanvas");
   var context = canvas.get(0).getContext("2d");
    
   context.strokeStyle = '#0000FF';
   context.fillStyle = '#FFFF00';
   context.lineWidth = 4;
   context.beginPath();
   context.arc(100,75,50,0*Math.PI,2*Math.PI,true);
   context.closePath();
   context.stroke();
   context.fill();
});

First we tell jquery which DIV to target to render the drawing. In this case we are setting the canvas as myCanvas DIV in the body. Then we set the context as 2D as this will be a 2D drawing.

Read more about html5 2D context here

Our circle shape has a few properties like, outline (stroke) colour, fill colour, radius and center co ordinates. We define these settings to construct the circle as explained below:

context.strokeStyle

This sets the stroke or outline colour of the circle. I have set it to Blue.

context.fillStyle

This is used to define the fill colour of the circle. In this case we have used the hexadecimal code for yellow.

context.lineWidth

This defines the stroke or outline border thickness.

context.beginPath

This is a method that clears any current drawing path to begin a path for a new drawing shape. This is used especially when we are building a composition with multiple objects. The script will need to know where a drawing stops and the next one begins

context.arc(100,75,50,0*MATH.PI,2*MATH.PI,true);

Now this is the core of the API which define the circle drawing itself.

The API is described below

context.arc(X,Y,Radius,beginAngle,endAngle,counterClockwise);

X is the X Coordinate of the circle centre point from the left edge of your canvas block. ao 100 will be 100px horizontal from the left border of the canvas block.

Y is the Y Coordinate of the circle centre point form the top edge of your canvas block. So 75 will be 75px vertical from the top border of the canvas block.

Radius is self explanatory. Radius of a circle is the distance from any point on the diameter to the centre of the circle.

beginAngle is where the drawing of the circle begins. In out case we are starting at 0*MATH.PI which is illustrated by the red box on the diagram above.

endAngle is where the drawing of the circle will stop. In our case we are doing a full circle so that will be 2*MATH.PI which means our drawing will end on the red. If we were to draw a half circle, we will begin on RED and end on Yellow which is 1*MATH.PI

counterClockwise

By default this value is FALSE, which means the drawing will be following a clockwise path, so bsically starting from RED going through BLUE then YELLOW, BROWN and back to RED. counterClockwise TRUE will start from RED to BROWN to YELLOW to BLUE and back to RED again.

closePath

This is used to make sure the shape is closed. On the full circle drawing this is not obvious, but if we were to draw half a circle then you can see the use of this method. Say for example i wanted to draw a half circle starting from RED to YELLOW Clockwise. If i dont use the closePath method you will only see the arc extending from RED to YELLOW clockwise. If i use the closePath method you will see the arc from RED to YELLOW plus a line connecting YELLOW to RED to fill the half circle.

Finally we apply the stoke and fill method which have properties defined at the beginning. The result will be the outline of the face that is a yellow circle with a Blue border.

Next we will create the arc that makes the smile. So your code should look like this:

$(document).ready(function() { 
   var canvas = $("#myCanvas");
   var context = canvas.get(0).getContext("2d");
    
   // The face
   context.strokeStyle = '#0000FF';
   context.fillStyle = '#FFFF00';
   context.lineWidth = 4;
   context.beginPath();
   context.arc(100,75,50,0*Math.PI,2*Math.PI,true);
   context.closePath();
   context.stroke();
   context.fill();

   // The smile
   context.strokeStyle = '#FF0000';
   context.lineWidth = 2;
   context.beginPath();
   context.arc(100,65,40,0.2*Math.PI,0.8*Math.PI,false);
   //context.closePath(); 
   context.stroke();
   //context.fill();
});

Note in the smile section i have not used the closePath method. It has been commented out as we only need to display the arc.

Also note the 0.2*MATH.PI and 0.8*MATH.PI angles where the start and finish are defined.

The fill method is also not required here as there is no shape to fill. The arc is a part of a circle and the circle is defined to start at 100px left and 65 pixels from top. with a smaller radius of 40 px as the arc will need to sit inside the circle and therefore a smaller radius is required.

Now the drawing should look like this:

Finally we add the eyes to finish off the drawing. The eyes will be a simple task of adding to fill circles with smaller radius and at defined centre points on the circle.

So the code should now look like this:

$(document).ready(function() { 
	var canvas = $("#myCanvas");
	var context = canvas.get(0).getContext("2d");

	// The Face
	context.strokeStyle = '#0000FF';
	context.fillStyle = '#FFFF00';
	context.lineWidth = 4;
	context.beginPath();
	context.arc(100,75,50,0*Math.PI,2*Math.PI,true);
	context.closePath();
	context.stroke();
	context.fill();


	// The Smile
	context.strokeStyle = '#FF0000';
	context.lineWidth = 2;
	context.beginPath();
	context.arc(100,65,40,0.2*Math.PI,0.8*Math.PI,false);
	//context.closePath(); 
	context.stroke();
        //context.fill();

	// The Left eye
	context.strokeStyle = '#000000';
	context.fillStyle = '#000000';
	context.beginPath();
	context.arc(80,60,10,0*Math.PI,2*Math.PI,false);
	context.closePath();
	context.stroke();
	context.fill();

	// The Right Eye
	context.strokeStyle = '#000000';
	context.fillStyle = '#000000';
	context.beginPath();
	context.arc(120,60,10,0*Math.PI,2*Math.PI,false);
	context.closePath();
	context.stroke();
	context.fill();

});

Now save your file and open in your browser to see the end result looking like this:

Comments

    0 of 8192 characters used
    Post Comment

    • smga22 profile image

      smga22 5 years ago from Dhaka, Bangladesh

      Thanks for sharing your experience here in hubpages, this will be very helpful for me. Voted up!

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)