Playing with the New Canvas Element

Full adoption of HTML5 is just round the corner, and with more and more browser-vendors making HTML5 top-priority these days, it's time, I think, we should take a look at some of the cool things we can do with the new <canvas> element. So what is it? Well although I don't profess to be an expert, I should tell you that it is much like a canvas in the real world, in that you can draw on to it using code, you can stick pictures on to it, and more interestingly you can manipulate these pictures. But a wonderful aspect of the new element is that it isn't really that hard to get to grips with, and the code for creating some interesting stuff is relatively simple to learn. So instead of writing a load of uninteresting and complex code out, I thought I might just tell you of a very simple idea that I, like many others, had.

After playing with the element for a short while I suddenly realised what I could do - make a really simple drawing application! I know not the most far out or original idea, but I liked the idea. So I set about creating it. Here's the demo. So as you can see it is really simple, but you might think that there would be a lot of code to create it. Actually the code that listens for the mouse click and drag actually occupies more space than that of the canvas code. Let's have a look. Here is the HTML.

<div id="controls">
<input id="brushRadius" type="text" value="4"></input>
<input id="brushColour" type="text" value="000000"></input>
<div id="palette"></div>
</div>

<canvas id="blank">
Your browser doesn't support this feature.
</canvas>

So at the top you can see the controls section, which allows the user to input two variables - the stroke width and the colour - both very simple. Below this is a small box which will have it's background colour set to that of the current brush colour later on. Now the Javascript. Notice the text between the canvas tags, this will be displayed if the browser doesn't support the canvas element.

var canvas = document.getElementById('blank');
	
var ctx = canvas.getContext('2d');
				
$("#blank").attr('width',$(window).width());
$("#blank").attr('height',$(window).height());

ctx.lineWidth = 4;
			
var mousedown = false;	
			
$("#blank").mousedown(function(e){					
	mousedown = true;						
});
				
$("#blank").mouseup(function(e){					
	mousedown = false;	
});
				
$("#blank").mousemove(function(e){		
	var x = e.pageX;
	var y = e.pageY;
		
	if(mousedown){				
		ctx.lineTo(x,y);
		ctx.stroke();
	}else {		
		ctx.moveTo(x,y);				
	}					
});
								
$("#brushRadius").change(function(){
	ctx.closePath();
	ctx.lineWidth = $("#brushRadius").val();
	ctx.beginPath();
			
});
				
function updateColour(){				
	var colour = $("#brushColour").val();

	ctx.closePath();
	ctx.strokeStyle = "#" + colour;
	ctx.beginPath();
					
	$("#palette").css("backgroundColor","#" + colour);					
}
				
$("#brushColour").change(function(){ updateColour(); });
$("#brushColour").keydown(function(){ updateColour(); });

Right, it may look like a lot, but bear with me. At the top we declare the canvas and make it into a 2D area to draw onto, we also declare a variable called "ctx" (short for context) to hold the canvas element, thus making the code more efficient. Then we set the canvas to fill the entire window and make a variable called "mousedown" and set it to false, notice we also set the brush width to 4 as a default value. This will be altered whenever the user clicks and hold the mouse button down by the following functions. Next we use the mousemove function to detect movement, and check to see if the mouse button is down. If it is then we draw a line from the previous location, to the current location and stroke it, otherwise we simply move it.

After this we listen for the #brushRadius input to be changed and then alter the line's width based upon the value inputted. The reason we close and then open the line, is to stop the changes affecting the previously drawn lines. Finally we have a function to update the colour. This function makes a variable to store the inputted value, closes the line, updates the line's colour, and then starts it again. And then it updates that box I told you about earlier, to reflect the inputted value. This function is then executed using the following two functions that fire whenever the input is altered.

So there is a lot to take in there, but after you familiarise yourself with it, you should begin to understand the simplicity of the code. The canvas element can do so much more than what I've shown you here today, and I would encourage you to get to grips with it. I would suggest a trip to the Mozilla developer's centre and go through the tutorial. It really is nice to have such power reasserted using such simple code - enjoy!

Flash, and all that Jazz

So it seems that the web is alight with talk of Adobe's ubiquitous Flash platform because of some rather interesting decisions taken, and points proposed by Apple's Steve Jobs, but what are the main points, beyond the simple "it crashes Macs" argument? Well in the article I hope to set out a few of my thoughts on the subject, just so that I don't go forgetting them!

Flash is, for all intents and purposes, okay. And I say that as a user, not a web designer/Mac users/fanboy. Some Flash websites created by the professional are mind-bogglingly awesome and never cease to amaze me, for example 2Advanced - the industry leaders are utterly fantastic at what they do. They've taken Flash to a whole new level, using powerful techniques that make for a stunning result (their website that is). And I admire that, because I think mastery of any platform should be applauded. And at this point in time there are certain things that can only be done with Flash - complex online games, and rich web applications to name just a few. And making a website in Flash obviously has advantages over other methods - for one you can ensure it will look the same across all platforms, and the Flash player plugin is installed on something like 95% of the world's computers, so your in safe hands.

But, and it's a big but; I will respect you more as a designer if you don't use Flash. Why? Well, about two years ago when I was new to the whole jQuery thing, I remember seeing a scrolling animation in a sidebar. It was basically displaying a load of pictures and just going up and down. When I first looked at it I though, yeah that's Flash, but when I right clicked it, I was presented with my normal contextual menu, and I was amazed! Now I realize that that sounds awfully mundane, but back then I was inspired. Since then I have found myself finding that many rich web experiences have nothing to do with Flash, and I love it! So when it comes to me, I wouldn't use Flash in a design, and that's just because I'm not a fan.

Now this is coming from someone that's tried to get into Flash. I learned my fair share of ActionScript, and got to grips with the software, but after a while I just found the allure of jQuery to enticing to resist, and so I dumped Flash. But lets talk about what the big guys are saying.

No Flash on the iPhone

Right, so we've gotten used to this lacking feature now, and being honest, have there been many times when your day has been ruined by this lack of support? Not for me (maybe I'm just lucky), in fact if anything it has improved my web experience - blocking out those pesky Flash banners that flash every colour of the rainbow. Don't get me wrong, it would be nice to have Flash on the iPhone OS, but at the end of the day, when so many things that are done in Flash, can be so easily replicated with some nifty Javascript and HTML5, why bother?

No Flash-generated Apps

Now this was an interesting move by Apple, but you can see where they are coming from. They would open to slowed development if the software didn't stay up to date, but I don't truly believe that this is the reason it has been disallowed. Really? I think old Steve Jobs just wants to see the death of Flash, and this nail in the coffin will serve to simply reduce the list of features on platform. But to be honest I think it was the right move, not because of what Jobs said in his open letter, but because I believe that if a developer really wants to get their app on the iPhone they will just pay an iPhone developer, and the result of this? Better quality apps. Think about it. Do you seriously think that Adobe's planned distribution converted would have lived up to the creation of a dedicated app? Definitely not.

At the end of the day, this has got a lot to do with Apple wanting total control over the applications heading for the app store, and nobody (bar Apple) is denying that. But it's a good thing if Apple wants to keep the apps in the app store high quality? But then is there really any competition to Flash? Do I hear Silverlight? Yeah, about that...

Just to clarify, I'm not someone what hates or bashes Flash. Nor do I love Apple in every respect. But what I think this whole thing has shown, is that many people don't like Flash. Even Microsoft is backing Apple in this, and I for one can't wait to just use HTML5; and with developers creating more and more fantastic apps every day, powered only by HTML5, I think the future is one not without Flash, but with less of a ubiquity.

What do you guys think? Am I just talking rubbish, or does Apple have a point?

Element Organization

So what do I mean when I say element organisation? Well put simply I'm referring to the way in which we group HTML elements in terms of either tables, divs or HTML5. Now to be honest I believe that tables these days are somewhat obsolete and I wouldn't even bother teaching it to new web designers so the objective of this article is to show you that you don't need tables! Let's begin with the trusty <div> element. We're just going to create a nice layout that could perhaps replace a table! (Just bear in mind that this is a rather basic tutorial).

Dividing, or div, elements are really easy to understand and once you get using them, you won't ever go back! So lets create a simple page header using div elements.

<div id="header">
  <h1>My Website</h1>
  <div class="nav">
    <ul>
      <li>Home</li>
      <li>About</li>
      <li>Contact</li>
    </ul>
  </div>
</div>

So there we have some code that will create our header, for the moment lets just focus on the <div> elements. So you'll see that we create these elements by using the standard convention of the less than and greater than symbols and then entering the word "div" which just tells the browser that it is a dividing element. We then have a few parameters that we can set. First off we can give the element an ID which we can later reference in our CSS or JavaScript, so you would only give and ID to something like a header or a main content box (basically just a name that isn't going to get used again). Then we can give it a class which we can use over again and acts much like and ID. Lastly we can actually apply styling to individual divs, e.g. <div style="display:none"><div>. This comes in handy when we want to show and hide elements on the fly, but you should know that in-line styling isn't something I advocate.

Lastly you will notice that we end our element with <div>. Now in the code above you'll notice that we have some elements in between the opening of the div and the closing of it. This is because the whole point of a div to to group elements together so that you can manipulate them later. However you can have an empty div that you can apply styling to if that's something you're interested in doing.

At this point in time I only create with divs, however in the near future it will soon become the norm to use HTML5 to group your elements. Now you can already do this, just as long as you are aware that it isn't yet fully supported. But for when that time comes you should have an idea on how you might style the same sort of code with HTML5. Now I'm not going to cover the in-depth areas of HTML5 just so as to stick to the topic in hand. So here is the code that would replicate the stuff you see above, but in HTML5.

<header>
  <h1>My Website</h1>
  <nav>
    <ul>
      <li>Home</li>
      <li>About</li>
      <li>Contact</li>
    </ul>
  </nav>
</header>

Now what you will notice about this is that it looks slightly cleaner and somewhat resembles XML, you'll see that in HTML5 many of the most commonly used names for divs have just been turned into actual tags; something which I'm sure I'll come to love.

And that's it for that little segment. To finish I'd like to go over another basic topic regarding using IDs and Classes when naming your elements. First IDs.

An ID, or identification, is used when we want to reference a singular element on our page; it is a name that can be used only once and can be added to elements like so - id="myElement" - that was easy wasn't it? Now when we want to actually reference an element with an ID in either CSS or JavaScript/jQuery we have to use the hash (or pound) symbol - # - e.g. #myElement { display:none; } in CSS and $("#myElement").hide(); in jQuery. So you give IDs to elements such as the header and main content box so that you can group a number of other elements and apply certain styling to them all.

Next classes. These are used to "class" elements together and more importantly can be used as many times as you like! They can be added to elements like so - class="left" - and you should know that you can add multiple classes to singular elements like so - class="left hidden". This is really useful when you want to have styling that you can apply to whatever elements you might need to, for example you might want to float all elements with a class of "left" to the left. But you might also want to hide some elements using the "hidden" class, I think you can properly see just how useful this can be. Now when you want to manipulate elements with certain classes we simple have to use a full stop (or period), e.g. .left { float:left; } in CSS and - $(".hidden").hide(); - in jQuery.

So I hope this article goes some way towards the eradication of table-based layouts on the web, and I hope you found it useful as a reference about IDs, Classes and divs!