Interactive Javascript Canvas 00

I’ve played a lot with physics experiments in flash and moving more to javascript and canvas for simple things I wanted to test it out with some physics and animations. I’ve been curious to find out how the performance compares. Obviously this will depend on the browser, but the browsers that do support canvas should be able to handle some interactive physics animations.

I have this project I keep coming back to, it’s been in as2 and then in as3 and has have multiple faces. But the gist is there are a bunch of circles or balls and they float around in a specified area. There are physics “controls” exposed to the user and they can control the velocity of the balls, the gravity, air friction or drag, elasticity and they can even grab a ball and throw it across the stage (canvas). Here are a couple iterations of this: BFA Portfolio, Current Interactive POG Portfolio, Dribbble likes, Lastfm scrobbles.

I’m going to rebuild the basic functionality via javascript. I have had this on my list of things to explore for months now, in fact, ever since I saw Keith Peters go through his month long javascript exploration, he had a specific example that made me think I really needed to do it. I started and then life happened… But now I’m ready to start documenting my progress and trying to share what I’ve learned.

I’ll start with his initial example he titles JavaScript Day 27: Mouse Part II.
View my version here: interactive physics animations via javascript & canvas.

[cc lang=”javascript”]
$(function () {
var canvas, context, width, height, x, y, radius = 25, clickX, clickY, drag = false;

canvas = $(“#canvas”)[0];
context = canvas.getContext(“2d”);
width = canvas.width;
height = canvas.height;
x = width / 2;
y = height / 2;
draw();

$(“#canvas”).mousedown(function (event) {
var dx, dy, dist;
dx = event.pageX – this.offsetLeft – x;
dy = event.pageY – this.offsetTop – y;
dist = Math.sqrt(dx * dx + dy * dy);
if(dist < radius) { drag = true; clickX = dx; clickY = dy; } else { drag = false; } }); $("#canvas").mouseup(function (event) { drag = false; }); $("#canvas").mousemove(function (event) { if(drag) { x = event.pageX - this.offsetLeft - clickX; y = event.pageY - this.offsetTop - clickY; draw(); } }); function draw() { context.clearRect(0, 0, width, height); context.beginPath(); context.arc(x, y, radius, 0, Math.PI * 2, false); context.fill(); } }); [/cc]