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 

canvas.html

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.

canvas.dart

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;
int HEIGHT;

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);
requestRedraw();

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

window.requestAnimationFrame(draw);

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

Conclusion

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)

Advertisements

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.

 tile.on.dragStart.add(_onDragStart);
 tile.on.dragEnd.add(_onDragEnd);
 tile.on.dragEnter.add(_onDragEnter);
 tile.on.dragOver.add(_onDragOver);
 tile.on.dragLeave.add(_onDragLeave);
 tile.on.drop.add(_onDrop);
 tile.on.touchStart.add(_onTouchStart);
 tile.on.touchMove.add(_onTouchMove);
 tile.on.touchEnd.add(_onTouchEnd);
 tile.on.touchLeave.add(_onTouchLeave);
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

touch.setDragNDropTouch(element);

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

card.on.drop.add(_onDropCheck);

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

Conundrum 

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

Conclusion 

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(low,middle);
mergeSort((middle+1), high);

merge(low,middle,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 ++;
}else{
unsorted[k] = placeholder[j];
j++;
}
k++;
}

while (i <= middle){
unsorted[k] = placeholder[i];
k++;
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)

PicsAPuzzle
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)

tile.on.touchStart.add(_onTouchStart);

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
    event.preventDefault();

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.

onTouchStart 

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
event.preventDefault();
//capture drag target
Element dragTarget = event.target;
//add style to element to indicate its moving
dragTarget.classes.add('moving');
_dragSourceEl = dragTarget;
}

onTouchMove

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
_dragSourceEl.classes.add('moving');
//prevent all default behaviour ie Scrolling
event.preventDefault();
//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){
_dropTarget.classes.add('over');
}
}

 

onTouchEnd

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

 

Conclusion 

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.

Chris