13 May 2014

HTML5 JavaScript Canvas Examples

These are very simple examples of drawing on Javascript Canvas, which I'm focused on right now.

First example is drawing some text. Here is how it looks like:

  <script src="app1.js"></script> 
    <div style="width:450px; height:150px; 
            margin:0 auto; padding:3px;">
        <canvas   id="canvasArea" width="450" height="150" 
            style="border:1px solid black">

window.onload = function()
   canvas  = document.getElementById("canvasArea"); 
   context = canvas.getContext("2d");

   var mText = "Hello Earth! This is Flanture drawing Canvas ...";
   var xPos  = canvas.width/2;
   var yPos  = canvas.height/2;

   context.font         = "45pt Comic Sans MS"; 
   context.fillStyle    = "navy";
   context.textAlign    = "center"; 
   context.textBaseline = "middle";

   context.fillText(mText, xPos, yPos);                  

Another simple example would be drawing some rectangles on Canvas.

  <script src="app.js"></script> 
   <div style="width:450px; height:350px; 
            margin:0 auto; padding:3px;">
      <canvas   id="canvasArea" width="450" height="300" 
         style="border:1px solid black">
      <canvas   id="canvasArea2" width="450" height="50" 
         style="border:1px solid black">

window.onload = function()
   canvas  = document.getElementById("canvasArea"); 
   context = canvas.getContext("2d");

   var xPos = 30; var yPos = canvas.height/2-50;
   var width = 100; var height = 50;

   context.lineWidth = 10;
   context.strokeStyle = "lightgreen";
   context.strokeRect(xPos+130, yPos, width, height+100);

   context.fillStyle = "teal";
   context.fillRect(xPos, yPos, width, height+10);
   context.clearRect(xPos+10, yPos+10, width-30, height-10);

   context.fillStyle = "darkkhaki";
   context.fillRect(xPos+260, yPos, width, height);
   context.clearRect(xPos+285, yPos+10, width-50, height-20);

// now canvas number 2

   canvas2 = document.getElementById("canvasArea2");
   context2 = canvas2.getContext("2d");

   var m2Text = "drawing rectangles on canvas";
   var x2Pos = canvas2.width/2;
   var y2Pos = canvas2.height/2;

   context2.font         = "12pt Comic Sans MS"; 
   context2.fillStyle    = "navy";
   context2.textAlign    = "center"; 
   context2.textBaseline = "middle";

   context2.fillText(m2Text, x2Pos, y2Pos);      


As you can see Canvas number 2 is only for showing text, can be excluded.

Now, just to make things a little bit complicated, here is example for drawing random rectangles on Canvas. It is kinda simple generative art example. This one uses only one color, but you can randomize colors also and even include gradients, both linear and radial. For simple gradient colors creation check this link .

window.onload = function()
   canvas  = document.getElementById("canvasArea"); 
   context = canvas.getContext("2d");

   var i, xPos, yPos, width, height;
   for (i = 0; i < 20; i++) {

      xPos = Math.random()*canvas.width;
      yPos = Math.random()*canvas.height;
      width = 10+Math.random()*100;
      height = 10+Math.random()*100;

      context.fillStyle = "darkkhaki";
      context.fillRect(xPos, yPos, width, height);

File index.html is same as above. By refreshing your page you create new image every time. Nice.

Way back in July 2009 there was post AS3 Drawing API examples with some drawing API practice. Here are exactly the same six figures drawn on JavaScript Canvas.

window.onload = function()
   canvas  = document.getElementById("canvasArea"); 
   context = canvas.getContext("2d");

[to be continued]


04 May 2014

AS vs JS GCD - WTF!?

  AS -> ActionScript programming language
  JS -> JavaScript programming language
  vs -> versus
  GCD -> greatest common divisor
  WTF!? -> wtf

translation: Common stuff between ActionScript and JavaScript programming languages.

Both ActionScript and JavaScript are based on ECMA Script standard, so it's inevitably to have same language core. Syntax is almost the same, also object model and many classes like Array, Date, Math and String. Both languages implement same operators and dot syntax, so when you look at the code sometimes you will not be able to see the difference, because in some parts there aren't any.

Take a look at Drawing with JavaScript in HTML5 vs ActionScript 3 in Flash article by @WilliamMalone HTML5 Game developer from Denver, Colorado. Example will walk you through drawing of dynamic content (in this case it's a warning icon) in AS as well as in JS and every step has been done simultaneously which is perfect to notice differences and common things.

JavaScript / ActionScript drawing example

There are also things which are very similar and with similar function, but not the same. In ActionScript there are Local Share Objects and they look like other key-value based datastore, JavaScript "favorite cookies". Also event listeners and event handling is key on both sides if you considering game development and interactivity programming.
This is pretty much how to add new eventListener:

target.addEventListener('click', function() {
    /* actions */ 
}, false);

There are tons of predefined Events in AS and JS and you can create Custom Events if you want.

Browser window event types are: onclick, ondblclick, onmousedown, onmousemove, onmouseover, onmouseout, onmouseup, onkeydown, onkeypress... 

You will probably use canvas as target in your browser, in this way:
canvas.addEventListener("type", function, false);

in which case you use "type" area events like these: click, dblclick, focus, focusin, focusout, keydown, keypress, keyup, mousedown, mouseenter, mousemove, mouseover, mouseup, mousewheel, pause, scroll, touchstart, touchmove ...

Despite many differences between ActionScript and JavaScript there is huge greatest common divisor worth knowing and developers who use both languages can confirm this is great advantage in fast moving web development world.

[to be continued]


28 March 2014

Tennis Stats Flash Animation Without Ana Ivanovic

This is my latest. It's not quite finished yet. Tennis stats animation is suppose to be collection of fictional tennis match animation panels with different statistical information displayed in appropriate form. Some panels are actually static but most are animated. They are all more or less based on real-life examples and can be modified to receive and display real match data.

Tennis Stats Animation

There are four panels right now, ones you can see on image above. Will add more later. Instead of currently displayed text "tennis stats animation" first plan was to create woman tennis silhouette in "waiting for serve" pose and animate it. My model was off course Ana Ivanovic, the most beautiful tennis player ever and as you can guess my "Ana playing" folder with video files became very heavy right away, but I just can't choose which file to use :) I'm working on it.

Your thoughts about it and how to improve it? (I mean animation off course, you just can't improve Ana)


18 March 2014

Easy JavaScript Radial Menu

Very nice example by Creative Punch CSS3 and JavaScript radial menu. Little bit of math and smooth transition. 

Radial menu CSS3 + JavaScript

04 March 2014

Schedule Flash Application

First, I'll start with some simple code. I need two smaller helper functions. First one is clone function since I need to hard-copy entire arrays and this can't be done with built-in functions. Clone function uses ByteArray to hard-copy any array.

Another helper function is createArray which outputs Array with numbers 1 to limit. This is simpler version of application where I only have numbers representing group members. In real life example I'll probably have list of students in text file or something like that so my Array will contain these names. 

Idea is to create application which will split group members into random subgroups will given number of elements (students). This will save time for teachers and make group exercises more interesting because groups are chosen randomly every time.

Main schedule function is simple, I just take one by one element from starter Array created using createArray function, put it in new multidimensional array and exclude it from starting one. I do this until first array is not empty.

This code will work without mistake only if remainder of n / g is zero. If it's not zero, code needs to be modified so extra elements are put in already existing groups, but equally.

Next will be to add some nice graphics around it, maybe some kind of slot machine, anything that looks like group members are selected randomly.


20 February 2014

Introduction to elegant CoffeeScript

When I read new article by Paula Borowska my first thoughts were, is it possible that this stuff is so elegant and time-saving and why have I missed it. 

For those whose heart is more with Python than JavaScript, CoffeeScript is the right way to go. Programming language which compiles into JavaScript! You write code mucho faster than in JavaScript and you need less lines and less punctuation marks. Yes, braces are past, forget about them :)

Never thought JavaScript can be fun even when writing it, but it seems like CoffeeScript makes it possible. I will definitely take a look at it.


18 February 2014

Countdown Timer: JS + CSS

This is very effective 3D Countdown Timer made entirely with CSS and JavaScript. Code is nothing too much, there is just four states to it and a little bit of JavaScript awesomeness :)

More details on this page by Doug Avery 

CSS JavaScript 3D Countdown Timer

30 January 2014

Guess The Flag Flash Game

There are several types of educational Flash games which model often repeats. This kind of games are also very simple to create and when technique is mastered of how to make single game, it's very easy to expand and create countless number of similar games.

One type of this kind of games is drag-and-drop match game like this one, Guess The Flag.

Guess the flag

Game is simple. Drag and drop country names to match appropriate flags. Notice that in this variation European Union is not actually one country. Yet. Anyway, after placing every word, check button appears.

game displaying errors
If there are errors, check button turn into "try again" button which here just says "again" since Germany and Spain flags are not matched with names of countries they represent. One solution for this situation is for those words to go back to start position and player can try again. Appropriate message can be displayed and/or points awarded if everything is fine. 

This is simple game but can have virtually countless variations and can cover any topic kids have to learn about. Small changes and additions are always welcomed like different kind of awards, some custom sounds or several levels with various difficulty. 


17 January 2014

AS3 Removing All Event Listeners

We can say that in ActionScript 3 Event Listeners have cumulative effect. Lets demonstrate this feature.
Our world-wide famous "square" object is also involved in this story.
First, we have to import some kind of event.

import flash.events.MouseEvent;

Now, that's great! We have something to work with.

square.addEventListener(MouseEvent.CLICK, onClick);

function onClick(evt:MouseEvent):void
    evt.target.x += 10;
    // square.addEventListener(MouseEvent.CLICK, onClick2);

What happened here? If you test it, code will move our square 10 pixels to the right per click. Considering coordinate axes this is expected behavior. Next, lets uncomment that confusing line and add another function definition.

function onClick2(evt:MouseEvent):void
    evt.target.x -= 15;
    // square.removeEventListener(MouseEvent.CLICK, onClick);

Now result is that first our world-wide famous pal goes 10 pixels right and than 15 pixels left, which means both functions are executed. But if we uncomment removeEventListener line our pal goes only 15 pixels to the left.

There is no built-in way to remove all event listeners at once in ActionScript 3.0. There is a way to check if specific event listener is already attached. You can do this using hasEventListener on your object. Using some kind of loop if object has specific listener you can remove it. This solution has limitations.

If you are not using AS3 Signals maybe some help you can find in this post.



template by blogger templates