{"id":2355,"date":"2011-10-09T19:16:13","date_gmt":"2011-10-10T00:16:13","guid":{"rendered":"http:\/\/www.lonhosford.com\/lonblog\/?p=2355"},"modified":"2015-07-31T18:25:49","modified_gmt":"2015-07-31T23:25:49","slug":"html5-canvas-circular-rotation-animation","status":"publish","type":"post","link":"https:\/\/www.lonhosford.com\/lonblog\/2011\/10\/09\/html5-canvas-circular-rotation-animation\/","title":{"rendered":"HTML5 Canvas Circular Rotation Animation Example"},"content":{"rendered":"<p>Started dabbling with the HTML5 canvas to create animations.  This example animates a filled circle rotating around the center point. <img loading=\"lazy\" decoding=\"async\" alt=\"\" src=\"https:\/\/lh3.googleusercontent.com\/-D0GmtVkl664\/TpIsHRo7uEI\/AAAAAAAAGJM\/N1sMmjSRBug\/s288\/Html5CanvasCircularMovement.jpg\" class=\"alignleft\" width=\"288\" height=\"288\" \/> I kept the example as simple as possible while anticipating some of the coding design required for a more complex build.<\/p>\n<p>A build on this example that accepts user keyboard input to control the animation play, start, stop, direction and speed is available in this <a href = \"https:\/\/www.lonhosford.com\/lonblog\/2011\/10\/10\/html5-canvas-circular-rotation-animation-using-jquery-hotkeys-for-user-interaction\/\">follow up post<\/a>.<figure style=\"width: 100px\" class=\"wp-caption alignright\"><a href=\"http:\/\/www.amazon.com\/gp\/product\/1430236655\/ref=as_li_ss_il?ie=UTF8&#038;tag=hosfordusa&#038;linkCode=as2&#038;camp=217145&#038;creative=399373&#038;creativeASIN=1430236655\"><img decoding=\"async\" border=\"0\" src=\"http:\/\/ws.assoc-amazon.com\/widgets\/q?_encoding=UTF8&#038;Format=_SL110_&#038;ASIN=1430236655&#038;MarketPlace=US&#038;ID=AsinImage&#038;WS=1&#038;tag=hosfordusa&#038;ServiceVersion=20070822\" ><\/a><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/www.assoc-amazon.com\/e\/ir?t=hosfordusa&#038;l=as2&#038;o=1&#038;a=1430236655&#038;camp=217145&#038;creative=399373\" width=\"1\" height=\"1\" border=\"0\" alt=\"\" style=\"border:none !important; margin:0px !important;\" \/><a href=\"http:\/\/www.amazon.com\/gp\/product\/1430236655\/ref=as_li_ss_tl?ie=UTF8&#038;tag=hosfordusa&#038;linkCode=as2&#038;camp=217145&#038;creative=399373&#038;creativeASIN=1430236655\">Foundation HTML5 Animation with JavaScript<\/a><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/www.assoc-amazon.com\/e\/ir?t=hosfordusa&#038;l=as2&#038;o=1&#038;a=1430236655&#038;camp=217145&#038;creative=399373\" width=\"1\" height=\"1\" border=\"0\" alt=\"\" style=\"border:none !important; margin:0px !important;\" \/><br \/>\n<figcaption class=\"wp-caption-text\">Learn More<\/figcaption><\/figure><\/p>\n<p>One item that is more sophisticated is that the canvas tag is dynamically created in the Javascript code on lines 35 &#8211; 40. This is not necessary as the tag could be inserted into the html and referenced with an id. <\/p>\n<p>Another is including JQuery from the Google CDN. Listening to the body onLoad method is a substitute. <\/p>\n<p>Also I included the script tag after the html content. The script tag could go in the head section. Placing after the html in the body tag allows html content to load and style before the script code is parsed.<\/p>\n<p><strong><a  href=\"\/content\/html5\/canvas\/circular_movement_ex01\/circular_movement.html\" target = \"_blank\">Demo<\/a><\/strong><\/p>\n<p><strong><a onclick=\"javascript: pageTracker._trackPageview('\/downloads\/html5\/canvas\/circular_movement_ex01.zip'); \" href=\"https:\/\/www.lonhosford.com\/content\/html5\/canvas\/circular_movement_ex01.zip\">Source<\/a><\/strong><\/p>\n<p>This is the html5 head section. There is an internal style on lines 8 &#8211; 17 for the html in the document. Line 4 brings in JQuery from the Google CDN. Line 20 is the display title for the page.<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\n&lt;!DOCTYPE HTML&gt;\r\n&lt;html&gt;\r\n&lt;head&gt;\r\n&lt;script language=&quot;javascript&quot; src=&quot;https:\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/1.6.4\/jquery.min.js&quot; type=&quot;text\/javascript&quot;&gt;&lt;\/script&gt;\r\n&lt;title&gt;HTML5 Canvas Circular Movement Based Animation&lt;\/title&gt;\r\n&lt;meta charset=&quot;UTF-8&quot;&gt;\r\n&lt;title&gt;Untitled Document&lt;\/title&gt;\r\n&lt;style type=&quot;text\/css&quot;&gt;\r\n\tbody {\r\n\t\tfont-family:Arial, Helvetica, sans-serif;\r\n\t\tfont-size:12px;\r\n\t}\r\n\t#titleDiv{\r\n\t\tfont-family:Verdana, Geneva, sans-serif;\r\n\t\tfont-size:16px;\r\n\t}\r\n&lt;\/style&gt;\r\n&lt;\/head&gt;\r\n&lt;body&gt;\r\n&lt;div id=&quot;titleDiv&quot;&gt;HTML5 Canvas Circular Movement Based Animation&lt;\/div&gt;\r\n&lt;script type='text\/javascript'&gt;\r\n<\/pre>\n<p>The animation key variables are definite and initialized here to keep as many bare numbers out of the code as possible. <\/p>\n<p>The canvas has a border. So there is some computational needs on lines 26-27 to take the border out in computing the center point. May not make a difference in this example, but is helpful for a future example where that boundary is important.<\/p>\n<pre class=\"brush: jscript; first-line: 22; title: ; notranslate\" title=\"\">\r\n\tvar CANVAS_WIDTH = 480;\t\t\/\/ Canvas width\r\n\tvar CANVAS_HEIGHT = 480;\t\/\/ Canvas height\r\n\tvar FPS = 30;\t\t\t\t\/\/ Frames per second\r\n\t\/\/ Canvas center points adjusting for stroke.\r\n\tvar canvasCenterX = (CANVAS_WIDTH - 1) \/ 2;\r\n\tvar canvasCenterY = (CANVAS_HEIGHT - 1) \/ 2;\r\n\t\/\/ Radius of the rotation\r\n\tvar radius = 200;\r\n\t\/\/ Speed of movement\r\n\tvar speed = .05;\r\n\t\/\/ Angle for computing cosine and sin.\r\n\tvar angle = 0;\r\n\t\/\/ Create a canvas element variable.\r\n\tvar canvasElement = $(&quot;&lt;canvas width='&quot; + CANVAS_WIDTH + \r\n\t  &quot;' height='&quot; + CANVAS_HEIGHT + &quot;'&gt;&lt;\/canvas&quot;);\r\n\t\/\/ Reference to the canvas 2d context.\r\n\tvar canvas = canvasElement.get(0).getContext(&quot;2d&quot;);\r\n\t\/\/ Dynamically append a canvas element to the body tag.\r\n\tcanvasElement.appendTo('body');\r\n<\/pre>\n<p>[ad name=&#8221;Google Adsense&#8221;]<br \/>\nThis defines the object that moves in the circular rotation. The name player is arbitrary but hints at a way to define objects for a game. <\/p>\n<p>Later we will see the animation loop. The animation loop call the draw function of the items in the animation. So you see the draw function for the player on line 49. This is how to draw a filled circle with a border using the html5 canvas api. <\/p>\n<p>Additionally each object has an init function that is called to initialize the animation objects. For this example the init function for the player object is empty. It could be used for an initial placement of an object for example.<\/p>\n<p>Line 59 shows the master init function that would call all necessary component init functions.<\/p>\n<pre class=\"brush: jscript; first-line: 41; title: ; notranslate\" title=\"\">\r\n\t\r\n\t\/\/ Object defining the player we are rotating.\r\n\tvar player = {\r\n\t\tcolor: &quot;#00A&quot;,\r\n\t\tx: 0,  \t\/\/ Starting x\r\n\t\ty: 0,\t\/\/ Starting y\r\n\t\twidth: 32,\r\n\t\theight: 32,\r\n\t\tradius: 20,\r\n\t\tdraw: function() \/\/ Draw the player.\r\n\t\t{\r\n\t\t\tcanvas.fillStyle = this.color;\t\t\r\n\t\t\tcanvas.beginPath();  \r\n\t\t\tcanvas.arc(this.x,this.y,this.radius,0,Math.PI*2,true); \r\n\t\t\tcanvas.fill();\r\n\t\t\tcanvas.lineWidth = 5;\r\n    \t\t        canvas.strokeStyle = &quot;black&quot;;\r\n    \t\t        canvas.stroke();\r\n\t  \t},\r\n\t\tinit: function()\r\n\t\t{\r\n\t\t}\r\n\t};\t\r\n\t\/\/ Initialize game\r\n\tfunction init()\r\n\t{\r\n\t\tplayer.init();\r\n\t}\r\n<\/pre>\n<p>[ad name=&#8221;Google Adsense&#8221;]<br \/>\nThe update function updates the model data. The animation timer will call this for each animation interval. <\/p>\n<p>Primarily the computations are a right triangle from the center point to the place for the player object to be drawn based on the current angle. This is the x and y where the leg and hypotenuse are based on the angle.<\/p>\n<pre class=\"brush: jscript; first-line: 68; title: ; notranslate\" title=\"\">\r\n\t\/\/ Update the model data.\r\n\tfunction update() \r\n\t{  \r\n\t\t\/\/ Compute the triangle coordinates from the center of rotation\r\n\t\tplayer.x = canvasCenterX + Math.cos(angle) * radius;\r\n\t\tplayer.y = canvasCenterY + Math.sin(angle) * radius;\r\n\t\t\/\/ Keep moving the rotation. Use -= for reverse rotation.\r\n\t\tangle += speed;\r\n\t}\r\n\r\n<\/pre>\n<p>This is the view being drawn. It draws anything that has to do with the overall canvas. However you could make that a class or object like player and give it a draw method. <\/p>\n<p>Line 85 shows the player draw method being called.<\/p>\n<pre class=\"brush: jscript; first-line: 77; title: ; notranslate\" title=\"\">\r\n\t\/\/ Draw the views\r\n\tfunction draw() \r\n\t{\r\n\t\tcanvas.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);\r\n\t\tcanvas.strokeStyle = &quot;red&quot;;\r\n\t\tcanvas.strokeRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);\r\n\t\tcanvas.fillStyle = &quot;#ccc&quot;;\r\n\t\tcanvas.fillRect(.5, .5, CANVAS_WIDTH-1, CANVAS_HEIGHT-1);\r\n\t\tplayer.draw();\r\n\t}\r\n<\/pre>\n<p>[ad name=&#8221;Google Adsense&#8221;]<br \/>\nThis is the start of the script and the heart of the animation. Once JQuery is ready the animation init function is called. Next a Javascript interval is started to call the animation update method to update the data and then the animation draw method to redraw the view.<\/p>\n<pre class=\"brush: jscript; first-line: 87; title: ; notranslate\" title=\"\">\r\n\t\/\/ JQuery ready\r\n\t$(function() \r\n\t{\r\n\t\t\/\/ Start here.\r\n\t\tinit();\r\n\t\t\/\/ Timer for animation.\r\n\t\tsetInterval(function() \r\n\t\t{\r\n\t\t\tupdate();\r\n\t\t\tdraw();\r\n\t\t}, 1000\/FPS);\r\n\t\t\t\r\n\t});\r\n\r\n<\/pre>\n<pre class=\"brush: xml; first-line: 100; title: ; notranslate\" title=\"\">\r\n&lt;\/script&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;\r\n\r\n<\/pre>\n<div id=\"fb-root\"><\/div>\n<p><script src=\"https:\/\/connect.facebook.net\/en_US\/all.js#appId=105467682877384&amp;xfbml=1\"><\/script><fb:like href=\"https:\/\/www.lonhosford.com\/lonblog\/2011\/10\/09\/html5-canvas-circular-rotation-animation\/\" send=\"true\" width=\"450\" show_faces=\"true\" font=\"\"><\/fb:like><\/p>\n<div id=\"fb-root\"><\/div>\n<p><script src=\"https:\/\/connect.facebook.net\/en_US\/all.js#xfbml=1\"><\/script><fb:comments href=\"https:\/\/www.lonhosford.com\/lonblog\/2011\/10\/09\/html5-canvas-circular-rotation-animation\/\" num_posts=\"2\" width=\"500\"><\/fb:comments><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Started dabbling with the HTML5 canvas to create animations. This example animates a filled circle rotating around the center point. I kept the example as simple as possible while anticipating some of the coding design required for a more complex build. A build on this example that accepts user keyboard input to control the animation [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5],"tags":[74,75,76],"class_list":["post-2355","post","type-post","status-publish","format-standard","hentry","category-general","tag-html","tag-html5-2","tag-html5-canvas"],"_links":{"self":[{"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/posts\/2355","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/comments?post=2355"}],"version-history":[{"count":34,"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/posts\/2355\/revisions"}],"predecessor-version":[{"id":3671,"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/posts\/2355\/revisions\/3671"}],"wp:attachment":[{"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/media?parent=2355"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/categories?post=2355"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/tags?post=2355"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}