Set your browser on Fire with P5.js

This post is made for those (like me) who like image processing, web development and maybe, for those who want to learn new programming technics...

- I will make you discover p5.js, a javascript library specialized in graphical creation for your web browser !

- I will also talk about the the Youtube channel "The Coding Train" presented by Daniel Shiffman. A lot of its videos are based on P5.js. It was for me a great source of inspiration and made me discover javascript (because I'm a newbie with JS...) So I'm pretty sure, you will learn a lot too...

- Finally I will present you my personnal example of what I did with P5.js. It's about an old retro fire effect (used in demoscene few years ago) :)

So let's begin with p5.js !

I- What is P5.js ?

a- Presentation

As I mentionned it previously, P5.js is a graphical Javascript library. With it, you will be able to make great effects in your web pages in a few minutes. 
This lib has been created by Lauren McCarthy ( in order to provide an educational tool used to understand graphical programmation basis.

Start here:

b- And what can I do with this lib

This library is pretty simple to use. It is composed of the following main groups of functions:
- Drawing shapes and images. It includes the loading of 3D models !
- Managing colors (include saturation, brightness, contrast...)
- Functions to interact with your environment (including the listening off your hardware events like the mouse or the keyboard)
- some mathematical functions
- and other usefull tools...

You can have a look of all the API references here:

c- Easy to start

If you are interested in playing with P5.js, it's super easy. You will find all you need on the website. Then you edit your code (javascript) in your prefered editor ! That's all.

You will also find additional libraries to get some sound / geolocation features / particles systems and much more ! Download only the one you need.

II- The coding train (youtube channel)

Now that you know about this tool, you are maybe wondering what you can do concretely...  The coding train is here to give you some ideas, (a lot of ideas !).

This Youtube channel is presented by Daniel Shiffman, a teacher that loves to teach :) He uses P5.js to implement a wide range of algorithms, from easy ones to complex ones like AI implentation and representation... Daniel is really clear and puts all its energy to make great tutorials. I presume you will like it too :)

If you are interested, I let you have a look to the channel:

Here are some of the tutorial video themes he made (but there is so much more !!):

Learn AI

More AI with Neural Networks

Make a Snake game in Javascript

Make retro effects (like a star field)

III- My sample, a retro fire effect !

For those who wonder how to implement a graphical effect, I will describe you my p5.js sample. It's a really simple sample but you will understand the key concepts of p5.js. 

I will share you the code, and for sure, you can play with it and improve performances or what you want.

a- Lib files

The first step is to download the library files. Then you should  make a new project folder with the following structure:

Your project folder

The child 'librairies' folder

b- sketch.js, draw your effect here

You will place all your code in this file. The 2 main methods needed by p5.js are the following:
- function setup ( )
- function draw ( )

The first one handle the page/effect initialization while the second is called several times per second to render the content. So here is the source code with all the steps commented:

// global parameters
var fireElemLenght  = 6;
var elemOpacity     = 255;

var fireLines   = [];
var fireWidth   = 0;
var fireHeight  = 0;

var nbColors    = 255;  // Nb Colors in the palette
var palette     = [];   // our color palette for the fire

// ======================================
// SETUP method 
// called 1 time during the page loading
// ======================================
function setup() {
  createCanvas(800, 600);
  // 2D Fire: init size of fire
  fireWidth   = int(width / fireElemLenght);
  fireHeight  = int(height / fireElemLenght);
  print(fireWidth + ", " + fireHeight);
  // for each fire's 'lines'
  for(var i= 0; i<fireHeight; i++)
    fireLines[i] = [];      // create the new line of fire pixels
    for(var x=0; x<fireWidth; x++)
      fireLines[i][x] = 0;  // Initialize to black
  // generate fire colors palette
  // set black background

// ======================================
// DRAW method
// called in the drawing process loop 
// ======================================
function draw() {
    // We clean the background each time
    // We generate a new base fire line (to make it 'move')
    // Compute the whole fire pixels
    // Display the result

// ======================================
// > Initialize Palette mehtod
// You can update this process to change the fire colors
// ======================================
function initializePalette()
  // generate our 255 color palette
  // try to change colors composing the fire
  for(var i=0; i<nbColors; i++)
    var val   = exp(i/10) - 1;

    var red   = map(val, 0, exp(7.5), 0, 255);
    var green = map(val, 0, exp(10), 0, 255);
    var blue  = random(50);
    if(green > 254) // check for colors range
      red   = 255;
      green = 255;
      blue  = 255;
    // check/erase for 'noisy' blue pixels
    if(red < 20 && green < 20)
      red = green = blue = 0;

    // add new color
    palette[i]  = color(red, green, blue, elemOpacity);

// ======================================
// > initFireLine() method
// Make a new base fire line (randomly, to make the fire 'move' when it grows)
// Remark: Y axis is inverter on our screens ==> baseY = fireHeight-1
// ======================================
function initFireLine()
  // generate fire base (1st line) color ('randomly')
  for(var x=0; x<fireWidth; x++)
    fireLines[fireHeight-1][x] = random(0,nbColors);
    fireLines[fireHeight-2][x] = random(0,nbColors);
    fireLines[fireHeight-3][x] = random(0,100);

// ======================================
// > fireGrow() method
// Compute the whole fire, line by line. Start after the base line
// We compute each pixel color from its neighbors (a kind of median)
// It gives a blurry effect
// ======================================
function fireGrow(){
 // for each fire line
 for(var y=fireHeight-2; y>=1; y--)

  // compute new fire color line 
  // based on the bottom & top lines
   for(var x=1; x<fireWidth-1; x++)
       // Get neighbors colors
       var c1 = fireLines[y+1][x];
       var c2 = fireLines[y][x-1];
       var c3 = fireLines[y][x+1];
       var c4 = fireLines[y-1][x];
       var c5 = fireLines[y][x];

       // We make a 'median' color
       var newCol = int((c1 + c2 + c3 + c4 + c5) / 5) - 1;
       fireLines[y - 1][x] = newCol;

// ======================================
// > drawFire() method
// Drawing pass - to draw the fire from its computed matrix
// ======================================
function drawFire(){

  // foreach fire lines
  for(var y=fireHeight-1; y>0; y--)
    // foreach pixel in the line
    for(var x=0; x<fireWidth-1; x++)
      // get current pixel color index
      var idx = int(fireLines[y][x]);

      // check for color index limits
      if(idx<0) idx = 0;
      if(idx >= nbColors) idx = nbColors-1;
      // apply current pixel color

      // Draw a square representing the current fire's pixel
      rect(int(x * fireElemLenght - (fireElemLenght / 2)),
          int(y * fireElemLenght + (fireElemLenght / 2)),
          fireElemLenght * 2 , 
          fireElemLenght * 2);



You should get something like that:

EMGU with Xamarin Forms guide [part 1]

I- Introduction, OpenCV and EMGU

Do you know OpenCV (Open Source Computer Vision Library: ?  This open source library let's you work and play with images and videos with a lot of powerful image processing algorithms !  If you want some details, I suggest you to first navigate to the link above or search for 'OpenCV' on Google. 

Examples of OpenCV processing found on the web (filters, object detection, edges...):

EMGU is a .NET OpenCV wrapper. That means that you will be able to use OpenCV functionnalities in your .NET projects using C# for instance. EMGU is cross platform, so you will also be able to use it in your Xamarin projects ! That's great because there is no advanced image processing library in Xamarin.

In this article, we will talk about EMGU and list the steps to setup a Xamarin Forms project using EMGU. It may help you because, we must say that it's not a trivial task... 

II-What do I need to start ?

1- A licence please

The first thing you have to understand, is that you will need to purchase a commercial licence to use EMGU with mobile devices (so with Xamarin). You can refer to this page for all the details:

The website isn't so clear so here is the purchase link:

2- iOS and Android libraries

Once you have purchased a licence, you will have access to a link where from you can download the libraries. In our case we need the iOS and Android libs.

As we will see in the next section, inside the extracted folders, you will find the source code but also:

  • - Needed Android libraries to be able to build your Xamarin Android projects
  • - Needed iOS DLL to be able to build your Xamarin iOS projects

Needed folder to build for Android:

Needed library to build for iOS:

III- Next, setup your Xamarin project to use EMGU

1- Create your project solution

First thing to do is to create a Solution for your project. In our example we will use Visual Studio to do this, but you can also try with VS for MAC. See picture below:

EMGU does not provides PCL library, that means that you will have to create a project with the "shared project" option instead of a "Portable Class Project". See picture below:

When asked, you should cancel the creation of Windows 10 projects (it's not in the scope of this article):

The base project will include:
- Shared project: you will put inside all your shared Pages for instance, or your shared services between iOS and Android
- Xamarin.Android project: you will put inside all your related Android services and classes
- Xamarin.iOS project: will contain all your iOS classes
- All EMGU Android / iOS needed libraries as we will see in the next chapter

2- Reference EMGU

When your empty Xamarin shared project is ready, you will have to make reference to EMGU component, for Android & for iOS projects.

- Notice that these process are not the same for Android & iOS !

2.a- Reference EMGU in your Android project

For Android, I think the best choice you have is to integrate the EMGU shared projects directly into your solution. Copy the Android projects that you extracted previously. Projects you need are listed below. In my example, I separate those projects in a specific solution folder called "EmguLib". 

Then you just have to reference those shared project from the Android one. Here is the organisation for Android:

Android: How to reference EMGU library

If you try to build the project now, you will surely have a compilation error:

"This package do not contain necessary binary for Xamarin Android App. Emgu CV for Android Commercial Licence is required. x86...."

Don't be afraid. We talked about it in the previous paragraph. You just have to copy / paste the "libs" folder from the android sources you downloaded to your project (at the same level as your EMGU shared projects that you reference). All will be good if you bought the licence :p

2.b- Reference EMGU in your iOS project

For iOS, it's a little bit "simpler" because you just have to copy one DLL library (specially compiled for iOS) and reference it into your iOS project. You can place it where you want into your solution hierarchy but take care the file is big ! (about 210 Mb).

File to reference in your iOS project (as seen in the previous paragraph):
--> EMGU.CV.World.iOS.dll

You should have something like that:

You are ready !

Steps below are not complicated, but there is no really helpful documentation about how to setup EMGU with XAMARIN FORMS. You can just try to inspect the sample projects. After playing around really shortly with EMGU, in a few line of code:

- I opened an asset image
- loaded it into a 'Mat' openCV object
- applied a Canny edge algorithm on it
- then displayed the image

Tada !

First step, load an image
Apply the 'Canny Edge Detector algorithm', and here is the result for Android & iOS:

It's only the begining. At this point, if you are new with OpenCV, you can try algorithms you want just to learn. On my side, new Xamarin Forms + EMGU articles will come, so  follow me ;) !

Xamarin Forms essential: FFImageLoading, manage your images

Discover 'FFLoadingImage' library

Today I want to make a quick presentation of a really good library for Xamarin Forms. This is the kind of library we would like to see more often on XF... This one is dedicated to image manipulation. It's called "FFImageLoading".

If I take time to make this presentation, it's because I think that we should use it in almost all our "basic" Xamarin Forms applications. When I say basic, I exclude Games or other specific apps. But in my mind, I suggest you to change all your traditional "<Image />" by "<FF:CachedImage />" in your apps.

Before to start, where to find it ?
On Github:
On Nuget:

Main features

So what will you find using this library ? I will not explain all the details but the main interesting features of the library.


The good point is that this library supports multiple platforms:

  • - All the xamarin platforms: iOS, Android, MAC, and Xamarin Forms 
  • - But also Windows (WinRT & UWP)

So you can use the library either in your XAML code or in your code behind. It's really flexible, ideal for Xamarin Forms projects.

Image cache system

The main feature provided by the library is a picture cache system. This system is pretty complete and you are able to customize it if you want (XAML and code behind). You can set cache keys to your images, you can set a lifetime and so on...

Thanks to the cache you can greatly improve performances of long lists for instance (with images in their data items). 

Here is a XAML example on how to use the 'CachedImage' control:

<!-- contact image -->
  Source="{Binding ProfilePictureUrl}"
  <FFTr:CircleTransformation BorderHexColor="#FFFFFFFF" BorderSize="0" />

'CachedImage' used in long list for better performances:

Image loading and PlaceHolders

Thanks to "FFImageLoading" you can load images from different sources (from XAML or code-behind):

  • - from stream sources
  • - from file image sources
  • - or from Uri sources

But the user-friendly point is that you can specify temporary images for the loading process and in case of error.
For instance if you load an image from the web, it can take some times, so the temporary picture will be displayed instead. 
And if an error occurs when loading the image, the "Error placeholder image" will be displayed automatically. From a user point of view, it's really cool and now it costs nothing ;)

Download properties

When you want to display a FFImageLoading image , you can specify several usefull parameters (XAML and code behind).

  • - we already talk about cache parameters like "CacheDuration" property
  • - you can also specify "retry" parameters in case of errors like "RetryCount" to tell how many times you want to retry or "RetryDelay" to wait before retrying loading the image.
  • - But you can also specify download properties like "DownSampleWidth" or "DownSampleHeight" to specify a new size for the downloaded image

SVG / Gif support

A good point to notice too, is that the library support the SVG and Gif formats. So instead of loading traditionnal pictures, you can load a SVG image for a loading placeholder for instance.

If you are a good designer and replace your icons and simple pictures by SVG files, it can make you save size on your final app's packages !


FFImageLoading offers "transformation" capabilities. That means that you can apply effects on images before to display it. These effects are of 2 kinds:

  • - image rendering effects, to apply some effects on colors
  • - or image clipping effects to make the image looks rounded, circle or cropped...
  • - AND you can also implement your own effect thanks to the provided "ITransformation" interface !

Some effects / transformations:


All these features look optimized (without any complicated setup for you) and I didn't really have any issue by using it. I just noticed a better user navigation thanks to the quick loading of images. So if you want to learn more about this library, I suggest you to follow the following links:

The Wiki:

How to use it in details (tutorial in video):

Xamarin Forms + Parse + Push Notifications + Android = trouble

Quick Introduction

It took me some times to implement Parse's push notifications in my Xamarin Forms (Android) application. I find out some issues and made workarounds. Strangely, I have the impression that I'm a rare guy working with Xamarin Forms and Parse... But maybe you are in the same situation that I was. So just read the following.

The context

I'm actually making a (cool) Xamarin Forms app (maybe I will talk about it later in another post). One of my final steps is to implement Push notifications. Details of the context of my project are the following:

- Xamarin Forms (Android & iOS) app
- I use Parse server for my business server. Actually I host my Parse server at for convenient reasons but I could host it on many other servers.
- So logically, for the push notifications, I would like to use Parse push notification service.
- In order to use Parse Services, I use Parse .NET SDK (latest available version is v. - note that it's important for the next part ;)

The problem (Parse .NET SDK)

I encountered many problems but specially 2 annoying ones with Parse. 
The first one is that there is no Parse PCL library to use with Xamarin Forms... I talked about it in this post: Parse for Xamarin - no PCL, my solution.
But my main problem was with push notifications (specially with Android). It was not working and I couldn't find any solution on the web ?! (maybe I'm not efficient enough with Google :p) It took me several days to find a working solution...

Almost my troubles where located in the Parse .NET SDK ! 

What are the issues ?!

1- Setup PN for android apps

First thing to do is to configure your Android Application. I'm sure you have found many articles on it. But the key points to care of are:
  • Use FCM (Firebase Cloud Messaging) instead of GCM (former Google Cloud Messaging) because it is deprecated.
  • Then make a big attention to your androidManifest.xml file. Some sections are mandatory in order to make PN works...
You can find a good article on it here. Take your time and follow the guide step by step:

For the "AndroidManifest.xml" file, take a look at mine with needed sections and permissions:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="" android:installLocation="auto" package="" android:versionName="1" android:versionCode="1">
  <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="25" />  
  <uses-permission android:name="" />
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.WAKE_LOCK" />
  <uses-permission android:name="android.permission.VIBRATE" />  
  <permission android:protectionLevel="signature" android:name="" />
  <uses-permission android:name="" />
  <application android:label="My app" android:icon="@drawable/icon">    
    <meta-data android:name="com.parse.push.notification_icon" android:resource="@drawable/icon" />
    <meta-data android:name="com.parse.push.gcm_sender_id" android:value="@string/gcm_sender_id" />  
    <provider android:name="" android:authorities="" android:exported="false" android:grantUriPermissions="true">
      <meta-data android:name="" android:resource="@xml/file_paths"></meta-data>
    <service android:name="parse.ParsePushService" />
    <receiver android:name="parse.ParsePushBroadcastReceiver" android:permission="">
        <action android:name="" />
        <action android:name="" />
        <category android:name="" />

Don't forget to replace "" by your own app's package name. And I put my GCM_SENDER_ID into the "strings.xml" file.
GCM_SENDER_ID must be prefixed by "id:", (ie: "id:XXXXXXX")

2- Parse .NET SDK, issue 1: latest release does not contain fixes

Yes you read it correctly. As everybody should have done, I used the latest Parse SDK release that can be found here on github:

"Missing SenderID issue": After investigations, I found that there was an interesting bug specifically on push notifications... but I also noticed that this bug was already corrected...


As you can see, the fix has been made on March 2016. The latest SDK release is from January 2016... So the latest release doesn't contain bug fixes !

3- Issue 2: GET_ACCOUNTS permissions uneeded

There is also a second issue that has not been merged into the latest release. It concerns a permissions in the "AndroidManifest.xml" file that you must not set !

This is the "Get_ACCOUNTS" permission. Be sure to remove it from your manifest in order to get Parse PN working EVEN IF A DEBUG MESSAGE TELLS you that this permission is needed...


It took me too much time to understand that :p ! And the last problem will make you understand why !

4- Issue 3: Invalid debug messages in the SDK :'(

Finally, as I told you, I found invalid debug messages in the SDK source code. So that's why I didn't understand quickly what was happening.

In particular in this file:

Take a look at the picture bellow. I thought I was dealing with a specific problem but in fact it was another :'0

Finally what did I do ?

As I have no more time, I did what nobody should do when publishing a "production" application :p
- I took the latest release source code
- Then I corrected by myself the mentionned issues (using the work already done by Richard Ross on github).

- Finally I recompiled a release version for Android only. If you are interested, you can download the recompiled Parse.Android.dll file below. I gave it the version number

Parse.Android.dll (v. with Push notification fixes)


Shuffle List in C#

Yesterday, I was looking for an algorithm to shuffle a list of objects in C#. So in my mind, I started to think about "complex" algorithms to do that, using random numbers and list elements switching...

I say "complex" because while I was googling, I found a good solution to do that ! And it takes only 1 line :p I would have never thinked of that :) :)

Here is the cool code:

var shuffledList = myObjectList.OrderBy(item => Guid.NewGuid());

So, that's really simple. You can use the "OrderBy()" Linq extension to rearrange the list. This method will take a 'random' object, in this case a GUID. And we know that GUIDs are 'unique' so, it does the job!

You can use variants like this one:

var rnd = new Random();
var shuffledList = myObjectList.OrderBy(rnd.Next());

Next step, compare performances, between different solutions...

Visual Studio for MAC, review (fr)

If you are a developer, there are many chance that you already used Visual Studio, the famous Microsoft's IDE.

Visual Studio for MAC is borned a few weeks ago. But is it a productive tool like on PC ? If you are a Xamarin Developer and never tried it, I suggest you to take a look at this short review to get some clues !

This review is avaible in french on

[Xamarin Forms] Custom bottom bordered entry (iOS & Android)

Custom entry with renderers

For my Xamarin Forms project I needed to render an 'Entry' control with a bottom border of a specific color. There are several possibilities but I will show you mine.

For that, I used renderers. iOS one is particularly not trivial.
The wished result look like that:

iOS Renderer

[assembly: ExportRenderer(typeof(ExtDatePicker), typeof(ExtDatePickerRenderer))]
namespace MyCompany.iOS.Renderers
    public class ExtDatePickerRenderer : DatePickerRenderer
        protected override void OnElementChanged(ElementChangedEventArgs<DatePicker> e)

            // Need to connect to Sizechanged event because first render time, Entry has no size (-1).
            if (e.NewElement != null)
                e.NewElement.SizeChanged += (obj, args) =>
                    var xamEl = obj as DatePicker;
                    if (xamEl == null)

                    // get native control (UITextField)
                    var entry = this.Control;

                    // Create borders (bottom only)
                    CALayer border = new CALayer();
                    float width = 1.0f;
                    border.BorderColor = new CoreGraphics.CGColor(0.73f, 0.7451f, 0.7647f);  // gray border color
                    border.Frame = new CGRect(x: 0, y: xamEl.Height - width, width: xamEl.Width, height: 1.0f);
                    border.BorderWidth = width;


                    entry.Layer.MasksToBounds = true;
                    entry.BorderStyle = UITextBorderStyle.None;
                    entry.BackgroundColor = new UIColor(1, 1, 1, 1); // white


In iOS, the native control used to represent an 'Entry' is a 'UITextField' control.
The key point is that we need our renderer to update this 'UITextField' on SizeChanged event and not on the traditional 'OnElementChanged' event.

Why because, the size is not yet computed when we enter the 'OnElementChanged' event. So we can draw our bottom line as we don't know its lenght...

Android Renderer

For Android, I decided to make a really simple renderer that will use a drawable resource as a background. Here is how I did:

First step, add the xml file that contains the "shape" in your android project resources:

The 'shape' (xml drawable resource)
To make the bottom line, I found on Stackoverflow a nice solution. You just have to generate a gradient from the desired border color to the transparent color with the border color having a really small height (making a line).

Here is the code:
<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="" android:shape="rectangle">
  <gradient android:angle="90"

And finally the renderer:
[assembly: ExportRenderer(typeof(ExtEntry), typeof(ExtEntryRenderer))]
namespace GoodChapp.Android.Renderers
    public class ExtEntryRenderer : EntryRenderer

        protected override void OnElementChanged(ElementChangedEventArgs e)

            if (Control != null)
                // Background

The final results (Android & iOS)

Surely, you can change the border color and any other properties !

[Xamarin Forms] build error: Unable to cast object of type 'Xamarin.Forms.Xaml.ElementNode' to type 'Xamarin.Forms.Xaml.ValueNode'

Xaml build error

For one of my Xamarin project, I just had this build error:
This error was related to my XAML code:

Unable to cast object of type 'Xamarin.Forms.Xaml.ElementNode' to type 'Xamarin.Forms.Xaml.ValueNode'

After searching for a long 'moment', I just didn't understand what happened...

My investigation (this process can help you :p)

So I decided to remove a large part of my xaml code and then re-add it little by little. Each step I tried to compile to see when error occurs.

So In my case, I determined that the piece of code that was going wrong was the following:

Ok, it was my mistake but in the code editor, Visual Studio didn't tell me anything.
I was trying to bind an event (I though it was a property) to a DateTime property... What is not possible.

Hope this helps someone to save a few minutes :)