Check out my
new book!
Photoshop blend modes with Pixastic I've added a new action to the Pixastic library called "blend". This action lets you blend two images using different blend modes like the ones available in Photoshop (multiply, screen, exclusion, etc.).

Example usage

var img = new Image();
img.onload = function() {
 var blendImg = new Image();
 blendImg.onload = function() {
  Pixastic.process(img, "blend", 
   {
    amount : 1, 
    mode : "multiply", 
    image : blendImg
   }
  );
 }
 blendImg.src = "blendimage.jpg";
}
document.body.appendChild(img)
img.src = "myimage.jpg";
The image on which you apply the action will be considered the base image when blending. You can use either an img element or a canvas element for the "blend image". It expects the images to be the same size but will simply crop the blend image if it's too large or leave untouched areas if it's smaller then the base image.

Check the demo page to see it in action.

Below are shown all the blend modes included. The images used are:
Base image:

Blend image:

Blend modes

Normal
Darken
Multiply
Color Burn
Linear Burn
Darker Color
Lighten
Screen
Color Dodge
Linear Dodge
Lighter Color
Overlay
Soft Light
Hard Light
Vivid Light
Linear Light
Pin Light
Hard Mix
Difference
Exclusion


So, basically all the Photoshop modes sans "dissolve" and the HSL based ones (which I guess I'll add at some point as well).

Read more...
Genetic algorithms, Mona Lisa and JavaScript + Canvas About a month ago, there was an interesting article about using genetic algorithms to "evolve" images. Roger Alsing had made a small program and put it to the test by letting it make a very good approximation of the Mona Lisa with 50 layered, semi-transparent polygons. I figured I'd try to do something similar with JavaScript and Canvas.

Genetic algorithms

So, the basic idea of genetic algorithms is that you have a population of individuals, each carrying a DNA string representing a possible solution to the problem (in this case, the polygonal likeness of Mona Lisa). The initial population is assigned random DNA and subsequent generations are then created by mixing the DNA of the fittest individuals of the current population. In order to ensure diversity in the population, there's a small chance of mutation where a DNA value is randomly changed. However, Roger Alsing's project actually uses a population of only one parent, making it more like a hill climbing algorithm where the current solution is altered slightly and if it's a better fit, the old one is discarded.

I tried to go for a more proper genetic algorithm approach with an adjustable population size, selection, DNA mixing and everything. Now, Roger used just short of a million generations to get to his result (which was very accurate). It took 3 hours for his (compiled) program to generate the resulting image, and of course, even if JS engines are getting faster, it's going to take a bit more time than that to get as nice a result as his using JavaScript. Still, even after a few hundred generations/a few minutes in my demo, with the default parameters, you should see the shape of Mona Lisa starting to take form. I'm unfortunately not very patient, so I'm not sure if my experiment can even create as good an approximation, given the necessary time.

There are also a few other images you can play with. I've made the images pretty small (100x100) so that evolution would be as speedy as possible. The fitness function actually uses an even smaller (50%) version.

Options

Some of the parameters can be changed before starting the evolution. They are:
  • Number of polygons: The number of polygons used to in the image approximation.
  • Polygon complexity: The number of vertices in each polygon.
  • Difference squared: If checked, the squared differences of the RGB values are used when calculated fitness, otherwise simply the absolute difference.
  • Population size: The number of different candidates in each generation.
  • Succesful parents cutoff: The percentage of candidates selected for breeding the next generation, eg. 0.25 = the fittest 25% of the current population.
  • Mutation chance: The chance that a value will mutate when breeding new candidates, for example 0.02 = 2% chance of mutation.
  • Mutation amount: The amount the mutated value will be changed, for example 0.01 = 1% means a random change between -1% and 1%.
  • Uniform crossover: If checked, values are mixed at random one by one from each parent, otherwise a single random cut in the DNA string is made and one part from each parent is used.
  • Kill parents: If checked, the new generation will consist entirely of the children of the old generation. If not checked, the parents are left alive and will compete against their offspring.

If the parents are not carried over to the new generation, you will notice that the best fitness value in the new generation might actually be worse than the previous one. On the other hand, that could make it easier to avoid dead ends and premature converging towards local optima.

Note that changing the parameters won't have any effect until the evolution is restarted.

A few results

Here are a few quick runs, showing the results.


Mona Lisa after 25 minutes


Firefox logo after 25 minutes


Opera logo after 40 minutes


Mondrian after 14 minutes


Microbe after 9 minutes

Browsers

Since we're using canvas there's no support for IE. Furthermore, we're using the getImageData method, so only Firefox, Opera 9.5+ and WebKit nightlies will work. I suggest using either the latest Firefox beta/preview or a recent WebKit nightly as they seem to yield the best performance.

One last note

Only now, after I'd been playing around with this, have I noticed that someone had already done a JavaScript/canvas version of Alsing's program (where you can even use your own images) back when the original article was published, and for some reason I missed it. That version stays closer to what Alsing was doing, though, where mine differs in a lot of ways.

I think my approach gets to something resembling the target image faster, but it seems to have problems getting the details in place after that. I haven't had the patience to let it run for more than a couple of hours and it's quite possible that the other techniques are able to get a better approximation in the long run.

Play with it here

Read more...
2008 - A Year of Awesome JavaScript 2008 has been just great, not least because of all the great stuff people have been doing with JavaScript, the new canvas element and the web in general. Browser vendors are now competing, trying to outdo each other in terms of JavaScript performance, leaving developers and end-users as winners as we now get to do cool stuff that wasn't really feasible before. Here's a summary of the neat things of the year 2008 as I saw it.

Games

It's been a great year for JavaScript games. It looks like DHTML and canvas-based games are now capable of taking over some of the areas where Flash used to dominate. Many people have been building remakes of classic video games like Super Mario, Pac-Man, Breakout, Space Invaders, Bomberman or T&C Surf Designs.

Others took the old arcade traditions and applied them to their own ideas, giving us cool games like Matt Hackett's Spacius, Mark Wilcox's Invaders from Mars, VertigoProject's RedLine Racing or a twist on the classic Tetris game.

We've even seen some roleplaying games, like the very cool Tombs of Asciiroth or the more graphical CanvasQuest by Andrew Wooldridge and the Prototype based ProtoRPG by Pierre Chassaing. Although they are mostly betas or demos at the moment, they look like they could turn out to be really cool one day.

2008 also saw a few libraries for JavaScript / DHTML game development pop up, most notably GameJS (pictured to the left with its demo game, Jetris) and GameQuery, the latter being an extension to the popular jQuery library.

Last, a special mention to a great (but small) game, DEFENDER of the favicon. Mathieu 'p01' Henri squeezed a version of the old Defender game into the 16x16 space of the favicon. How sweet is that?

Demos


Antisocial Demo The canvas element is now supported in most browsers (that are not made by companies called Microsoft). That means we now have more options for creating dynamic graphics in the browser and people have not been shy to use it to show off their mad skills. Some have made small and simple demos showing the capabilities of the canvas, while others took it a step further, like Matt Westcott and his Antisocial demo, a social network satire in nice demo style complete with a demo making tool.

256 bytes Mars demo Others who have been busy this year include the talented Mathieu 'p01' Henri who, among other things, specializes in making really tiny things, including tiny pieces of code that do cool things, examples: Rubber effect, Tunnex, Mars. All in 256 bytes each, nice!

20 lines canvas demo - Hypno Trip Down the Fractal Rug As if that's not enough, Mathieu Henri is also a regular over at the Ozone Asylum where he teamed up with the canvas element for the 20 lines contests to create visual goodies such as Dynamic Hypnoglow, Twinkle and Hypno Trip Down the Fractal Rug. These contest also gave birth to other great effects like colliding balls, some sort of 3D cube effect and dynamically generated BMP flames.

20 lines Boulder Dash clone The Asylum inmates have even created small 20-line games, ranging from Lunar Lander to a Boulderdash clone and an impressive homage to Wolfenstein 3D

3D


Projective transform with canvas At the moment, the canvas element only supports 2D graphics, although there are efforts to enable a hardware accelerated third dimension from both the Mozilla and Opera teams. That doesn't mean there's no 3D graphics being done, though. Everything from basic 3D cubes, texturing experiments to regular JavaScript/Canvas 3D engines have been done.

Also check out the stuff done by the guys over at the Wii Opera SDK (it's not just for Opera or the Wii) and of course the 3D stuff here at Nihilogic.

Emulation


JavaScript ZX Spectrum Emulator That JavaScript performance is getting better and better must be true since it's now possible to emulate other systems in the browser. Matt Westcott (who also made the Antisocial demo) pulled another rabbit out of the hat, JSSpeccy the ZX Spectrum emulator. That's just way cool.

James Urquhart also played a bit and created a proof of concept SCUMM interpreter. It won't let you play Day of the Tentacle or even Maniac Mansion, but supposedly it can at least let you see a bit of OpenQuest.

JavaScript AGI interpreter A personal favorite of mine was António Afonso's JavaScript AGI interpreter. AGI was the system used by Sierra in the golden days of adventure gaming and when António made this little gem with an (almost) working Leisure Suit Larry, it just totally tickled my fancy.

Graphics


Processing.js One of the most impressive feats this year must be John Resig's port of the Processing language to JavaScript, Processing.js, complete with a giga-ton of cool demos. In the same vein, Aza Raskin created Algorithm Ink, a JavaScript/Canvas port of the Context Free program, a method for creating images based on rules and instructions. And there's more! Eitan Suez liked Turtle, the old Pascal graphics programming tool, so much that he decided to make a JavaScript version of it, TurtleJS.

JavaScript Fractal Explorer On a more mathematically nerdy note, a few people have also been tackling fractals using JavaScript. Once again, p01 decided to play and rendered the Mandelbrot set with 137 bytes of DHTML which, with a bit of friendly competition, ended up at a tiny 111 bytes (FF only). Oliver Hunt created a prettier, graphical Mandelbrot set (as did I), and Russ Hall even made a full-fledged fractal explorer application.

Audio


JavaScript drum machine While waiting for proper support for the HTML5 audio element, most people have gotten used to settling for Flash-based audio but that doesn't mean you can't make weird experiments with sound and JavaScript. For example, check out the JS-909 drum machine by Cameron "The Man in Blue" Adams. Admittedly, it does rely on Quicktime, but cool nonetheless.

Or how about dynamically generating and playing WAV files, like this sine waveform generator by sk89q, and while we're at it, have some generated MIDI as well.

Odds and ends


Not just graphics and audio files can be generated, though. How about a small JavaScript library capable of generating ZIP files on the fly?

Homer made with CSS How much can you really do with CSS these days? Isn't it just for styling your text and placing your divs? Apparently not. Román Cortés has at least shown that an image of Homer Simpson can be created if your CSS-fu is strong enough.

Ernest Delgado mixed my Mario Kart demo with OpenStreetMap to create a nice little tech demo resembling the GPS navigation systems found in cars.

Cubescape Finally, Cubescape is a cute, fun toy where you simply build a cubic landscape by dropping colored cubes. Great timewaster from The Man in Blue.

Of course, I've also been doing a bit of tinkering here at Nihilogic myself, so be sure to check the archive to see if there's anything you missed. I just hope 2009 will be as cool as 2008 was (and I don't see why that should not be the case!).

What do you think was great in 2008?

Edit: Chinese translation here
Read more...