2010
11-16

Canvas – no more Flash

We all know Flash and Java. If you write webpage with it and if your users install it, then they can watch animation elements on your web page. But today I was playing with something new called "Canvas". It's included in HTML5, so you don't need to install anything except web borwser to make it work. It have graphic card support, so it work fast. Here is my example that I wrote:
Your web browser don't supprot HTML5 Canvas
And here is code for that example (wibout blog code):
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <script type="application/javascript">
  3.  
  4. var atime= 0;
  5. var canvas;
  6. var ctx;
  7. var screen_width= 512;
  8. var screen_height= 384;
  9. var background;
  10.  
  11. var ballsList_num= 3;
  12. var ballsList= [];
  13.  
  14. var flys_num= 100;
  15. var flys= [];
  16.  
  17. /// function runed after page is loaded
  18. /// load data
  19. function init(){
  20. canvas= document.getElementById("canvas");
  21. canvas.width= screen_width;
  22. canvas.height= screen_height;
  23. ctx= canvas.getContext("2d");
  24. for(var a=0;a<ballsList_num;a++)
  25. ballsList[a]= new Ball(a);
  26.  
  27. for(var a=0;a<flys_num;a++)
  28. flys[a]= new Fly(a);
  29.  
  30. //background= document.images[0];
  31. background= document.getElementById('background');
  32.  
  33. setInterval( draw, 10);
  34. }
  35.  
  36. function drawClock( ){
  37. var cr= 50
  38. ctx.save();
  39. ctx.translate(screen_width-75,75);
  40. var now= new Date();
  41. var sec = now.getSeconds() + (now.getMilliseconds()/1000);
  42. var min = now.getMinutes();
  43. var hr = now.getHours();
  44. hr = hr>=12 ? hr-12 : hr;
  45. //ctx.fillRect(cx-cr,cy-cr,cx+cr,cy+cr);
  46. ctx.lineCap= "round";
  47.  
  48. /// draw background
  49. ctx.save();
  50. ctx.beginPath();
  51. ctx.arc(0,0,cr,0,Math.PI*2,true);
  52. ctx.closePath();
  53. ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
  54. ctx.fill();
  55. ctx.lineWidth= 10;
  56. ctx.strokeStyle = "#FFFF00";
  57. ctx.stroke();
  58. ctx.restore();
  59.  
  60. /// draw hours background
  61. for( var h=0; h<12; h++){
  62. ctx.save();
  63. ctx.beginPath();
  64. ctx.rotate( h*Math.PI/6 );
  65. ctx.moveTo(0,-cr*0.7);
  66. ctx.lineTo(0,-cr*0.85);
  67. ctx.lineWidth= 5;
  68. ctx.strokeStyle = "#404040";
  69. ctx.stroke();
  70. ctx.restore();
  71. }
  72.  
  73. /// triangle with moving one vertex
  74. ctx.fillStyle = "rgba(0, 100, 0, 1.0)";
  75. ctx.fillStyle = "#FFFFFF";
  76. ctx.beginPath();
  77. ctx.moveTo(-cr, 1.15*cr);
  78. ctx.lineTo(cr, 1.15*cr);
  79. ctx.lineTo(-cr+cr*(1+Math.sin(atime/50)), 3*cr);
  80. ctx.closePath();
  81. ctx.fill();
  82. ctx.stroke();
  83.  
  84. /// draw hours
  85. ctx.save();
  86. ctx.rotate( hr*(Math.PI/6) + min*(Math.PI/(2*12*60)) + sec*(Math.PI/21600) );
  87. ctx.beginPath();
  88. ctx.moveTo(0,0);
  89. ctx.lineTo(0,-cr*2/4);
  90. ctx.lineWidth= 4;
  91. ctx.stroke();
  92. ctx.restore();
  93.  
  94. /// draw minutes
  95. ctx.save();
  96. ctx.rotate( min*(Math.PI/30) + sec*(Math.PI/(2*12*60)) );
  97. ctx.beginPath();
  98. ctx.moveTo(0,0);
  99. ctx.lineTo(0,-cr*4/6);
  100. ctx.lineWidth= 3;
  101. ctx.stroke();
  102. ctx.restore();
  103.  
  104. /// draw seconds
  105. ctx.save();
  106. ctx.rotate( sec*(Math.PI/30) );
  107. ctx.beginPath();
  108. ctx.moveTo(0,10);
  109. ctx.lineTo(0,-cr*5/6);
  110. ctx.lineWidth= 1;
  111. ctx.stroke();
  112. ctx.restore();
  113.  
  114. ctx.restore();
  115. }
  116.  
  117. /// constructor of Ball class
  118. function Ball(_id){
  119. this.id= _id;
  120. this.r= 10*(2+this.id);
  121. this.x= Math.random()*screen_width;
  122. this.y= Math.random()*screen_height;
  123. this.xmin= this.r/2;
  124. this.xmax= screen_width-this.r/2;
  125. this.ymin= this.r/2;
  126. this.ymax= screen_height-this.r/2;
  127. this.speed= 1/20;
  128. this.xu= this.speed;
  129. this.yu= this.speed;
  130. switch(this.id){
  131. case 0:{
  132. this.fillStyle="rgba( 0, 255, 255, 1.0)";
  133. }break;
  134. case 1:{
  135. this.fillStyle="rgba(255, 0, 255, 1.0)";
  136. }break;
  137. default:{
  138. this.fillStyle="rgba(255, 255, 0, 1.0)";
  139. }break;
  140. }
  141. this.update= function(utime){
  142. if( this.x < this.xmin )
  143. this.xu= this.speed;
  144. if( this.xmax < this.x )
  145. this.xu= -this.speed;
  146. if( this.y < this.ymin )
  147. this.yu= this.speed;
  148. if( this.ymax < this.y )
  149. this.yu= -this.speed;
  150. this.x+= this.xu * utime;
  151. this.y+= this.yu * utime;
  152. return;
  153. }
  154. this.draw= function(){
  155. ctx.save();
  156. ctx.beginPath();
  157. ctx.arc(this.x,this.y,this.r/2,0,Math.PI*2,true);
  158. ctx.closePath();
  159. ctx.lineWidth= 1;
  160. ctx.fillStyle = this.fillStyle;
  161. ctx.fill();
  162. ctx.restore();
  163. return;
  164. }
  165. }
  166.  
  167.  
  168. /// constructor of Fly class
  169. function Fly(id){
  170. this.id= id;
  171. this.x= screen_width/2;
  172. this.y= screen_height/2;
  173. this.update= function(utime){
  174. var step= 0.5;
  175. switch( Math.floor ( Math.random ( ) * 4 ) ){
  176. case 0:{
  177. this.x+=step;
  178. }break;
  179. case 1:{
  180. this.x-=step;
  181. }break;
  182. case 2:{
  183. this.y+=step;
  184. }break;
  185. case 3:{
  186. this.y-=step;
  187. }break;
  188. }
  189. return;
  190. }
  191. this.draw= function(){
  192. ctx.save();
  193. ctx.beginPath();
  194. ctx.arc(this.x,this.y,1.5,0,Math.PI*2,true);
  195. ctx.closePath();
  196. ctx.lineWidth= 1;
  197. ctx.fillStyle = "rgba(255, 255, 255, 1.0)";
  198. ctx.fill();
  199. ctx.restore();
  200. return;
  201. }
  202.  
  203. }
  204.  
  205. /// main function of all application
  206. function draw(){
  207. var utime= 30;
  208. if (canvas.getContext) {
  209. //glPush
  210. ctx.save();
  211. //glClear
  212. ctx.clearRect(0,0,screen_width,screen_height);
  213. //ctx.fillRect(0,0,screen_width,screen_height);
  214.  
  215. ///background
  216. //ctx.drawImage(background,0,0);
  217. ctx.drawImage(background,0,0,screen_width, screen_height);
  218.  
  219. /// two rectangles
  220. ctx.fillStyle = "rgb(200,0,0)";
  221. ctx.fillRect (10, 10, 55, 50);
  222. ctx.fillStyle = "rgba(0, 200, 0, 0.5)";
  223. ctx.fillRect (30, 30, 55, 50);
  224.  
  225. /// draw flys
  226. for( var a=0; a<flys_num; a++){
  227. flys[a].update(utime);
  228. flys[a].draw();
  229. }
  230.  
  231. /// draw balls
  232. for( var a=0; a<ballsList_num; a++){
  233. ballsList[a].update(utime);
  234. ballsList[a].draw();
  235. }
  236.  
  237. /// draw clock
  238. drawClock();
  239.  
  240. atime++;
  241. //glPop
  242. ctx.restore();
  243. }
  244. }
  245. </script>
  246. </head>
  247. <body onload="init();" style="color:#FFF; background-color:#000;">
  248. <!-- canvas screen -->
  249. <canvas id="canvas">Your web browser don't supprot HTML5 Canvas</canvas>
  250. <!-- images that we will use in our canvas application -->
  251. <img src="background.png" id="background" style="display:none;" />
  252. </body>
  253. </html>
  254.  
I wonder why Canvas isn't so popular as Flash and Java. Probably because WebGL. WebGL is new version of Canvas with 3D support, but it not published jet. But most people involved in that type of graphic prefare to work with testing WebGL rather than Canvas. It's just my hypothesis.

40 Coments.

  1. Thank you for sharing I wish I could go somwhere.

  2. In it something is also to me it seems it is excellent idea. I agree with you.

  3. blancpain says:

    Very useful message

  4. breguet says:

    This phrase, is matchless, it is pleasant to me

  5. Breitling says:

    In my opinion you commit an error. I can prove it.

  6. tattoo says:

    Number will not pass!

  7. bell ross says:

    On mine it is very interesting theme. I suggest all to take part in discussion more actively.

  8. I can consult you on this question and was specially registered to participate in discussion.

  9. It agree, rather amusing opinion

  10. It is simply excellent phrase

  11. Actually. Prompt, where I can find more information on this question?

  12. bet365 says:

    hello!This was a really brilliant Topics!
    I come from milan, I was luck to approach your subject in wordpress
    Also I learn a lot in your website really thank your very much i will come every day

  13. bet365 says:

    how are you!This was a really outstanding post!
    I come from itlay, I was fortunate to look for your blog in wordpress
    Also I learn a lot in your Topics really thank your very much i will come again

    • Kelsey says:

      wow. Quiet long stretches of beach are my idea of haeven! What a tremendous blessing to have a wonderful place like this to visit every year. Hmmm, I’d have to say that for me, a trip to India a couple of years ago was pretty magical. So much to see and experience, it definitely made a mark on me that’s going to last a lifetime.

  14. Completely I share your opinion. In it something is also idea excellent, agree with you.

  15. Yes, really. It was and with me. We can communicate on this theme.

  16. bet365 says:

    Good day!This was a really excellent blog!
    I come from roma, I was luck to come cross your topic in wordpress
    Also I obtain much in your website really thank your very much i will come later

  17. I can not recollect, where I about it read.

  18. emt training says:

    Beneficial info and excellent design you got here! I want to thank you for sharing your ideas and putting the time into the stuff you publish! Great work!

  19. Looks like you are an expert in this field, you really got some great points there, thanks.

    – Robson

  20. Superb blog post, I have book marked this internet site so ideally I’ll see much more on this subject in the foreseeable future!

  21. Hey there this is a fantastic post. I’m going to e-mail this to my pals. I came on this while exploring on aol I’ll be sure to come back. thanks for sharing.

  22. sex says:

    Seriously like your sites information! Definitely a wonderful deal of data which is very helpful. Proceed to retain publishing and i am likely to proceed reading via! Cheers.

  23. Zetaliedlit says:

    Agreeable, they press in compensation to be taught that filing lawsuits is not the be in to ode specious piracy. Fairly than, it’s to draft something muster than piracy. Like affluence of use. It’s sinker a straws easier to utter iTunes than to search the Internet with possibly of malware and then crappy idiosyncratic, but if people are expected to avail in burst up again loads and interruption against ages, it’s not flourishing to work. They in no way record of a sorry on sooner anterior to people design software and Network sites that vocal suffer with an influence it ridiculously amenable to crib, and up the quality. If that happens, then there intending purposes be no stopping piracy. But they’re too on the ball and apprehensive of losing. Risks suffer with to be bewitched!

    great wall of china tours

  24. Terrific work! This is the type of information that should be shared around the web. Shame on the search engines for not positioning this post higher!

    • Susan says:

      I had a rather hard time cnisoohg just one type of physician I would want to work for. So many of them fascinate me, and with me not really going into any medical field other than support, I never gave this any thought in the past. After reading the list, I am more favorable of working for a neonatologist. It is difficult to think about how neonatologist physicians sometimes have the most difficult job in the world, but I can only imagine how amazing it would be to be a part of saving a baby’s life. I had a coworker once whose baby was born at 36 weeks, and her baby had a lot of heart and lung problems. There were concerns about whether or not they would ever fully develop once she had him, but after many months in the NICU, and many scares that happened during it, the doctors were able to save him and he is now a very healthy 5 year old. It is because of that I have a higher interest in the neonatologist field.I hate to say which type of physician I would care less to work for, and it is because I worry that many will take it the wrong way. When I was 16, I used to help my mom at an assisted living home as a caregiver. We would get to work at 7:00 A.M. every morning to prepare breakfast for four of the elderly men and women that we were caring for. We would then make sure that all bedding was changed, rooms were cleaned, meals were prepared, and appointments were handled. We worked 12 hour days, and they were always grueling. The owner of the home made sure that everyone had their medicine and made it to their doctor appointments on time. However, she was more worried about getting paid for her services than actually helping the elderly. She would yell at them if they did something wrong, and even call them terrible names. My mom reported her and we both quit our job, but it has always left a sting in my heart since then. It is because of my experience with that situation that I do not think I could ever work for a gerontologist. I know that the situations would be much different, but ever since my experience with caring for elderly individuals it is very hard for me to think about assisting a physician in geriatrics because I worry that someone else might treat the elderly in the same way the owner of the home did. I am a firm believer that the elderly deserve the ultimate care and comfort when going through any treatment and aging in general, but I do not think I could ever work in that environment again.

  25. admin says:

    I wonder how much of that comments are spam bot comments.
    But right now I’m not going to delete any comments to don’t delete any real human comment. I install antispam plugin so no more spam comments will apear here.
    If you are real human and can not comment here, please email me.

  26. Lnape says:

    Can i hyperlink up to the following, by way of this webpage? I am likely to gain as much causes of suggestions as i am have the ability.

  27. admin says:

    You can put link to my webpage where ever you want.

  28. LovelyH says:

    Nice animation.
    I like fact that it don’t require installation of flash or java or any think like that.

  29. ShaneSab says:

    На сайтах с низкой конкуренцией можно показать за пару часов и поправить за неделю.

    Проблемы которые сейчас я предлагаю разрешить:

    -Проинспектировать как работает с сайтом ваш сегодняшнийспециалист и проверить текующую ситуацию по SEO?
    -Найду просчеты сделанные ранее и построю проект по внесению правок.
    -Продемонстрирую как осуществлять контроль деятельность своего SEO эксперта.

    Намереваетесь нанять SEO мастера?

    -Помогу провести собеседование потенциальногоSEO специалиста. Разберу по каким стандартам оценивать его уровень.
    – Опишем различия между нанятым в штат SEO, делегированном SEO и раскрутке своими силами.

    Собираетесь сами продвинуть существующий веб-сайт. Расскажу все насчет продвижения, после консультации вам станет ясно:

    -Сколько будет стоить ваш сайт
    -Сколько по времени требуется будет его продвигать для того чтобы добиться топов
    -Из каких именно ступеней состоит само по себе продвижение, обобщенно проанализируем каждый из них.
    -Проанализируем в связи с чем не нужно пользоваться услугами компаний, оказывающих список услуг по SEO

    Хотите создать интернет-сайт и начать его продвижение?

    -Расскажу и далее покажу как создать наиболее экономный и хороший вариант web-сайта.
    -В какой степени большим или сложным может быть ваш интернет-сайт для того чтобы соперничать в топе.
    -Сколько вкладывают ваши конкуренты в продвижение.
    -До какой степени реально войти в топы с вашим вебсайтом и с вашим бюджетом.

    Есть желание узнать окупится ли консультирование?

    Звоните по телефону или в скайп – я дам ответ на все темы касающиеся SEO и предполагаемого вебсайта.

    Абсолютно любые вопросы – сделайте звонок +7(921)9114848 или по скайпу admin1.ru
    Часовая беседа по стоимости 3тыс рублей, имеется возможность подписание соглашения и оплата на расчетный счет.
    Оказываю бесплатные консультации за отзыв (таким образом у основной массы интернет-сайтов проблему видно практически сразу)

    acol7wns24

Leave a Reply

  ( Ctrl+Enter )