Working with the Canvas element
One of the biggest problems I’ve been having with taking the KnitProject to the next level is drawing with JavaScript. This is where the Canvas element comes in.
If you’re an IE user you can leave right now, Unless you download some plugin, none of this will work. Frankly I don’t care about IE and don’t intent to support it. If and when IE descides to support the Canvas element (or you download the plugin) then you can come back and play with the big boys.
So, the first step is to place the canvas tag on your webpage. Something like <canvas id="display" width="150" height="150"></canvas> This will give you a place to draw. You can place some text or an image inside the tag for a fallback for those with old browsers.
Next, you need to get the 2d context for this Canvas. (2d is the only context available right now.) I use jQuery, so adjust accordingly if you don’t. (Although you really should, jQuery rocks!) something like var display = $("#display")[0].getContext("2d"); will do nicely.
Then you just have to draw on it. That’s it!
Ok, that’s not really it. There’s two really good tutorials here and an interactive game here. I plan on using Canvas it to develop the next version of KnitProject. The first step is simply knowing where and when the mouse clicks on the canvas.
First up, just change color on click, and tell us the (x,y) position of the mouse relative to the canvas (I don’t care about mouse clicks anywhere else.)
Go ahead, try it out.
Detect Mouse Click
So how did I do this?
First get the context and sent an event to the mouse down. On that event, get the position of the mouse, minus the position of the canvas element (made easy due to jQuery). Display it and tell it to flip colors! Pretty simple. The most important thing is how we found out the (x,y) positions on the element.
Here’s the code!
var display; //This is going to be our Drawing Context
var isRed = true; //Should we Draw red or green?
$(document).ready(function(){
//Get the context
display = $("#display")[0].getContext("2d");
//Register MouseDown Clicks
$("#display").bind("mousedown", onMouseDown);
//Draw it
draw();
});
function onMouseDown(evt){
//Redraw the display
draw();
//Get the mouse cords on the Canvas
var offset = $("#display").offset();
var x_pos = Math.floor(evt.pageX - offset.left);
var y_pos = Math.floor(evt.pageY - offset.top);
//Display it
$("#text").html( "("+ x_pos +","+ y_pos +")" );
}
//Draw on the Canvas
function draw(){
if( isRed ) {
display.fillStyle = "rgb(255,0,0)";
isRed = false
} else {
display.fillStyle = "rgb(0,255,0)";
isRed = true;
}
display.fillRect(0,0,150,150);
}
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
