CSS3 – Animating the DOM – Part 1

So recently my focus has moved visibly from native mobile development to web based development, this is mainly due to the constrain of work. As I try to keep my blog up to date it only makes sense that I transition the blog to this area too. No doubt I will be back to mobile soon but for now it’s web stuff and today its CSS3.

So recently I wanted to animate some elements of my web application to add a little more interaction to the application. Traditionally animation has been saved for flash websites and flex RIAs. As HTML5 gains steam so will the users expectations of web experiences so we must adapt to create intelligent and engaging applications and using animations can really give an application the feeling that its a living thing and not just a static page.

CSS 3 Basics

We will start with the basics as always and hopefully build up to some more advance techniques in future posts, However you may find that these basic effects can achieve exactly what you need.


If you aren’t familiar with transitions then this brief introduction may help. Transitions basically define the start and end of your animation i.e Moving an object from A -> B should take x amount of seconds. You need transitions to make the movement that appears on screen appear seamless and smooth otherwise you will get a stickato movement that looks horrible.

transition: all 1s ease-in-out;

The above CSS follows this format

You can declare each of the above transition properties in its own CSS rule:

transition-property: background-color,width,height;
transition-duration: 2s, 1s, 0.5s;
transition-delay: 0s, 0.5s, 1s;

So this will animate background-color for a duration of 2 seconds and delay of 0s, width for a duration of 1 seconds with a delay of 0.5.

Using the above method you can achieve effects like this

Css3 Transition Opacity on Hover
Css3 Transition Opacity on Hover

You can transition many properties on elements such as color/background/height/ width and so much more you can also combine these to make nice effects too. The above shows how you can use transitions to fade out an image using the Opacity css property.

.div {
transition:all 3s ease;

.div:hover {

Have a play around with transitions for now and see what effects you can create with using these basic transitions alone, In the next post we will look at more advance transitions and start to take a look at adding transformations on top too.


Responsive Web Development

I have been struggling recently to find anytime to work on any pet projects due to work commitments. As you may have picked up from previous blog posts my first choice framework for web apps is usually bootstrap, Bootstrap is a framework for rapidly prototyping web applications created by the Twitter team. Over the last year or so Bootstrap has grown in popularity and many sites can be easily recognisable by the default theme.

Twitter Bootstrap Default
Twitter Bootstrap Default

Recently I wanted to try out the responsive functionality of Bootstrap, as expected it is easy and quick to create a simple application that can be scaled across devices without any great need to write any additional CSS media queries. By chance I came across Foundation by Zurb, a framework similar to bootstrap in many respects but maybe for more experienced developers, it also has a great range of templates and mobile specific responsive functionality built in. I decided to take a look and at first I wasn’t so keen but the framework forces you to create more custom elements rather than reusing the standard to death so in practice you will usually end up with a unique looking application. Features like off canvas elements and mobile CSS classes make creating mobile web experiences much easier in Foundation.

Foundation by Zurb Template
Foundation by Zurb Template

I hope to get back to doing some more work on my Dart projects soon but due to work I have been focusing on more traditional technologies. Hope to try update this blog a lot more often this year starting …. Now.

Its been a while

It’s been a while since wrote any posts as the Christmas period was very busy and work has continued to act as a roadblock to any free time I may get. However today I had some time and had a realisation that March is on its way already and I have done little work on any of my projects. Q1 is a write off so time to switch attention to rest of the year, so here goes Q1 recap.

    GitHub Game Off 2012

My Last post Dart Canvas I wrote about using Canvas with Google Dart in November this was all in preparation for the GitHub Game-Off, I ultimately ran out of time and couldn’t complete my small platform game. As this was my first game development experience it was a good challenge. Picture of the small game can be found below still very basic. I have to say however I really enjoyed Dart for the development work, It just feels easy and natural to pick up coming from a Java background.

    Android Projects

I did start work on an Android project that I would really like to finish by summer this year all going well. Details of the project still underwraps no its not top secret I just dont know much about it myself. Its a fun app though I think…

    JellyBam Custom Roms

During the first start of the year I had some issues with my Galaxy S3, occasional lock ups forcing a battery removal to return to normal was begin to get more and more common. I took this as an opportunity to try out a custom rom for my device. After looking through a few I liked the UI configuration of Paranoid and the stability of Cyanogen. Jellybam was recommended by a colleague who had installed it on his S2 and combined features from other roms that I had liked. So far I have had a few issues but the stability is better takes sometime for the developer to get the release “Stable” but all in all its been a good experience.

Just a quick update I hope to be writing at least monthly again soon as I start my projects for this year, and learn about all those new features in Dart over the last few months.


Dart Canvas

I entered the Github GameOff at the start of the month and forgot all about it, The GameOff is a hackathon for the month of November that requires participants to create web based game. Seeing as I would like to learn some of the principles of game design I thought I would proceed anyway in my spare time with my entry. Since I have been experimenting with Dart I decided that it would be a good place to start.


GitHub GameOff 2012 – Theres still time !

The Basics 

I have never used canvas in anger and decided this would be my start point for my Game/Application (of which I still have no idea what it will be). There are a lot of tutorials available for canvas and HTML5, however most of them will be in Javascript they can be easily ported to DART. Check out the Mozilla Developer Network for some really good tutorials. I like to write about the work Iv done on my blog especially when its new to me, as I find it helps secure the new concepts by writing about them and also hope to share my experiences.

Getting Started 


Ok. So your ready to start and you have created a new DART project. Open the .html page and add a canvas element to the document (see example)

<canvas id='canvas' width='450' height='450'> </canvas>

You can add a fallback element below incase the browser of the user doesn’t support canvas. However this should be bare minimum to run in chromium.


Open the DART file. I created a new class for my application called Game. Feel free to name your class whatever you wish

It is important to understand the two main elements we will be working with.

CanvasElement – This is the element in which all the drawing data will be rendered. This correlates to the element you specified in your html.

CanvasRenderingContext2D Р Implementation of CanvasRenderingContext this is the class that will allow you to draw the shapes onto the #canvas surface.

Declare both of these variables at the top of your class like so

CanvasElement canvas;
CanvasRenderingContext2D ctx;
int WIDTH;

Now its time to set these, you can do this in the initialisation of your class, However I put this logic in an init() method

canvas = document.query('#canvas');
ctx = canvas.getContext('2d');
WIDTH = canvas.width;
HEIGHT = canvas.height;
player = new Player(ctx);

The observant will notice that the code above calls request redraw this will be vital in maintaining an animation loop later in the tutorial. The only logic in this method for a basic implementation will be


In this call to requestAnimationFrame you pass in the method that you wish to use to draw your scene. In my example this is called simply draw. For now create an empty method

void draw(num _){
//Logic will be added later

You now have the canvas element and drawing context for your app available for use. Lets start drawing.

Drawing on Canvas 

Now you have set up the structure for you application, Lets look at how you can draw basic shapes onto the canvas.

Again place this logic wherever you prefer in your application as long as its execution comes after the above steps. I created a new method called createCanvasBg()

void drawCanvasBg(){

ctx.fillStyle = ‘black’;

ctx.fillRect(0, 0, WIDTH , HEIGHT);


Now in the draw method you implemented as part of the set up, add a call to drawCavasBg() in your method body. Run the application making sure you have kicked off the initialisation code in the main execution block. If successful you should see that you now have a black box on your screen. Not very exciting I know !

Create a new method(createSquare) or add logic to your execution block that will create the new square on the screen. Follow the implementation below

ctx.fillStyle = 'red';

// ctx.fillRect(x,y,height,width)
ctx.fillRect(100, 100, 50 , 50);

In order to draw a circle add the following instead of fillRect use the arc function.

context.arc(x, y, radius, 0 , 2 * Math.PI, false);

Run your application again and you should see a nice red square added to the canvas.

What you should have at this point


I hoped to provide a very very basic tutorial of canvas with dart as often drawing and graphics in the browser can intimidate people. This is how I got started and I was able to see what’s possible, I am currently contemplating making a simple platform game with a similar structure. Time allowing I hope to update this tutorial series as I go sharing my new experiences in the area. Next we will look at adding a player to the canvas that we can control using the arrow keys. This will be the hero for our game. I have also started looking at Dart Box2D a popular Javascript physics engine that has been ported to Dart, which I would suggest looking at if you havent already Seth Ladd from Google Dart Team has a good series of tutorials on his blog for this also.

Dart is a great language I am really enjoying developing with it and hoping to get more involved in the open source development of the language working on a few bugs at the moment. Just trying to find time out with work can be very difficult. I hope  you find this series useful I will continue to update my progress of my Github GameOff submission as it evolves (if it evolves :S)

Dart Touch

For those of you that have been following my blog you will know I have been experimenting with Dart and the DOM. I have made a couple of simple example applications as learning aids such as PicsAPuzzle and more recently the Conundrum word game.

During these experiments I battled with touch interactions on tablet/mobile devices, so I decided to make a library that allows you to easily add User Interactions to any html element on your page.

What is Dart Touch ?

The idea behind dart touch is that it will apply vey basic styling and actions to any html element, thus meaning you have to write less code and be generally more productive when creating interactive content

How to use it ?

dart touch is designed to be very easy to use and very flexible in terms of implementation. Previously to create a touch compatible drag n drop element would require you to map these event handlers and code each of the related methods.

void _onDragStart(MouseEvent event) {
void _onDragEnd(MouseEvent event) {
void _onDragEnter(MouseEvent event) {
void _onDragOver(MouseEvent event) {
void _onDragLeave(MouseEvent event) {
void _onTouchStart(TouchEvent event){
void _onTouchEnd(TouchEvent event){
void _onTouchMove(TouchEvent event){
void _onTouchLeave(TouchEvent event){
void _onDrop(MouseEvent event) {

This requires 9 methods to be individually coded to do very simple and basic actions to allow elements to be dragged and dropped with other items. With dart touch all you require is to add the css from the base.css file to your own projects css file and set the interaction you require via the setMethod from dart touch. example below


Passing this element into the set method will set all those interactions we looked at earlier for you, this only provides a basic implementation of all interactions if you want to further customise the Event Handlers you can create you own and add it to the basic implementation. Example


This doesn’t overwrite the functionality of onDrop it simply adds further functionality.


My latest Dart experiment Conundrum is an extremely difficult word game, simply as there are no hint’s yet. But basically rearrange the letters to spell the 9 letter word. Conundrum is made with dart_touch to show how the interactions can be used and extended. You can view the demo here

Conundrum Example


Dart Touch is very young at the time of reading exactly one day old !!! It currently only supports drag n drop actions, I plan on adding more in the future when time allows out with my day job. The code is fully open source and I would love people to contribute, fix bugs and help me out.

Source Code –¬†https://github.com/cmac458/dart_touch

If you want to chat about it please get in contact on Google Plus or Twitter @cmac457

Thanks for reading, hope you find dart touch helpful !


DART – MergeSort

Since I have started using DART many people have asked why I like it so much. As a Java developer at my roots I appreciate being able to code in an environment I am comfortable in, I believe this also makes us more efficient as programmers. As proof to some colleagues I decided to take one of the main sorting algorithms in a CS Grads tool belt the classic Merge Sort and code it in Dart as an experiment to show how similar it is.

class Sorting {

var unsorted ;
List placeholder;

var length;

List sort(List values) {
this.unsorted = values;
length = values.length.toInt();
placeholder = new List(length);
mergeSort(0, length-1);
return unsorted;


void mergeSort(low,high){

if(low < high) {
var middle = ((low+high)/2).toInt();
mergeSort((middle+1), high);


void merge(int low, int middle, int high){

for (int i = low; i <= high; i++){
placeholder[i] = unsorted[i];
int i = low;
int j = middle+1;
int k = low;

while (i <= middle && j <= high){
if (placeholder[i] <= placeholder[j]){
unsorted[k] = placeholder[i];
i ++;
unsorted[k] = placeholder[j];

while (i <= middle){
unsorted[k] = placeholder[i];


As you can see the above code looks very similar to the Java equivalent. The next step was to create a test package to test the logic of the merge sort. Dart has the very handy unittest.dart package that helps us create JUnit style tests that can be run via the editor or via the command line.

import '../packages/unittest/unittest.dart';
import '/C:/Users/O325882/dart/Sorting/web/Sorting.dart';

void main(){
Sorting sorter = new Sorting();
test('Merge_Worst', () => expect(sorter.sort([5,4,3,2,1]),orderedEquals([1,2,3,4,5])));
test('Merge_Best', () => expect(sorter.sort([1,2,3,4,5]),orderedEquals([1,2,3,4,5])));


As everyone can see there are many similarities between DART and more OO focused languages specifically Java. Making it very easier for Java devs to move into doing funky things with the browser and embrace HTML5 technologies.

Touch Events HTML5 – Drag n Drop (DART)

My last post focused on my simple app PicsAPuzzle which can be viewed here (picture below)

Iteration 1 of PicsAPuzzle

The purpose of the app was a quick learning project for me become more comfortable with Dart. The biggest criticism I had with the project was that I couldn’t play it on my mobile device or iPad. This entered me into find out how to add interactivity via touch events to the html web app.

HTML5 Touch Events 

The HTML5 specification may be huge and still growing but there is a lot of handy features that you may not know exist. Touch Events are one. I wanted to implement Drag and Drop the same way I could with a mouse but using my finger instead. HTML offers onDrag and onDrop event handlers for this. However with touch these do not exist. The three basic touch events are

  • touchStart
  • touchEnd
  • touchMove

There are more such as touchLeave but these 3 are all you need for most tasks. A touch event has 3 list each that contain the number of touches ie fingers on the screen at the time of firing the event.

  • touches
  • targetTouches
  • changedTouches

You set touchEvents the same way as any other kind of event (example in Dart)


Points to consider when using TouchEvents

  1. Zooming РOn mobile devices moving multiple fingers about the screen can result in the webpage being zoomed in/out. You may want to prevent this. I recommend doing so for drag n drop operations, You can prevent with following meta tag :
    <meta name="viewport" 
      content="width=device-width, initial-scale=1.0, user-scalable=no">
  2. Scrolling РEspecially with Drag n Drop interactions moving your finger around a screen is the default way to scroll a page on mobile devices so using the following code in you handler methods will prevent such interactions with the browser

Implementing Drag n Drop 

So that covers the basics of touch event’s and how best to prepare your application for mobile devices. We will start looking at implementation of Drag n Drop. Code snippets have been commented to describe the logic without writing addition paragraphs on them.


This method works very similarly to the onDragStart/onDragEnter methods. You want to capture the element being dragged and apply some style to the element to indicate to the user that the element is selected and draggable.

void _onTouchStart(TouchEvent event){
//stop scrolling by default
//capture drag target
Element dragTarget = event.target;
//add style to element to indicate its moving
_dragSourceEl = dragTarget;


The event is fired when the finger moves across the screen from its starting co ordinates. Tracking the finger until it stops allows us to simulate the mouse moving across the screen. What I did for this was to capture the co ordinates of the first fingers position and find out which element the finger was over, that way when the finger is removed we know the last place it visited.

void _onTouchMove(TouchEvent event){
//indicate to user element is in motion
//prevent all default behaviour ie Scrolling
//Get the current x,y position of the first finger and find the element it is over
_dropTarget = document.elementFromPoint(event.touches[0].pageX,event.touches[0].pageY);
// If the finger is over an element indicate that in the UI
if(_dropTarget != null){



The implementation of the onTouchEnd method will be identical to the onDrop method in the last tutorial I wrote РGetting Started : Dart. You are completing the same logic think of lifting your finger off the screen as depressing the mouse button. If you are unsure of the implementation you can look back at the last post here



I still have some work to do in regards to the css styling as we dont have as many transition states with touch events I have to streamline the css to provide a smoother dragging effect. However this should get most people started with implementing their own Drag n Drop HTML5 web app. If you have any questions do post them I will try my best to answer. Im likely to be very busy im working on a new utility library to make creating cross platform interactions much easier, so will post progress on that or anyone interested in helping out can contact me here too.

[Update PicsAPuzzle responsive template is broken at time of writing so please be patient with it]

Thank for reading, Dont forget to check out PicsAPuzzle on Github I aim to create a few more small apps to experiment with different interactions. All constructive feedback is welcome.