{"id":667,"date":"2017-09-27T13:00:36","date_gmt":"2017-09-27T12:00:36","guid":{"rendered":"http:\/\/chewett.co.uk\/blog\/?p=667"},"modified":"2018-04-30T01:02:21","modified_gmt":"2018-04-30T00:02:21","slug":"html5-canvas-drawing-tutorial-basic-shapes","status":"publish","type":"post","link":"https:\/\/chewett.co.uk\/blog\/667\/html5-canvas-drawing-tutorial-basic-shapes\/","title":{"rendered":"HTML5 Canvas Drawing Tutorial &#8211; Basic Shapes"},"content":{"rendered":"<p>This post is the first in a series of blog posts where I explore the HTML5 canvas. This first tutorial looks at creating the basic elements required to draw on a canvas and drawing some basic shapes.<\/p>\n<h2><!--more--><\/h2>\n<h2>Creating and styling the canvas<\/h2>\n<p>The first step to creating an HTML5 canvas animation is adding the canvas to a page. This is achieved by adding a <code>canvas<\/code>\u00a0element to the page. This can be placed like any other block type HTML element and styled similarly.<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">&amp;lt;style&amp;gt;\r\n    #canvasBorder {\r\n        border: dashed rgba(0, 0, 0, 0.4);\r\n        display: inline-block;\r\n    }\r\n&amp;lt;\/style&amp;gt;\r\n&amp;lt;div id=&quot;canvasBorder&quot;&amp;gt;\r\n    &amp;lt;canvas id=&quot;mainCanvas&quot; width=&quot;500&quot; height=&quot;500&quot;&amp;gt;&amp;lt;\/canvas&amp;gt;\r\n&amp;lt;\/div&amp;gt;<\/pre>\n<p>The above code adds the canvas element to the page and styles it and the body to make the page look a little more interesting. Here I assign an ID to the canvas element so that I can access it later with JavaScript. The width and height attributes have values in pixels.<\/p>\n<h2>Preparing to draw in the canvas<\/h2>\n<p>Now I have added the element to the page I can set up variables to access the canvas. Using the element ID above I can select the canvas with <code>document.getElementById<\/code>. Using this element selector I then get the canvas 2d context by calling\u00a0<code>getContext(\"2d\")<\/code>\u00a0on the canvas element. This drawing context is the basis of drawing onto my canvas element.<\/p>\n<pre>var canvas = document.getElementById(\"mainCanvas\");\r\nvar context = canvas.getContext(\"2d\");<\/pre>\n<p>Now I have the 2d context I am able to use a number of methods on the context to draw basic shapes.<\/p>\n<h2>Drawing basic shapes<\/h2>\n<p>Now we have the 2d context I can start drawing some basic shapes. The most basic shape is drawing a line between two points.<\/p>\n<h3>Drawing a Line<\/h3>\n<p>The basis of drawing a line using the 2d context is selecting two points which will then have a line drawn between them. This will use the x, y coordinates in pixels.<\/p>\n<pre>context.beginPath();\r\ncontext.moveTo(20,20);\r\ncontext.lineTo(100,50);\r\ncontext.stroke();<\/pre>\n<p>Using the <code>moveTo<\/code> and <code>lineTo<\/code> functions you can create a line joining to points. First you tell the context that you are starting to draw a path with a call to <code>beginPath<\/code>. Once this has been done you can either start drawing, or move the starting point. In this example I have used <code>moveTo<\/code> to start drawing at the coordinates 20, 20.<\/p>\n<p>To draw a line from the starting position you call <code>lineTo<\/code> which sets the path to the coordinate given in the function.<\/p>\n<p>Once the path has been created you can tell the context to draw the line by calling <code>stroke<\/code>. This will create the line along the given path. In this example from the coordinate given in <code>moveTo<\/code> to the coordinate given in <code>lineTo<\/code>.<\/p>\n<p>This basic example can be extended to make more complex paths by performing a series of calls to <code>lineTo<\/code> or any other functions to create the path. Once a path has been created calling stoke will create a line following the given path.<\/p>\n<h3>Drawing a Rectangle<\/h3>\n<p>Similarly you can draw a rectangle using similar methods. First again we call <code>beginPath<\/code> to initilize the path. Calling <code>rect<\/code>\u00a0on the context\u00a0will create a rectangle path starting at the x and y positions 50, 75 with the width and height of 120, 140.<\/p>\n<pre>context.beginPath();\r\ncontext.rect(50, 75, 120, 140);\r\ncontext.fillStyle = \"#FFCB1A\";\r\ncontext.fill();<\/pre>\n<p>Once the path has been created you can specify the fill style with the context property<code>fillStyle<\/code>. Once you have defined the fillstyle\u00a0<code>fill<\/code> can be called to fill in the path.<\/p>\n<pre>context.lineWidth = 1;\r\ncontext.strokeStyle = \"black\";\r\ncontext.stroke();<\/pre>\n<p>Instead of, or in addition to, filling the rectangle you could stroke it along the border. Above shows an example to define the colour and width of the border. This border is applied across the path as before so requires you to define the path using <code>rect()<\/code>.<\/p>\n<h3>Drawing text<\/h3>\n<p>Text can be drawn similarly to drawing a rectangle by using the<code>fillText<\/code> method.<\/p>\n<pre>context.fillStyle = \"black\";\r\ncontext.font = \"20px Arial\";\r\ncontext.fillText(\"Hello World!\", 25, 270);<\/pre>\n<p>The <code>fillStyle<\/code> and <code>font<\/code> can be set using their respective properties of the context object. Once you have set the colour and font style <code>fillText<\/code> can be called. This has three parameters, the text to enter, and the respective x and y position.<\/p>\n<h2>Drawing a Circle (or arc)<\/h2>\n<p>The final basic shape I will describe in this post is a circle. Again we start a path with <code>beginPath<\/code> and then use the <code>arc<\/code> command to create the path.<\/p>\n<pre>context.beginPath();\r\ncontext.arc(300, 100, 50, 0, 2*Math.PI);\r\ncontext.fillStyle = \"#CBFF1A\";\r\ncontext.fill();\r\n\/\/Fill its outline\r\ncontext.stroke();<\/pre>\n<p>Here <code>arc<\/code> has some more properties than the standard drawing functions. The first two parameters are the coordinates of the center of the arc. \u00a0The third parameter defines the radius of the arc and the final two parameters define the starting and stopping position of the arc. This is defined in radians so to draw a circle you set these to 0 and 2 * Pi.<\/p>\n<p>Again like the above functions once you have defined your path you can fill and stroke it as required.<\/p>\n<h2>HTML5 Canvas drawing Conclusion<\/h2>\n<p>With these simple methods you can create complex shapes using the 2d context. In the next blog post I will talk about animating your canvas.<\/p>\n<p>The example including the source code is <a href=\"http:\/\/chewett.co.uk.localonly\/html5_canvas\/basic_shapes_canvas_beginning\/\">available on my website<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This post is the first in a series of blog posts where I explore the HTML5 canvas. This first tutorial looks at creating the basic elements required to draw on a canvas and drawing some basic shapes.<\/p>\n","protected":false},"author":1,"featured_media":672,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_exactmetrics_skip_tracking":false,"_exactmetrics_sitenote_active":false,"_exactmetrics_sitenote_note":"","_exactmetrics_sitenote_category":0,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"jetpack_post_was_ever_published":false},"categories":[5],"tags":[154,155,72],"class_list":["post-667","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-informational","tag-html5","tag-html5-canvas","tag-javascript"],"wppr_data":{"cwp_meta_box_check":"No"},"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2017\/09\/html5_canvas_basic_shapes.jpg?fit=800%2C800&ssl=1","jetpack_shortlink":"https:\/\/wp.me\/p2toWX-aL","jetpack_sharing_enabled":true,"jetpack-related-posts":[{"id":1186,"url":"https:\/\/chewett.co.uk\/blog\/1186\/exploring-the-many-method-parameters-of-drawimage-with-html5-canvas\/","url_meta":{"origin":667,"position":0},"title":"Exploring the many method parameters of drawImage with HTML5 Canvas","author":"Chewett","date":"May 30, 2018","format":false,"excerpt":"In this post I look at the different method parameters that can be used with drawImage and what they are useful for. Whats the use for different parameters of drawImage The context drawImage function allows for creating more complex canvas scenes by allowing you to draw different images at various\u2026","rel":"","context":"In &quot;Informational&quot;","block_context":{"text":"Informational","link":"https:\/\/chewett.co.uk\/blog\/category\/informational\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/06\/drawImage_methods.jpg?fit=800%2C800&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/06\/drawImage_methods.jpg?fit=800%2C800&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/06\/drawImage_methods.jpg?fit=800%2C800&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/06\/drawImage_methods.jpg?fit=800%2C800&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":1130,"url":"https:\/\/chewett.co.uk\/blog\/1130\/new-html5-canvas-experiments-and-tutorials-section-of-my-website\/","url_meta":{"origin":667,"position":1},"title":"New HTML5 Canvas Experiments and tutorials section of my website","author":"Chewett","date":"April 21, 2018","format":false,"excerpt":"This post talks about the new HTML5 Canvas part of my website and what I plan to do with it. The new page on my website! I have added a link on the\u00a0homepage of my website\u00a0to the\u00a0new HTML5 canvas experiments and tutorials section. Here you will be able to view\u2026","rel":"","context":"In &quot;Informational&quot;","block_context":{"text":"Informational","link":"https:\/\/chewett.co.uk\/blog\/category\/informational\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/04\/new_html5_canvas_part_of_website.jpg?fit=800%2C800&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/04\/new_html5_canvas_part_of_website.jpg?fit=800%2C800&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/04\/new_html5_canvas_part_of_website.jpg?fit=800%2C800&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/04\/new_html5_canvas_part_of_website.jpg?fit=800%2C800&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":1144,"url":"https:\/\/chewett.co.uk\/blog\/1144\/creating-a-loading-progress-bar-animation-with-html5-canvas\/","url_meta":{"origin":667,"position":2},"title":"Creating a loading progress bar animation with HTML5 Canvas","author":"Chewett","date":"April 28, 2018","format":false,"excerpt":"In this HTML5 canvas example I create a simple loading progress bar demonstrating how you can use animation in a canvas. Creating an animation function Like all animation, the HTML5 canvas can create moving images by rapidly changing the image you are viewing. This is done by having a function\u2026","rel":"","context":"In &quot;Software&quot;","block_context":{"text":"Software","link":"https:\/\/chewett.co.uk\/blog\/category\/software\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/04\/loading_progress_bar_animation_html5.jpg?fit=800%2C800&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/04\/loading_progress_bar_animation_html5.jpg?fit=800%2C800&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/04\/loading_progress_bar_animation_html5.jpg?fit=800%2C800&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/04\/loading_progress_bar_animation_html5.jpg?fit=800%2C800&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":1177,"url":"https:\/\/chewett.co.uk\/blog\/1177\/scaling-sprites-for-pixel-art-with-html5-canvas\/","url_meta":{"origin":667,"position":3},"title":"Scaling Sprites for Pixel Art with HTML5 Canvas","author":"Chewett","date":"May 12, 2018","format":false,"excerpt":"In this blog post, I am showing a simple way of scaling sprites for Pixel Art\u00a0using the HTML5 canvas. Why we scale up sprites rather than rendering them higher quality When displaying pixel art it\u00a0is originally drawn pixel by pixel at a\u00a0very low resolution and then scaled up from original\u2026","rel":"","context":"In &quot;Software&quot;","block_context":{"text":"Software","link":"https:\/\/chewett.co.uk\/blog\/category\/software\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/05\/scaling_sprites-for_pixel_art.jpg?fit=800%2C800&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/05\/scaling_sprites-for_pixel_art.jpg?fit=800%2C800&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/05\/scaling_sprites-for_pixel_art.jpg?fit=800%2C800&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/05\/scaling_sprites-for_pixel_art.jpg?fit=800%2C800&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":1166,"url":"https:\/\/chewett.co.uk\/blog\/1166\/better-positioning-of-text-using-measuretext-with-html5-canvas\/","url_meta":{"origin":667,"position":4},"title":"Better positioning of text using measureText with HTML5 Canvas","author":"Chewett","date":"May 5, 2018","format":false,"excerpt":"In this tutorial I am extending the previous animation example by better positioning the text using measureText with the HTML5 canvas. The problem with positioning text When positioning\u00a0text you will sometimes want to know the width and height so that you can centre it on the canvas. However this isn't\u2026","rel":"","context":"In &quot;Software&quot;","block_context":{"text":"Software","link":"https:\/\/chewett.co.uk\/blog\/category\/software\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/05\/measure_text_html5_canvas.jpg?fit=800%2C800&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/05\/measure_text_html5_canvas.jpg?fit=800%2C800&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/05\/measure_text_html5_canvas.jpg?fit=800%2C800&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/05\/measure_text_html5_canvas.jpg?fit=800%2C800&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":1412,"url":"https:\/\/chewett.co.uk\/blog\/1412\/using-the-ds18b20-temperature-sensor-with-a-wemos-d1-mini-esp8266\/","url_meta":{"origin":667,"position":5},"title":"Using the DS18B20 Temperature Sensor with a WeMos D1 Mini (ESP8266)","author":"Chewett","date":"November 21, 2018","format":false,"excerpt":"In this blog post I talk about the additional steps needed to use the DS18B20 onewire temperature sensor with a WeMos D1 Mini (ESP8266) using the Arduino IDE. Important differences compared to using the DS18B20 on an Arduino There is one major difference to bear in mind when using the\u2026","rel":"","context":"In &quot;Electronics&quot;","block_context":{"text":"Electronics","link":"https:\/\/chewett.co.uk\/blog\/category\/electronics\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/11\/wd18b20_on_wemos_d1_mini.jpg?fit=800%2C800&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/11\/wd18b20_on_wemos_d1_mini.jpg?fit=800%2C800&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/11\/wd18b20_on_wemos_d1_mini.jpg?fit=800%2C800&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/chewett.co.uk\/blog\/wp-content\/uploads\/2018\/11\/wd18b20_on_wemos_d1_mini.jpg?fit=800%2C800&ssl=1&resize=700%2C400 2x"},"classes":[]}],"_links":{"self":[{"href":"https:\/\/chewett.co.uk\/blog\/wp-json\/wp\/v2\/posts\/667","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/chewett.co.uk\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/chewett.co.uk\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/chewett.co.uk\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/chewett.co.uk\/blog\/wp-json\/wp\/v2\/comments?post=667"}],"version-history":[{"count":7,"href":"https:\/\/chewett.co.uk\/blog\/wp-json\/wp\/v2\/posts\/667\/revisions"}],"predecessor-version":[{"id":1155,"href":"https:\/\/chewett.co.uk\/blog\/wp-json\/wp\/v2\/posts\/667\/revisions\/1155"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/chewett.co.uk\/blog\/wp-json\/wp\/v2\/media\/672"}],"wp:attachment":[{"href":"https:\/\/chewett.co.uk\/blog\/wp-json\/wp\/v2\/media?parent=667"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/chewett.co.uk\/blog\/wp-json\/wp\/v2\/categories?post=667"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/chewett.co.uk\/blog\/wp-json\/wp\/v2\/tags?post=667"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}