context.isPointInPath()

By Ben

Continuing on my journey of learning the in's and out's of HTML5's Canvas, I found myself needing to detect whether a point on my canvas was within the region of one of my multiple objects already drawn on the canvas.

At first I thought I was stuck with the only option of having to loop through each of the objects, calculating all of the co-ordinates that the object covers and then seeing if any of them tally up with another my point of interest. I hope that makes sense, it definitely took me a while to even come up with that solution. However, as I began down this route I thought there must be a better way, something I'm missing.

After some googling, I came across isPointInPath(), a function within the Canvas API which, in short, allows you to check if a co-ordinate (passed into the function) is within the current path being drawn. Perfect! The only issue is that I have been drawing my object's through the use of methods such as .drawRect() which, from what I could tell anyway, could not be used within a path. This therefore meant that I needed to redraw my object's.

In the code below, I check to see if a point is within the current path, and therefore change the colour of the object I am about to draw. This is it in it's simplest form, but you could use it to do alot more, especially when bringing mouse interactions into a Canvas piece.

context.beginPath();
            
context.moveTo(100, 100);
context.lineTo(200, 100);
context.lineTo(200, 200);
context.lineTo(100, 200);
                                    
context.fillStyle = "rgb(0, 0, 0)";
context.fill();
                    
if(context.isPointInPath(250, 250)) {
    var blockColour = "rgb(255, 0, 0)";
}
else {
    var blockColour = "rgb(0, 255, 0)";
}
                    
context.closePath();
                    
context.fillStyle = blockColour;
context.fillRect(250, 250, 5, 5);

You can also see though that I am drawing a 5x5 rectangle, starting at the co-ordinate I passed into the isPointInPath function. This means though that whilst the starting point is not in the path, another point within the rectangle could be. This leaves me the next challenge to see if I can check if any point within a path is within a point within another path. I do like to give myself challenges, don't I?

In the following demos, you can see an example of the above code in action; a point being within the path and another point being outside the path.

Mobile support for 'Responsive Web Design'

By Ben

Responsive Web Design is a hot topic in the Creative Jar offices over the last couple of months - numerous discussions have been held, and I even gave a presentation on the topic to get minds thinking and looking for opportunities to bring this into our projects. I could talk about Responsive Web Design for hours, but I won’t today - I will save that for another blog post.

Following on from these discussions, I wanted to get a better handle on the mobile support of Responsive Web Design. It is easy to get tunnel-visioned and just care about iOS users - oh no, that would be too easy, and like only supporting Chrome on the desktop. Therefore, I tested a number of the mobiles available for their support of responsive web design.

Mobile/Platform Screen variations HTML5/CSS3 support CSS3 Media Queries
iPhone 4S / iOS Landscape & Portrait Good Good
Windows 7 Landscape & Portrait Good Good
Sony Ericsson Xperia / Android Landscape & Portrait Good Good
HTC Hero / Android Landscape & Portrait Good Good
Nokia / Symbian Landscape & Portrait Average Good

Whilst it is great news that the majority of the phones I tested have good support of the technologies which make up Responsive Web Design, it isn't the end of the world if they didn't - a nice fallback of Responsive Web Design is that the standard view would be rendered. Things will be harder to navigate (as is the main reason of creating a Responsive Web Design), but not the end of the world.

Adding hover interaction to my HTML5 canvas banner

By Ben

Having finally got to grips on rotating and animating in my HTML5 canvas, I found myself having to battle my next hurdle - adding user interaction!

The basis of adding mouse interaction with a canvas banner is to track the user’s mouse co-ordinates against your canvas elements. If the co-ordinates you can then set a variable, say hoverState = true, and you can then use this to check whether an action should fire within your animation loop. You can see the resulting code at the end of this post.

Having recently finished reading Rob Hawkes’ book on ‘Foundation HTML5 Canvas For Games and Entertainment’ I knew the basis of how I was going to achieve this - my problem? The animation I actually want to achieve.

If you take a look at our current services banner, you will notice that when you hover over one of the service circles, there is a smooth animation which introduces a secondary, slightly transparent circle which grows outwards. “Easy!” I thought, I would just increment the radius of my a new circle when the user hovers over the primary circle! And in essence it would be that simple, but having elements in the canvas which is all transparent is where it gets complicated and frustration ensues.

Problem 1: Overlapping transparent elements means double the opacity

As I said, the first thing I tried was to just introduce a secondary circle upon hover of which the radius increases with each iteration of the animation. The problem which resulted from this was the secondary circle could be seen through the semi-transparent primary circle - which was far from ideal when what is intended to be smooth animation results with a jarring jump in opacity.

Overlapping opacity problem

Problem 2: Stroke width is not ‘outside’ the element.

After a bit of thinking, I realised what I was trying to recreate was in essence a border around the primary circle and I remembered canvas allows you to stroke a path/element. However, when I tried applying a stroke to the circle of which the width increased with each iteration of the animation, I ran across the problem that the stroke width is not ‘outside’ the element.

If you imagine applying a stroke to a layer in Photoshop, you specify whether it appears inside the layer, outside, or centre. Canvas in-fact applies a stroke similar to that of a centred stroke, which results in the below:

Centre stroke problem

Solution: Combining stroke and increasing radius

My solution was to combine the best of 2 methods I tried. The first step was to increase the stroke of the secondary circle, then with each iteration the radius of the circle increases. This results in us faking the effect of a stroke on the outside of the element.

$(window).mousemove(function(e) {
    illustrationOffset = servicesIllustration.offset();
    illustrationX = Math.floor(e.pageX - illustrationOffset.left);
    illustrationY = Math.floor(e.pageY - illustrationOffset.top);
   
    dX = tmpService.x - illustrationX;
    dY = tmpService.y - illustrationY;
    distance = Math.sqrt((dX*dX)+(dY*dY));
    if(distance < tmpService.radius) {
        tmpService.serviceHoverIn = true;
        $(servicesIllustration).css("cursor", "pointer");
    }
    else {
        if(tmpService.serviceHoverIn) {
            tmpService.serviceHoverIn = false;
            tmpService.serviceHoverOut = true;
            $(servicesIllustration).css("cursor", "default");
        }
    }
});

if(tmpService.serviceHoverIn || tmpService.serviceHoverOut) {
    context.strokeStyle = tmpService.hoverInnerColor;
    context.lineWidth = tmpService.hoverInnerStrokeWidth;
    var radius = tmpService.radius + (tmpService.hoverInnerStrokeWidth/2);
    context.beginPath();
    context.arc(tmpService.x, tmpService.y, radius, 0, Math.PI * 2, false);
    context.closePath();
    context.stroke();
    context.lineWidth = 1;
    if(tmpService.serviceHoverIn && tmpService.hoverInnerStrokeWidth < tmpService.hoverInnerRadius) {
        tmpService.hoverInnerStrokeWidth++;
    }
    else if(tmpService.serviceHoverOut && tmpService.hoverInnerStrokeWidth > 0) {
        tmpService.hoverInnerStrokeWidth--;
    }
    else if(tmpService.serviceHoverOut && tmpService.hoverInnerStrokeWidth == 0) {
        tmpService.serviceHoverOut = false;
        tmpService.hoverInnerStrokeWidth = 0;
    }
}

You can see the results of the above code here. My next step is to duplicate the service object for multiple services, and then add some click interaction!

Rotating and animating in HTML5 Canvas

By Ben

In my mission to reproduce the interactive banner on our services banner, I came across the need to animate arrows around the edge of an outer circle. Having previously animated circles around the edge of another circle, I thought it would be easy - oh how I was wrong.

My first step was to implement the same code I used for the circles, which worked great, however the circles did not rotate and follow the path as intended.

I then decided to use the .rotate() method when drawing the arrows - however as I was rotating the canvas, the starting co-ordinates for the arrow had therefore shifted and also everything drawn afterwards would also be rotated, resulting in a very interesting result when running the code:

It took some head-bashing, but I finally realised that I would need to use a few more methods to get the result I wanted:

  1. .save() & .restore() - before doing anything, I decided to save the state of the canvas so that I can restore it after drawing the arrows, and mean that everything drawn afterwards would be as intended.
  2. .translate() - before rotating the canvas, I realised that I should shift the starting point of the canvas to the point at which I want to draw the arrow. That way after I rotate the canvas, I can just draw it at 0, 0 and the arrow will be in the correct place.

My resulting code is below, which you can see a running demo of here.

topArrowX = tmpService.x + ((tmpService.radius + tmpService.hoverInnerRadius) * Math.cos(tmpService.arrowAngle*(Math.PI/180)));
topArrowY = tmpService.y + ((tmpService.radius + tmpService.hoverInnerRadius) * Math.sin(tmpService.arrowAngle*(Math.PI/180)));

context.save();
context.translate(topArrowX, topArrowY);
context.rotate(tmpService.arrowRotation*(Math.PI/180));
drawArrow(0, 0);
context.restore();

bottomArrowX = tmpService.x + ((tmpService.radius + tmpService.hoverInnerRadius) * Math.cos((tmpService.arrowAngle + 180)*(Math.PI/180)));
bottomArrowY = tmpService.y + ((tmpService.radius + tmpService.hoverInnerRadius) * Math.sin((tmpService.arrowAngle + 180)*(Math.PI/180)));

context.save();
context.translate(bottomArrowX, bottomArrowY);
context.rotate((tmpService.arrowRotation + 180)*(Math.PI/180));
drawArrow(0, 0);
context.restore();

Animating in HTML5 Canvas

By Ben

Continuing my research and development into HTML5 Canvas. Having previously tried to create a HTML5 Canvas animation, and failing, I set myself the task of trying again. This time with the aid of Rob Hawkes' 'Foundation HTML5 Canvas For Games and Entertainment'.

The basis of animating in HTML5 Canvas is a simple 3 step looped process; updating everything that needs to be drawn (e.g. moving the position of your elements), clearing the canvas and then redrawing using your updated variables/positions.

A simple animation would be to move a box along a single line:

$(function() {
var canvas = $("#canvasElement");
var context = canvas.get(0).getContext("2d");
var canvasWidth = canvas.width();
var canvasHeight = canvas.height();
var x = 10;
var y = 10;
function moveBox() {
// Clears out our canvas to redraw
context.clearRect(0,0, canvasWidth, canvasHeight);
// Draws our box
context.fillRect(x, y, 10, 10);
// Increases our x variable by 1 each time this function is called, moving our box along the horizontal axis
x++;
// Calls our moveBox() every 33 milliseconds, causing the whole process to loop
setTimeout(moveBox, 33);
}

// Call the function once to call to start things off
moveBox();
});

Hopefully the comments in the code above explains what is happening within each step of our process. And that's it! You can view the demo here.

Having achieved a simple animation, I wanted to take things further, and using more guidance from my bible that is Rob Hawkes' book, I was able to create circles animating around another circle - the basis of something we want to work on and develop further for the Creative Jar website. You can view the demo and source code here.

Hype for Mac - a review

By Ben

HTML5 is very much at the top of everybody’s interest list - people are talking about it, and now, starting to implement it into their sites.

Aside from the endless capabilities of making your website more semantic using the new HTML5 tags (being the semantic-nazi I am), the introduction of the <canvas> element had me very excited. I had never been a big fan of Adobe Flash, but before now there hasn’t been much more of an alternative.

Whilst <canvas> isn’t the main topic of this blog post, if you wish to read more about HTML5 canvas, I urge you to read HTML5 Doctor’s post, ‘An introduction to the Canvas 2D API’.

HTML5 <canvas> can look incredibly daunting to get up and running with, and during my R&D time, I wanted to experiment and see if I could reproduce the interactive banner found on our services page, but this time using <canvas> rather than traditional HTML, CSS3 and jQuery.

Hype for Mac's Element Inspector

To cut a long story short, and so we can get to the good bit, I stumbled upon Hype for Mac and was intrigued as to how easy it would be to create a HTML5 interactive piece using a desktop interface, and without writing a single line of code. This blog post outlines my experiences with Hype for Mac, and hopefully help people get an understanding of what to expect out of it.

Setting up the initial view

The first step I took was to set up the starting point of my interactive banner - this also gave me a good opportunity to get a handle on the the app’s interface and see what was achievable.

True to Mac’s native apps, Hype for Mac uses an ‘Element Inspector’ to set various properties. For example, position, dimensions, radius (to create circles), fill (background images, colours), text formatting, shadowing, opacity.. the list goes on!

However, when setting up the background of the ‘scene’, I found that whilst I could apply a background colour, I was not able to set an image as the background. To get around this I had to import the image as an element, and move it to overlay the background. Not the most ideal way, but nothing I’m sure a future version could fix.

One major plus that the interface had for me was the ability to drag elements around the ‘scene’ and the apps intuitiveness to help lock items to a grid or in relation to other elements. Maybe that’s just me, but simple minds and all that.

Another thing to note that I found useful when creating the elements within the scene, the user interface will prompt you if you are applying a property which a major browser does not support - this way preventing any surprises further down the line!

It wasn’t long before I had set up my initial view, and was ready to animate.

Implementing animations & my problems with it

For a first-time user, applying animations to your elements can prove a mystery - straight away there isn’t a lot to go on in terms of getting started. However, after watching some quick videos on the Hype for Mac website, everything fell into place and you could simply run away with it.

In short, you can either set your own keyframe start/end points using the timeline at the bottom and using the Element Inspector just change properties that you wish to see animate. Even easier, the app offers a recording function which will automatically capture properties which have changed and generate the timelines required when you click stop. I was very impressed with this, and hats off to the creators for making it so easy.

However, nothing is without it’s problems and there were a few things which I found irritating:

Layer ordering

As you can see from my initial view (above), a lot of the main elements overlap each other and as part of the animation I would have liked to bring elements ‘to the front’ when hovered over. Much like you see in any picture editing software such as Adobe Photoshop, the layer ordering is depicted by the order the elements appear in your scene (see screenshot). So I was a bit disappointed to find that layer/element ordering was not a property you could animate.

Duplication of effects

When creating an animation for each of the elements, I found things becoming very repetitive. For example, the hover in/out animations for each of the main circles in my banner are the same, just with a different position. Hype for Mac does not seem to offer any help in duplicating animations on elements, you are left with just repeating steps of animating properties numerous times, a bit tedious after a few.

‘Jump to’

You can fast forward or click to a certain time within the timeline, however it would be nice for Hype for Mac to implement a ‘Jump to’ function which allows you to - well, jump to a certain time within the timeline. A nice animation within my project was the arrows found in the other circles would slowly follow the path of the circle round - completing a 360degree rotation. In theory, I would want my arrows to slowly move, perhaps 1degree for every second - however, I could not jump to 360 seconds in the timeline to apply the animation end point.

The output

At the end of the day, we want our interactive element to be the best it could be - and whilst the ease of use that Hype for Mac offers, I was disappointed with the outcome.

The first thing you notice, and something your end users will also notice is the animations appear chuggy, and not smooth. If you wish your interactive elements to be realistic, believable and earn the user’s trust, you don’t really want your animations to feel slow or judders.

As I mentioned before, a part of my project was for the arrows to slowly rotate round the main circles, to make this nicer we would want this animation to continuously loop. So if the user were on the page for longer than 360 seconds, the arrows would not just stop at the end, but start going around again - giving a much more polished interaction. However, I could not find a way within Hype to set animation to loop - again rather disappointing that something that would be easy to implement from a code point-of-view could not be achieved by using the app.

Being me, I couldn’t resist a peek under the hood and see what was being exported by our app. I was shocked to see that our markup just consisted of

elements with JavaScript performing the styling and animating. Where is the HTML5? Why not use the brand new <canvas> element and be truly HTML5?

Aside from that, the output from Hype for Mac was lightweight and easy to implement within a web template.

View a working demo of the (unfinished) interactive banner here.

In conclusion, whilst I ran into a lot of problems with the effects I wanted to achieve, and my issue with the lack of semantic markup and not using all of HTML5’s potential, Hyper for Mac offers a quick and easy way to add interactivity to your website.

Internet Explorer 9: What's round the corner

By Ben

I thought that hell would have frozen over long before I ever blog about a Microsoft product, let alone Internet Explorer, let alone looking forward to it, but here I am - blogging about Internet Explorer 9, the latest soon-to-be-released version of Internet Explorer.

Even though the much improved Internet Explorer 8 was only released over a year ago in March 2009, Microsoft are already hard at work (and not too far off releasing) version 9 of their controversial browser application. You can even download the latest preview of the browser from their test drive microsite.

It was also announced that the first official beta of Internet Explorer 9 will be launched on September 15th 2010, that's just 3 weeks away from today.

Having just switched to Google Chrome after years of being a Firefox fanboy, there is no worries of me jumping ship to Internet Explorer as my browser of choice anytime soon. However, the main reason for my excitement is the possibilities it opens up when developing websites.

Though we hate to admit it, Internet Explorer is probably one of the most influential browsers in terms of the technologies we decide to build our websites in. Due to the large market share, we have to make sure that what we build is compatible. This meant that using exciting new technologies such as CSS3, and HTML5 was not as possible as the more standards compliant and frequently updated browsers like Mozilla Firefox, Google Chrome and Opera.

As of the fourth preview release, Internet Explorer has surprisingly good support for CSS3 selectors (43 out of 43) and properties, scores 93/100 on the Acid3 test – a much higher score than the 20/100 IE8 receives, a faster JavaScript engine and supports new HTML5 tags such as <video> and <header>.

With the end of Internet Explorer 6 coming more of a reality day by day, we are likely to see a big surge in people upgrading and therefore allow us to use these new technologies which the latest browsers are now supporting.

As an industry we are steaming forward into a more standardised playing field, meaning our web designers and developers are happier and the web will become a much more competitive and exciting venture.

Semantic HTML, the h1 tag, and SEO

By Ben

As designers who code and developers, we like to shout about writing semantic HTML as a standard in our work, but a lot of the time we then get asked "What does Semantic HTML actually mean?"

In short, it means the HTML tags we use imply meaning to the content, rather than presentation. This in affect means our HTML is cleaner, easier to understand, more accessible for screen readers, and should no custom CSS be applied to the document – the content is still readable in the manner it was intended.

Some examples of these would be using: <p> tags for our paragraphs of text; <address> for, you guessed it, an address; <h1>, <h2>, <h3> for headings and sub-headings – increasing the number as the heading decreases in the page's hierarchy.

When writing semantic HTML, we also tend to use <em> and <strong> tags rather than <i> and <b>. Earlier we stated we want to use HTML tags which imply content, not presentation. In this case <em> and <strong> imply that the content should be emphasised and have strong meaning, whereas if we were to use <i> and <b>, they are a presentational instruction for the content to be italicised and bolded – which can just as easily be done through CSS, further separating visual style from content.

The above are just a small handful of the tags we can use, and with the continuing development of HTML5 we are seeing even more tags created to make our templates even more semantic, removing the need of copious amounts of <div> tags (a <div> being just a container, implying no meaning to its content).

Headings and SEO

On the topic of semantic HTML, the conversation about the use of headings and its impact on the SEO (Search Engine Optimization) of a page is often raised – and one tag which causes confusion and a plethora of opinions, is the <h1> tag.

The <h1> tag is intended for the most important heading on the page. Most of the time designers and developers wrap the site title and/or logo in the <h1> tag as they deem this piece of information as the most important. However some SEO specialists disagree, and would rather the current page's or blog post's title should be within the <h1> as this holds the most weight about the information that is on the page. So who is right and who is wrong?The answer is there is no right or wrong way, and there is a lot of grey area, just personal preference and different SEO strategies – hence the reason for difference in opinions and implementations.

Personally, I agree that the page title should be in the <h1>, and the site title should then be within a link to the site's homepage.

But what about the home page, that doesn't necessarily have a title? After a recent discussion with other developers we came up with a simple solution. This solution can also be found in the recently released Twenty-Ten default theme for WordPress 3.0.

On the home page, the most important heading on the page is the site title, correct? Well on this page, we wrap the site title and/or logo within a <h1> tag, giving it the highest priority on the page in terms of structure, and search engines will recognise this.

When moving onto a subsequent page, the <h1> tag will then be used for the page title as discussed earlier, and the site title will then be wrapped with a link.

This might require a bit more code from the server side point of view, but the result is a lot more efficient for your semantic HTML, and it will definitely make SEO consultants and specialists happy.

@font-face fonts: What are they and where do I find them?

By Ben

@font-face

For many designers and front-end developers, another hot topic of conversation is the @font-face CSS declarations which now allow us to use any font we like in our websites as if it was installed on the users computer.

Before we were restricted in which fonts we could use, relying solely on the fonts which most users would have installed on their computers; Arial, Verdana, Times New Roman, Courier New – to name just a few.

Now we can upload the required font files to our server, reference them in our CSS and we are all set.

I bet I know what you are thinking – what about browser support? It goes without saying that everything we do is affected in someway or another by the browser support of the features we want to use. The good news is that @font-face is currently supported by all major browsers: Firefox 3.5+, Chrome 4+, Safari 3.2+, Opera 10.1+, even Internet Explorer 6+.

But hang on, isn't Internet Explorer 6 (IE6) over 10 years old? Yes it is, and even though @font-face is officially a new declaration within CSS3, it was originally planned for CSS2 and therefore was implemented by IE6 – when it came to @font-face being removed from the spec (for reasons I am not quite sure of), support was never removed from IE6.

For more information on the code required and how to create a bulletproof @font-face declaration which is cross-browser, check out Paul Irish's article on 'Bulletproof @font-face syntax'.

However, though in theory @font-face allows us to use any font we like – we are restricted by the font's licenses whether font embedding or sharing is permitted. This is mainly down to the fact that if we are linking to a font file in our code, it means anybody can just download the font and then is it on their computer.

Therefore, it is important to check if the font you want to use is permitted to be used on the web.

Alternatively, there are a few resources which I have come across and found extremely useful in getting @font-face fonts and making sure they are permitted to be used.

  • Font Squirrel

    The Font Squirrel website lists 'hundreds of @font-face font kits' which are 100% free for commercial use. The kits provide all the necessary fonts and code needed to be implemented.

  • Fontspring

    If you wish to have even more of a selection of font, and have a more unique feel to your website - Fontspring provides purchasable fonts along with @font-face licenses, all very reasonable prices.

  • FontDeck

    Whereas the last 2 services allowed you to select individual fonts, and in the case of FontSpring, purchase @font-face licenses, FontDeck allows you to pay a subscription and have full access to their library of fonts to use on your website. Great alternative if you want to use a lot of fonts, or as a freelancer you love to use unique fonts for all your clients' websites.

  • TypeKit

    Like FontDeck, TypeKit allows you to pay a monthly subscription allowing access to their library of fonts and use them on your website. The higher level your account type is, the more fonts you can use and the more website domains you can use the fonts on.

So when you are next designing a website, or even as a client looking to have a website designed, look into the possibility of using more custom fonts to get more aesthetics and edge on the web. Stand out, be at the forefront of new technologies and trends.

iPad App of the week: Sorted

By Ben

Sorted: App icon

The iPad has been released for just over a month now in the UK, and we are now starting to see some fantastic apps released to the App Store and though it may seem we are talking a lot about Apple's latest gadget, we thought it would be nice to take a look at our favourite iPad apps.

In my desperate search for a simple to do list app which didn't have the £11.99 price tag that the popular app Things has, I found this week's app of the week: Sorted. For 59p, it surely is a bargain.

Sorted allows you to maintain multiple lists, great for if you are running different projects, or just list to separate your items:

Sorted: My lists view

You can also set a list item's due date and priority:

Sorted: Add due date and prioritise item

Using the tabs across the top, you can filter your list by List, Priority, Date and Completed:

Sorted: Completed view

If items need a bit more information, you can enter some comments for the item:

Sorted: Add comments to a list item

Sorted for the iPad makes your to do list easy. The user interface is clean and feels great on the iPad. The creators have also tried to make use of the core iPad actions such as swiping your finger across an item will mark it as complete, where this could have just been a simple button.

Having used the app for a while now, my only fault is it proves quite difficult to delete an item. The action is supposed to be easy in that you swipe the item using 2 fingers. Either I am doing something wrong, or I can never get it to work and just end up marking the item as complete.

Overall, this is a nice and well thought out app. There is room for improvement, such as the delete item item, and maybe introducing a badge count on the app's icon would be nice – to see how many items are due soon, or overdue. Though for 59p, I cannot really complain!