{"id":763,"date":"2012-10-05T16:47:39","date_gmt":"2012-10-05T16:47:39","guid":{"rendered":"http:\/\/a.parsons.edu\/~dejongo\/12-fall\/?p=763"},"modified":"2025-02-20T22:07:20","modified_gmt":"2025-02-20T22:07:20","slug":"12-canvas","status":"publish","type":"post","link":"https:\/\/b.parsons.edu\/~dejongo\/12-canvas\/","title":{"rendered":"12 Canvas"},"content":{"rendered":"<p><script type=\"text\/javascript\" src=\"http:\/\/b.parsons.edu\/~dejongo\/12-fall\/stuff\/draw.js\"><\/script><\/p>\n<p>The canvas element was originally developed by Apple for OSX as a way to encourage easy customization of dashboard widgets. It utilized Apple&#8217;s HTML rendering engine called webkit to create 2D graphics at around the same time as the WHATWG (Web Hypertext Application Technology Working Group) came together to create what would become HTML5. Apple, of course, played a central role in the creation of HTML5, and the technology was adopted by other the browser vendors. <\/p>\n<h2>What Is It?<\/h2>\n<\/p>\n<p>Canvas is a drawable region that uses Javascript drawing functions to create dynamically generated graphics. This is what other drawing programs do. Illustrator draws vectors using postscript to create pictures, Canvas uses javascript. A difference is that the vectors are always rasterized at screen resolution in canvas, meaning that they are turned into a bitmap.<\/p>\n<h2>How To Use the Canvas Element<\/h2>\n<\/p>\n<p>You first have to create the canvas element, and you do that in the body of the document: <\/p>\n<pre>&lt;canvas  id=\"canvas\" height=\"250\" width=\"300\">\r\n\t&lt;p>Use a browser that supports the canvas element\r\n&lt;\/canvas>\r\n<\/pre>\n<\/p>\n<p>The canvas element needs to be initialized in the Javascript, which appears between the <code> &lt;script type=\"application\/javascript\"><\/code> and <code>&lt;\/script><\/code> tags, and that is usually done in the head of the document:<\/p>\n<pre><script style=\"display: block;\" contenteditable=\"true\" type=\"text\/javascript\">\r\nfunction draw() {\r\n\tvar canvas = document.getElementById(\"canvas-1\");\r\n\tif (canvas.getContext) {\r\n\t\tvar ctx = canvas.getContext(\"2d\");\r\n\t}\r\n}\r\n<\/script>\r\n<\/pre>\n<\/p>\n<p>The actual instructions are written right after the canvas element has been initialized. The following examples show the instructions that draw a square and a circle.<\/p>\n<h2>Square<\/h2>\n<\/p>\n<p>You draw on the canvas by coding the exacting steps the computer requires to draw these shapes. There is only one shape it supports natively, and that is a square. All other shapes have to be drawn path by path. Luckily, there are drawing functions that make it possible to create complex shapes.\n<\/p>\n<p>If we take a red square as an example, you first specify the fill style and then fill the rectangle based on the given coordinates. Click the draw button and you will see this red square appear in the canvas window. If you change the values, the square will change.<\/p>\n<section id=\"editor\">\n<div class=\"handson_demo\">\n<h3>Javascript Code View<\/h3>\n<pre id=\"console\" contenteditable onkeyup=\"drawIt()\">\r\n\r\n\r\nvar canvas=document.getElementById('theCanvas');\r\nvar context=canvas.getContext('2d');\r\n\r\n\/\/code for the square\r\ncontext.fillStyle = \"rgb(255,0,0)\";\r\ncontext.fillRect(50, 50, 50, 50);\r\n\r\n<\/pre>\n<\/div>\n<\/section>\n<div id=\"canvasConsole\" style=\"border: 1px solid silver; margin: 0 auto;\">\n   <canvas id=\"theCanvas\" style=\"height:250px; \n \twidth:500px;\"><\/p>\n<p>Use a browser that supports the canvas element\n   <\/p>\n<p><\/canvas>\n <\/div>\n<form method=\"get\">\n   <input id=\"doDraw\" type=\"button\" onclick=\"drawIt()\" value=\"Draw It!\"\/><br \/>\n   <input id=\"doClear\" type=\"button\" onclick=\"clearIt()\" value=\"Clear It!\"\/><br \/>\n<\/form>\n<h2>Paths<\/h2>\n<\/p>\n<p>Paths require a few more steps. You have open and close a path using the following code: <code> beginPath() <\/code>, and <code>closePath()<\/code>, though the shape automatically closes when you <code>stroke()<\/code> or <code>fill()<\/code> the path. In that case, the closing of the path can be skipped. There are path methods that draw lines, arcs, bezier and quadratic curves.\n<\/p>\n<p>The following circle has all of its steps annotated, so show exactly how many steps it takes to create a red circle with a white fill that has a shadow, the letter P and a stroke to create a no parking sign. Copy the code and replace the code for the square in the Javascript Code View, click Draw It if you haven&#8217;t already done so, and you can play with the code, add to it, subtract, to see how it works. If you get excited, I have included many more definitions below that you can use to draw simple shapes.<\/p>\n<pre>\r\ncontext.beginPath(); \/\/Begin drawing path\r\ncontext.strokeStyle=\"#f00\"; \/\/ sets stroke color\r\ncontext.fillStyle=\"#fff\"; \/\/sets fill color\r\ncontext.arc(175,120,100,0,Math.PI*2, true); \/\/ draws circle\r\ncontext.lineWidth=40; \/\/ sets width of stroke\r\ncontext.shadowOffsetX=\"3\" \/\/ adds shadow offset x\r\ncontext.shadowOffsetY=\"3\" \/\/ adds shadow offset y\r\ncontext.shadowBlur=\"7\" \/\/ adds shadow blur\r\ncontext.shadowColor=\"#888\"\/\/ sets shadow color\r\ncontext.stroke(); \/\/ draws stroked circle\r\n\r\n\/\/remove shadow from inside of circle\r\ncontext.shadowOffsetX=\"0\" \/\/ removes offset x\r\ncontext.shadowOffsetY=\"0\" \/\/ removes offset y\r\ncontext.shadowBlur=\"0\" \/\/ removes blur\r\ncontext.fill(); \/\/ draws fill\r\ncontext.closePath; \/\/ closes path\r\n\r\ncontext.beginPath();  \/\/ draws P\r\ncontext.lineWidth=15; \/\/ width of line\r\ncontext.strokeStyle=\"#000\"; \/\/ color of stroke\r\ncontext.fillStyle=\"#000\"; \/\/ color of fill\r\ncontext.font=\"9em sans-serif\"; \/\/ size of font\r\ncontext.strokeText(\"P\",120,190); \/\/ text stroke\r\ncontext.fillText(\"P\",120,190); \/\/ text fill\r\ncontext.closePath; \/\/  but closes path\r\n\r\ncontext.beginPath();   \/\/ draws Slash\r\ncontext.strokeStyle=\"#f00\"; \/\/ sets stroke color\r\ncontext.moveTo(100,50); \/\/ begin vector\r\ncontext.lineTo(240,210); \/\/ end vector\r\ncontext.lineWidth=25; \/\/ width of line\r\ncontext.stroke(); \/\/ draw stroke\r\ncontext.closePath; \/\/ not necessary but closes path\r\n<\/pre>\n<style>\n#definitions {\nwidth: 600px; \nheight: 250px; \noverflow: auto; \nborder-bottom: 3px solid silver;\nborder-top: 3px solid silver;\npadding: 10px 0;}\n#definitions > p{\nfont-size: 80%;\nmargin: 0;\n#definitions > h3{\nfont-size: 80%;\nmargin: 5px 0 2px;}\n<\/style>\n<h2>Definitions:<\/h2>\n<\/p>\n<p>You can copy these definitions and paste them into the editor to create a shape. Check out the example shapes to see what definitions are required.<\/p>\n<section id=\"definitions\">\n<code><\/p>\n<h3>Styles<\/h3>\n<p>set the fillStyle<br \/>\ncontext.fillStyle=\"color\"\n<\/p>\n<p>set the strokeStyle<br \/>\ncontext.strokeStyle=\"color\"\n<\/p>\n<p>line widths<br \/>\ncontext.lineWidth=number\n<\/p>\n<p>line join styles<br \/>\ncontext.lineJoin=\"style\" (bevel, round, miter)\n<\/p>\n<p>line end styles<br \/>\ncontext.lineCap=\"style\" (butt, round, square)<\/p>\n<h3>Rectangles<\/h3>\n<\/p>\n<p>draw a rectangle<br \/>\ncontext.strokeRect(left, top, width, height)\n<\/p>\n<p>fill a rectangle<br \/>\ncontext.fillRect(left, top, width, height)\n<\/p>\n<p>erase a rectangle<br \/>\ncontext.clearRect(left, top, width, height)<\/p>\n<h3>paths<\/h3>\n<\/p>\n<p>begin a path<br \/>\ncontext.beginPath\n<\/p>\n<p>complete a path<br \/>\ncontext.closePath\n<\/p>\n<p>move the pen to a location<br \/>\ncontext.moveTo(horizontal, vertical)\n<\/p>\n<p>draw a straight line from current pen location to a new location<br \/>\ncontext.lineTo(horizontal, vertical)\n<\/p>\n<p>stroke the current path<br \/>\ncontext.Stroke()\n<\/p>\n<p>fill the current path<br \/>\ncontext.fill()<\/p>\n<h3>Text<\/h3>\n<\/p>\n<p>set the font<br \/>\ncontext.font=\"bold italic size font-family\"\n<\/p>\n<p>set the alignment<br \/>\ncontext.textAlign=\"left right center\"\n<\/p>\n<p>fill some text<br \/>\ncontext.fillText(\"string to fill\", top, left)\n<\/p>\n<p>stroke some text<br \/>\ncontext.strokeText(\"string to stroke\", top, left)<\/p>\n<h3>Shadows<\/h3>\n<\/p>\n<p>shadow color<br \/>\ncontext.shadowColor=\"color\"\n<\/p>\n<p>shadow horizontal offset<br \/>\ncontext.shadowOffsetX=number\n<\/p>\n<p>shadow vertical offset<br \/>\ncontext.shadowOffsetY=number\n<\/p>\n<p>shadow blur<br \/>\ncontext.shadowBlur=number\n<\/p>\n<p>taken from <a href=\"http:\/\/www.westciv.com\/\">Westciv<\/a>\n<\/p>\n<p><\/code><\/section>\n<h2>Simple Shapes<\/h2>\n<\/p>\n<p>More code examples to paste into the Javascript Code View.<\/p>\n<h3>Smily Face<\/h3>\n<pre>\r\ncontext.beginPath();\r\ncontext.arc(75,75,50,0,Math.PI*2,true); \/\/ Outer circle\r\ncontext.moveTo(110,75);\r\ncontext.arc(75,75,35,0,Math.PI,false);  \/\/ Mouth (clockwise)\r\ncontext.moveTo(65,65);\r\ncontext.arc(60,65,5,0,Math.PI*2,true);  \/\/ Left eye\r\ncontext.moveTo(95,65);\r\ncontext.arc(90,65,5,0,Math.PI*2,true);  \/\/ Right eye\r\ncontext.stroke();\r\n<\/pre>\n<h3>Caution Sign<\/h3>\n<pre>\r\ncontext.beginPath();   \/\/ Triangle\r\ncontext.strokeStyle=\"#000\";\r\ncontext.fillStyle=\"#ff0\";\r\ncontext.moveTo(70,20);\r\ncontext.lineTo(137,120);\r\ncontext.lineTo(3,120);\r\ncontext.lineTo(70,20);\r\ncontext.lineWidth=3;\r\ncontext.stroke();\r\ncontext.fill();\r\ncontext.closePath;\r\n\r\ncontext.beginPath();   \/\/ !\r\ncontext.fillStyle=\"#000\";\r\ncontext.font=\"5em sans-serif\";\r\ncontext.fillText(\"!\", 58,108);\r\ncontext.closePath;\r\n<\/pre>\n<h2>Play Time<\/h2>\n<p><img decoding=\"async\" style=\"float: right; margin: 0 0 10px 10px;\" src=\"http:\/\/b.parsons.edu\/~dejongo\/12-fall\/stuff\/11_canvas_example.jpg\"\/>\n<\/p>\n<p>See if you can draw this figure using the shapes similar to the ones already drawn in the demo, or draw your own shapes<a href=\"http:\/\/b.parsons.edu\/~dejongo\/12-fall\/stuff\/11_canvas_example.html\">.<\/a> You can copy and paste the definitions, just make sure you initiate the object, give it properties, draw it and then create it, and if this seems laborious, be glad you are not a computer, who does nothing but this type of routines.\n<\/p>\n<p>Better yet, watch someone else <a href=\"http:\/\/studio.sketchpad.cc\/sp\/pad\/view\/ro.9KPxftbkKN$2Z\/latest?&#038;soundcloud_url=http:\/\/soundcloud.com\/aribadernatal\/sketchcast_1342117029538\">create a canvas <\/a> based on <a href=\"http:\/\/processingjs.org\">processing<\/a>, a sister visual programing language developed to teach visually oriented people programming, right before your eyes, using <a href=\"http:\/\/popcornjs.org\/\">popcorn<\/a>.<\/p>\n<h2>Turn Postscript Into Javascript<\/h2>\n<\/p>\n<p>Drawing these primitive shapes by hand is really only for the purpose of understanding how canvas works.  In its raw form it will never be a drawing tool for design students.\n<\/p>\n<p>But that can change if someone were to write drawing software that could be translated to the canvas element. This is exactly what <a href=\"http:\/\/blogs.msdn.com\/b\/mswanson\/archive\/2010\/10\/12\/adobe-illustrator-to-html5-canvas-plug-in-released.aspx\">Mike Swanson<\/a> has done. He created an <a href=\"http:\/\/visitmix.com\/labs\/ai2canvas\/\">Adobe Illustrator to HTML5 Canvas<\/a> plugin. [Unfortunately, the plugin has not been updated, and it did not load the last time I tried it with Illustrator CC. Still, this is a good learning opportunity for you to understand how canvas works, and it is better to use <a href=\"12-scalable-vector-graphics-svg\/\"> SVG Graphics<\/a> and insert the vector art straight into the code.]\n<\/p>\n<p>This is an Illustrator plug-in that transforms Illustrator art into canvas art, allowing you use Illustrator as a front end to draw with, and the plugin will render it into Javascript code equivalent that can be rendered in the canvas element. Check out the <a href=\"http:\/\/b.parsons.edu\/~dejongo\/12-fall\/stuff\/Yellowstone_Map.html\">Yellowstone Map<\/a> as an example, and if you go to the website, you will see that the plugin is able to create motion graphics as well. We do not have the ability to install Illustrator plug-ins in the school&#8217;s computers but please try this on your computer, as Illustrator is a very good front end to drawing directly on the canvas. If you follow his tutorial, you can even animate!<\/p>\n<h2>Illustrator<\/h2>\n<\/p>\n<p>So here is an example of Illustrator art I created turned into Javascript. It takes only 5700 lines of code! To put that into perspective, the <a href=\"http:\/\/b.parsons.edu\/~dejongo\/12-fall\/stuff\/11_CircleOfLife_Folder\/11_CircleOfLife.ai\">Illustrator file<\/a> requires about the same number of lines using postscript to create the picture. <a href=\"http:\/\/b.parsons.edu\/~dejongo\/12-fall\/stuff\/11_CircleOfLife_Folder\/11_CircleOfLife.txt\">Here<\/a> is a text version of the Illustrator file, and the <a href=\"http:\/\/b.parsons.edu\/~dejongo\/12-fall\/stuff\/11_CircleOfLife_Folder\/11_CircleOfLifeHTML-CSS.txt\">html source<\/a> so you can see that there are an equal number of instructions.<br \/>\n<iframe loading=\"lazy\"  style=\"padding-top: 30px\" src=\"http:\/\/b.parsons.edu\/~dejongo\/12-fall\/stuff\/11_CircleOfLife.html\" width=\"580\" height=\"581\" scrolling=\"no\"><\/iframe><\/p>\n<h2>Wrap Up<\/h2>\n<\/p>\n<p>Advanced examples using the canvas element from the web:<\/p>\n<ul>\n<li><a href=\"http:\/\/en.inforapid.org\/\">Information map<\/a> to visualize information.\n<\/li>\n<li><a href=\"http:\/\/canvasrider.com\/\">Games<\/a>, since Javascript controls the drawing code, why not have it be a game.\n<\/li>\n<li>A <a href=\"http:\/\/mugtug.com\/sketchpad\/\">painting application<\/a>.\n<\/li>\n<\/ul>\n<h2>Make Your Own Game<\/h2>\n<\/p>\n<p>Canvas is made for creating games. It turns graphic assets into bitmaps ready for use. If you already know some JavaScript, and would like to explore making games, then the next links are for you.\n<\/p>\n<p>Step by step <a href=\"http:\/\/www.lostdecadegames.com\/how-to-make-a-simple-html5-canvas-game\/\">explanation <\/a>of how to create your own game using javascript and canvas.<br \/>\n<iframe loading=\"lazy\"  style=\"padding-top: 30px\" src=\"http:\/\/www.lostdecadegames.com\/demos\/simple_canvas_game\/\" width=\"512\" height=\"480\" scrolling=\"no\"><\/iframe><\/p>\n<p><iframe loading=\"lazy\" width=\"560\" height=\"315\" src=\"https:\/\/www.youtube.com\/embed\/c-1dBd1_G8A?si=uP5Ji2e06WPowWKT\" title=\"YouTube video player\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The canvas element was originally developed by Apple for OSX as a way to encourage easy customization of dashboard widgets. It utilized Apple&#8217;s HTML rendering engine called webkit to create 2D graphics at around the same time as the WHATWG &hellip; <a href=\"https:\/\/b.parsons.edu\/~dejongo\/12-canvas\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[16],"tags":[],"_links":{"self":[{"href":"https:\/\/b.parsons.edu\/~dejongo\/wp-json\/wp\/v2\/posts\/763"}],"collection":[{"href":"https:\/\/b.parsons.edu\/~dejongo\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/b.parsons.edu\/~dejongo\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/b.parsons.edu\/~dejongo\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/b.parsons.edu\/~dejongo\/wp-json\/wp\/v2\/comments?post=763"}],"version-history":[{"count":19,"href":"https:\/\/b.parsons.edu\/~dejongo\/wp-json\/wp\/v2\/posts\/763\/revisions"}],"predecessor-version":[{"id":6440,"href":"https:\/\/b.parsons.edu\/~dejongo\/wp-json\/wp\/v2\/posts\/763\/revisions\/6440"}],"wp:attachment":[{"href":"https:\/\/b.parsons.edu\/~dejongo\/wp-json\/wp\/v2\/media?parent=763"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/b.parsons.edu\/~dejongo\/wp-json\/wp\/v2\/categories?post=763"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/b.parsons.edu\/~dejongo\/wp-json\/wp\/v2\/tags?post=763"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}