Tutorials – CreativeJS http://creativejs.com The very best of creative JavaScript and HTML5 Wed, 03 Jun 2015 20:19:39 +0000 en-US hourly 1 https://wordpress.org/?v=4.4.1 I ain’t ‘fraida no maths http://creativejs.com/2014/01/i-aint-fraida-no-maths/ http://creativejs.com/2014/01/i-aint-fraida-no-maths/#comments Mon, 06 Jan 2014 18:18:44 +0000 http://creativejs.com/?p=6021 Continue reading ]]> CodingMaths

Learn all you need to know about maths for programming with this brilliant video series from Keith Peters.

I always encourage people to learn to code and often they’ll reply that they’re “not good enough at maths”. The truth is that you don’t need very much maths to be able to program – it’s much more about logic.

That said, creative coding and particularly graphics programming can get a bit scary on the maths side. Thankfully my good friend Keith Peters has been quietly working on an amazing series of videos all about maths* for coding.

You might know Keith as Bit101 and he wrote 31 days of canvas tutorials a year or two back, as well as writing a lot of best-selling ActionScript books back in the days when Flash was still a socially acceptable pastime. Crazy, heady days.

It’s an unmissable series of videos, and he’s still making them. It’s well worth investing the time into this type of maths, particularly trigonometry and the vector maths. It’ll really improve your creative coding.

Coding Math video series on YouTube by Keith Peters

* For some reason he calls it math – singular – which obviously is weird. But don’t let that put you off.

]]>
http://creativejs.com/2014/01/i-aint-fraida-no-maths/feed/ 3
Hello Processing! http://creativejs.com/2013/11/hello-processing/ Wed, 27 Nov 2013 16:34:43 +0000 http://creativejs.com/?p=5972 Continue reading ]]> helloprocessing

Hello Processing! is a wonderful new interactive tutorial produced by the Processing Foundation as a part of Code.org’s Hour of Code initiative. Learn to code in an hour with Daniel Shiffman, who really is the best creative coding instructor around if you ask us!

The tutorials teach Processing, but a whole lot of JavaScript went into making them as interactive as they are. Ace for code editing, Popcorn.js for media-driven events and Processing.js for in-browser execution of Processing code.

The result is an interactive and high energy introduction to programming. They didn’t stop at just having the video and code samples synced up, you can even edit and run the code live as it’s being discussed. Perfect for sharing with all your non-programming friends!

It’s still in beta right now (the official release is slated for later in December) so you may find a few bugs here and there. If you do, help them out by reporting it on github.

Hello Processing!

]]>
Make a shoot-em-up in 20 minutes http://creativejs.com/2013/05/make-a-shoot-em-up-in-20-minutes/ http://creativejs.com/2013/05/make-a-shoot-em-up-in-20-minutes/#comments Wed, 08 May 2013 11:05:06 +0000 http://creativejs.com/?p=5307 Continue reading ]]> browserinvaders

Last year at the State of the Browser conference in London, in an arbitrary but fun test, I pitted the browsers against each other to see which could render the most 3D particles.

BrowserInvaders2

This year, to change it up a bit, I live coded a space invaders type game, complete with particle explosions, and invited the browser reps to compete in a short tournament.

StateOfTheBrowserSeb

The code was from the new CreativeJS games workshop, so it’s pretty simple to understand. You can get the source code on my github, and watch the video for a full (if slightly rushed) explanation.

Play the game (1-5 to change the browser type, s to restart the game)
Watch the video
Get the source code
Come to a CreativeJS Games workshop

]]>
http://creativejs.com/2013/05/make-a-shoot-em-up-in-20-minutes/feed/ 1
Painting with Pixels http://creativejs.com/2013/03/painting-with-pixels/ Thu, 28 Mar 2013 13:55:29 +0000 http://creativejs.com/?p=5185 Want to break into canvas and creative code and don’t know where to start? How about a simple drawing app that even lets you save screenshots as JPGs straight from canvas to your downloads folder? Check out our latest tutorial.

]]>
Advanced Uploading Techniques — Part One http://creativejs.com/2012/08/advanced-uploading-techniques-part-one/ Thu, 30 Aug 2012 15:18:31 +0000 http://creativejs.com/?p=4575 Continue reading ]]>

The first in a series of advanced uploading techniques, in this tutorial I discuss how to build a chunked uploader that will let you break your large files into smaller pieces using the File API. We will also look into the possibilities that chunked uploading opens for us, such as allowing users to pause and resume their uploads.

Head on over to the tutorial!

]]>
The guide to implementing 2D platformers http://creativejs.com/2012/05/link-the-guide-to-implementing-2d-platformers/ http://creativejs.com/2012/05/link-the-guide-to-implementing-2d-platformers/#comments Tue, 29 May 2012 16:00:17 +0000 http://creativejs.com/?p=4048 Continue reading ]]>
Game programmer and designer Rodrigo Monteiro (@amzeratul) has published a thoroughly in-depth guide to building 2d platformer games. In presenting the four different ways to build a 2d platform, Rodrigo does a great job of introducing the concept behind each theory without immediately giving away the actual implementation. I consistently found myself thinking in my head, “Hmm…now how would I go about solving that problem?” Much of the article is kept language agnostic, so you may be tempted as well!

A few quick takeaways and lessons learned:

  • If you’re unsure which type of platformer you want to implement, and you want to do an action game, Monteiro suggests a smooth tile-based implementation (example #2)
  • Ladders are typically one tile wide to restrict movement along the y axis (a notable exception would be the vines your climb in Mario 2)
  • Moving platforms are typically implemented using AABB (Axis-Aligned Bounding Box)—the same method for your playable character
  • Flash developers will be familiar with the concept of “bitmasking” or drawing a separate non-linear hit area used for collision detection. With this method, collisions are performed much the same way as tile-based, except that the pixels themselves are the actual “tiles”
  • When implementing physics-based engines such as Box2d, friction must often be accounted for depending on the direction of movement. In Monteiro’s words, “you’ll want friction to be high on the foot, but low on the sides.”

Go have a look for yourself! The Guide to Building 2d Platformers

]]>
http://creativejs.com/2012/05/link-the-guide-to-implementing-2d-platformers/feed/ 1
requestAnimationFrame — The secret to silky smooth animation http://creativejs.com/2012/04/requestanimationframe-the-secret-to-silky-smooth-javascript-animation/ http://creativejs.com/2012/04/requestanimationframe-the-secret-to-silky-smooth-javascript-animation/#comments Thu, 26 Apr 2012 16:04:54 +0000 http://creativejs.com/?p=3492 Continue reading ]]>
Do you often find yourself lying awake at night wondering how you, too, can get your JavaScript animations to be as smooth as those silk sheets of yours? I can’t say for certain that all of us on the CreativeJS team actually have silk sheets, but we did want to show you how to make your animations rock, so we created a page over in our Resources section dedicated to the new(ish) requestAnimationFrame API. Go take a look!

]]>
http://creativejs.com/2012/04/requestanimationframe-the-secret-to-silky-smooth-javascript-animation/feed/ 3
Day 12 — 3D pixel particles http://creativejs.com/2012/01/day-12-3d-pixel-particles/ http://creativejs.com/2012/01/day-12-3d-pixel-particles/#comments Thu, 05 Jan 2012 09:00:17 +0000 http://creativejs.com/?p=2200 Continue reading ]]>

The Christmas season is pretty much over, but before you take the tree down, and return your baubles to the musty box in the cupboard, we have one final 12 days of CreativeJS post for you.

And it’s a goodie! Today, I’m going to explain a magic formula that can figure out where a 3D point would be on your 2D canvas. Once we know that we can make some 3D pixel particles!

A 3D point has an x, y and z position, where z is how far away it is from you. If a point is at 0,0,0 then we are going to render it right in the middle of the screen. Let’s call our 3D co-ordinates x3d, y3d, and z3d.

The first part of the formula tells us how big or small things should appear at a given z distance :

var scale = fov/(z3d+fov);

Where fov is a notional field of view, in other words, how zoomed-in or wide-angled our virtual lens is1.

Now we know how big things are at that distance, we just multiply our 3D x and y by that scale factor to get our 2D x and y.

var x2d = x3d * scale; 
var y2d = y3d * scale;

If you think about it, this kinda makes sense. Let’s say our particle is 5 pixels over to the right, and it moves towards us. As it gets nearer, the particle moves further to the right in the 2D space. We’re multiplying our x3d (which is 5) by a growing scale factor to get our x2d. And our particle will move further right as it comes towards us.

There’s just one more thing though – this formula assumes that the 2D co-ordinate system also has its 0,0 point in the middle of the screen. So we need to add half the width and height of our canvas to the result to offset this.

var x2d = (x3d * scale) + halfWidth; 
var y2d = (y3d * scale) + halfHeight;

Get it? Great! You should also watch out what happens if points go behind the camera, because if you try to render them they’ll be all inverted. We’re not worrying about that in our simple code here, but if you wanted to implement that then just check to see if z is less than –fov and if it is, don’t draw it.

And that’s all there is to it. Who’d have thought it’d take so few lines of code to make a simple 3D pixel renderer?

1It’s not an actual field of view as an angle, it’s just an arbitrary value that the formula requires. I usually use around 150 – 250, but you can experiment to see what results you get.

So now if we combine it with Paul King’s day 3 post about setting pixels in a canvas, we can now colour the relevant 2D pixel for the 3D point.

So let’s make a whole bunch of 3D points! :

var pixels = []; 
for(var x = -250; x<250; x+=5) { 
	for(var z = -250; z<250; z+=5) { 
		var pixel = {x:x, y:40, z:z};
		pixels.push(pixel); 
	}
}

You can see here we’re creating a horizontal grid of 3D point objects with x, y and z properties. Here’s what it looks like when we render it :

Now let’s look at our render function, called 30 times a second :

function render() { 
 
	// clear the canvas
	context.clearRect(0,0,width, height); 
	// and get the imagedata out of it
	var imagedata = context.getImageData(0, 0, canvas.width, canvas.height);
 
	// iterate through every point in the array
	var i=pixels.length; 
	while(i--){
		var pixel = pixels[i]; 
 
		// here's the 3D to 2D formula, first work out 
		// scale for that pixel's z position (distance from 
		// camera)
		var scale = fov/(fov+pixel.z); 
 
		// and multiply our 3D x and y to get our
		// 2D x and y. Add halfWidth and halfHeight
		// so that our 2D origin is in the middle of 
		// the screen.
		var x2d = (pixel.x * scale) + halfWidth; 
		var y2d = (pixel.y * scale) + halfHeight; 
 
		// and set that 2D pixel to be green
		setPixel(imagedata, x2d, y2d, 0, 255, 60); 
 
		// add 1 to the z position to bring it a little 
		// closer to the camera each frame
		pixel.z-=1;
 
		// if it's now too close to the camera, 
		// move it to the back
		if(pixel.z<-fov) pixel.z += (fov*2);
 
	}
 
	// and write all those pixel values into the canvas
	context.putImageData(imagedata,0,0); 
 
}

So we’re iterating through each 3D point object, converting it into 2D and setting the pixel for that 2D position. Then we’re moving each point forward towards the camera by decrementing z, and once it gets too close we’re moving it to the back.

Play with it here on JSFiddle.

How about this version where we create 3D pixels in undulating waves using Math.sin(…), and we have now declared a custom Pixel3D object in which to store our 3D x, y and z.

Or this version that has pixels in a big doughnut shape (or torus if you want to sound extra posh). Note that we’re now rotating every point around the origin relative to the mouse position – using the newly added rotateX and rotateY functions in our Pixel3D object. And instead of just setting a pixel colour, we’re adding the colour values onto what’s already there (this is known as additive blending and it causes the particles on top of each other to burn out to white).

And finally, here’s a strange attractor, copied from Paul’s example from a while back. This version has a trails effect, and also a pulsating colour for each pixel based on a sine wave.

So clearly there are a few techniques in these examples that I haven’t explained in great detail, mainly to do with setting up 3D points and rotating them. But at least once you have x, y and z values for 3D points, you now know how to draw them in 2D. And for me that was the largest stumbling block to getting started in 3D.

I hope you enjoy your new 3D explorations, and I hope you’ve enjoyed the 12 days of CreativeJS! We’d love to hear what you think, so please leave a comment.

]]>
http://creativejs.com/2012/01/day-12-3d-pixel-particles/feed/ 9
Day 11 – Animating with sprite sheets http://creativejs.com/2012/01/day-11-sprite-sheets/ http://creativejs.com/2012/01/day-11-sprite-sheets/#comments Wed, 04 Jan 2012 10:00:26 +0000 http://creativejs.com/?p=2198 Continue reading ]]>

The holidays are over and we’re all back at the office getting back to the regular routine and feeling a bit like robots. No? OK, that’s maybe a stretch. Hopefully you at least like robots though, because we’re about to animate a little robot heart using sprite sheets twice: one using canvas and one using a div.

Animating with a sprite sheet is like moving a connected series of images past a set viewing area. Think of a viewmaster or a film strip if you’re old enough.

The image below shows you approximately what’s going on behind the scenes. We have one big image that contains every frame of the robot animation (the sprite sheet) and we display one at a time, moving along and down our list of images as we progress through the animation. Do this fast enough and you have animation :)

The sprite sheet

We’ll be using the same sprite sheet image (this one) for both variations. I won’t get into how to create a sprite sheet here, but there are a number of ways to make them and you certainly don’t have to put them together all by hand. I’ve used Keith Peter’s SWFSheet to export the sprite sheet I’m using here from a SWF.

First up, the canvas version

Once we’ve done our initial file set up, the first thing to do is load in our sprite sheet image. When we know our image has loaded, we set an interval to call our loop function 30 times a second, which is where everything happens.

	//load the image
	image = new Image();
	image.src = "robot2.png";
 
	image.onload = function() {
            //we're ready for the loop
            setInterval(loop, 1000 / 30);
        }

Great! we’re ready to actually make something happen. The loop function starts out easily enough with a call to clearRect(…) to clear our canvas. But what’s with that excessively long drawImage(…) function? It’s a bit ugly.

c.drawImage(image, xpos, ypos, frameSize, frameSize, 0, 0, frameSize, frameSize);

All those extra arguments are there because we are defining two different rectangles The first rectangle (xpos, ypos, frameSize, frameSize) defines the rectangle in our source image that we want to copy from. This will change every frame because we are updating the xpos and ypos values each time. The second rectangle (0, 0, frameSize, frameSize) defines where in our canvas we are drawing to. For this example that will never change. (You might also notice that both my width and height are being set to frameSize. To keep things simple, I’m using a square image area.)

Next up, we do a little bit of math to figure out exactly which part of our sprite sheet we should draw from to display the correct frame:

//each time around we add the frame size to our xpos, moving along the source image
xpos += frameSize;
//increase the index so we know which frame of our animation we are currently on
index += 1;
 
//if our index is higher than our total number of frames, we're at the end and better start over
if (index >= numFrames) {
	xpos =0;
	ypos =0;
	index=0;	
//if we've gotten to the limit of our source image's width, we need to move down one row of frames				
} else if (xpos + frameSize > image.width){
	xpos =0;
	ypos += frameSize;
}

We add our frameSize to our xpos to move along our sprite sheet horizontally (remember, our images our square). We also increment an index counter to keep track of what frame we’re on. If our index is higher than the total number of frames we have, it’s time to start over. If our next horizontal move would have us going past the width of our sprite sheet, we move down to the next row. This repeats over and over, creating our animation. Play with it here on JSFiddle.

One down!

Once more, with divs

I think you’re getting the hang of it now, so I’ll do a little less explaining for this one. We’re going to do pretty much the exact same thing except this time we’re calculating how to move the background image of a div so that the correct frame in the animation is visible.

The first notable difference is in our small block of CSS:

#anim {
	width:200px;
	height:200px;
	background-image: url(robot2.png);
}

We’re identifying our target div anim, setting its height and width (our viewable area), and assigning its background image (our sprite sheet).

Our loop function looks incredibly similar, or you might even say nicer since it doesn’t have nearly as many lines of comments. The only real difference is the first line:

div.style.backgroundPosition = (-xpos)+"px "+(-ypos)+"px";

We’re repositioning #anim‘s background image every frame. The calculations to determine the xpos and ypos values are the same as in the canvas version so the rest of the function should look very familiar. But you can see we’re using -xpos and -ypos – this is because we want to move the background image up and to the left to reveal the next frame.

So there you have it, the same sprite sheet animation two ways! Hopefully it was even a bit fun :)

And with that, we wrap up Day 11 of the 12 days of CreativeJS. Only one more to go!

]]>
http://creativejs.com/2012/01/day-11-sprite-sheets/feed/ 19
Day 10 – Drawing rotated images into canvas http://creativejs.com/2012/01/day-10-drawing-rotated-images-into-canvas/ http://creativejs.com/2012/01/day-10-drawing-rotated-images-into-canvas/#comments Tue, 03 Jan 2012 09:00:32 +0000 http://creativejs.com/?p=2195 Continue reading ]]>

The room may still be spinning after the New Year celebrations but at least after this, you’ll be able to rotate your images to counter the effects!

You probably know we have this handy canvas context function drawImage :

context.drawImage(image, x, y);

where image is a DOM image (or another canvas), and x and y is the top left of the image. There are several other optional parameters, but I’m not using them today. (You can take a look at the canvas cheat sheet we posted yesterday if you’re curious.)

What’s not that obvious is how to draw a rotated image. You’d think there’d just be a nice rotation angle built in to drawImage, right? But no, instead, you have to rotate the entire co-ordinate system before you draw stuff!

Check this example out, we already have a canvas context set up, and we have logoImage loaded and ready to use :

context.drawImage(logoImage, 50, 35);

We’re drawing our logo from the top left at 50 pixels across and 35 pixels down which gives you this :

rotated image 1

All straightforward so far, but what if we rotate our co-ordinate system first?

context.rotate(0.5); 
context.drawImage(logoImage, 50, 35);

Whoa, what happened? Well, the entire co-ordinate system rotated by 0.5 radians (roughly 30º) around the top-left corner of the canvas before we drew the image. So if you think about it, 50 across and 35 down isn’t the same as place as it used to be.

So how do we rotate our image and keep it in the same place? Well before we call rotate we need to move the origin of our canvas to where we want to draw our image, and we can do this using context.translate(x,y).

context.translate(50, 35); 
context.drawImage(logoImage, 0, 0);

The translate function moves the entire co-ordinate system; context.translate(50, 35) moves the origin across by 50 and down 35. Now if we draw our image at 0,0 it’s actually at the new position of the origin :

Remember that context.rotate rotates around the origin. So if we move the origin to the 50,35, the image will be rotated around that point :

context.translate(50, 35); 
context.rotate(0.5); 
context.drawImage(logoImage, 0, 0);

All good so far, but what if we want to rotate around the centre of the image? Well we have to move the origin into the middle of where we want to draw the image, and then draw the image up and left half its width and height.

Confused? This example will make it clearer :

// move the origin to 50, 35   
context.translate(50, 35); 
 
// now move across and down half the 
// width and height of the image (which is 128 x 128)
context.translate(64, 64); 
 
// rotate around this point
context.rotate(0.5); 
 
// then draw the image back and up
context.drawImage(logoImage, -64, -64);

So, to re-iterate, we’re moving the origin to the middle of where we want the image to be drawn, then rotating around that point, and then drawing the image left and up in our newly rotated co-ordinate system.

The only thing left to understand is radians, but we explained all about that on our day 4 post. You did see that, right? :)

One final thing: at the end of all our translating and rotating, our co-ordinate system is all screwed up and there’s no way to get it back (don’t even think about resizing the canvas to reset it!). But we can save it first :

// save the context's co-ordinate system before 
// we screw with it
context.save(); 
 
// move the origin to 50, 35   
context.translate(50, 35); 
 
// now move across and down half the 
// width and height of the image (which is 128 x 128)
context.translate(64, 64); 
 
// rotate around this point
context.rotate(0.5); 
 
// then draw the image back and up
context.drawImage(logoImage, -64, -64); 
 
// and restore the co-ordinate system to its default
// top left origin with no rotation
context.restore();

Now we know how to draw centred and rotated images, so why not package this up into a nice function?

var TO_RADIANS = Math.PI/180; 
function drawRotatedImage(image, x, y, angle) { 
 
	// save the current co-ordinate system 
	// before we screw with it
	context.save(); 
 
	// move to the middle of where we want to draw our image
	context.translate(x, y);
 
	// rotate around that point, converting our 
	// angle from degrees to radians 
	context.rotate(angle * TO_RADIANS);
 
	// draw it up and to the left by half the width
	// and height of the image 
	context.drawImage(image, -(image.width/2), -(image.height/2));
 
	// and restore the co-ords to how they were when we began
	context.restore(); 
}

Check out this example to see it in action.

It’s worth taking the time to properly understand translation, rotation and saving and restoring the draw state stack – it’s incredibly powerful. And who knows, maybe the room will stop spinning in time for tomorrow’s post. :)

]]>
http://creativejs.com/2012/01/day-10-drawing-rotated-images-into-canvas/feed/ 14