sics of the canvas element. How to draw to it, create loops which redraw it allowing animation, and in the end, wind up with a basic playable "Snake" game.

Advertise here with BSA

Learning Canvas: Making a Snake Game is a post from CSS-Tricks

]]> Note from the editor: The following is a guest post by Nick Morgan aka Skilldrick. I don't know much about canvas, so it's a pleasure to be able to share an article about a current web technology that is outside of my current range of knowledge.

Of all the new elements being added in HTML5, I think canvas is one of the most exciting. Canvas gives you a fixed-size drawing surface and a selection of basic commands to draw on that surface.

In this tutorial I'm going to show you how to make a simple snake game using canvas. You know, like you used to get on your Nokia phone.

Making the canvas and our first rectangle

Let's make a <canvas> element, and draw something on it. In this code snippet, I've created the canvas element, set its dimensions, and
drawn a pink rectangle on it.

The first thing to note here is that we don't call drawing methods on the canvas, but on its drawing context. Currently canvas only has one context, which we acquire by calling .getContext('2d').

First we set the fill style of the context, which takes the form of a CSS colour, e.g. #f00 or rgba(100, 100, 100, 0.5). Then we call fillRect, which takes the coordinates of the top-left hand corner of the rectangle, its width, and its height. Notice that x/y coordinates in canvas start at the top-left hand corner of the canvas - x increases to the right and y increases downwards.

Making a game loop

Now, canvas wouldn't be too much fun if you couldn't make things move. The standard way to make movement in a game is with the game loop. This is a function that gets called at a fixed interval to update the state of the game and display the changes.

I've started adding in some organisation to the code now. To keep the global scope clear, I'm only using one global variable, called JS_SNAKE. I'm then making an object called game which will hold all the game-related functions. game is an object with one public method, init, and a number of private variables and functions.

The loop basically does three things. First, it updates the game's state (in this case adding 2 to the x position and 4 to the y). Then it updates the display, taking into account the updated state. Finally, it calls setTimeout, passing the gameLoop function and the time to wait until calling it again.

This results in a function called every 500ms which will draw a rectangle in a different position each time. We need to call clearRect each time to clear the canvas, otherwise we'd be drawing over the previous frame each time.

Drawing a snake

Now comes the fun bit: drawing the snake. The snake is a collection of square blocks. Each frame we add a new head and remove the tail, thus moving the snake forward.

The snake object has two public methods, advance and draw. advance moves the snake one square to the right, and draw actually draws the snake to the canvas.

advance makes a copy of the head of the snake, moves it forward by 1, then adds the new head to the front of the position array and removes the tail (using unshift and pop, respectively).

draw calls an internal function, drawSection, which takes a block position and draws a square. At the beginning of draw we save the context, and at the end restore it. Saving the context saves its previous settings, so any changes we make can be reverted. In this case, I want to change the fillStyle to #33a, but I want it to revert to whatever it was before when draw has finished.

Moving the snake

We now need to hook up the keyboard so we can control the snake. I'm not going to go into detail on the code, but it's fairly straightforward.

There's a new function called in game.init() which sets the event handlers. So far, the only event we care about is keydown. If the key pressed is any of the arrow keys (keycodes 37, 38, 39 or 40), then we tell the snake to set a new direction.

setDirection checks to see if the new direction is valid. This is to stop going back on yourself, e.g. pressing left when you're travelling right. If the new direction is valid, then it sets nextDirection to the new direction. This is then used in advance so we know where the new head position should be.

Adding an apple

Now the snake needs something to eat, so let's give it an apple.

There's not much to this, except we're drawing a circle for the first time. To draw a circle in canvas, you need to start a new path, then draw a circle, and then fill the path. To start the path, call beginPath() on the context. To draw the circle call arc() on the context. arc takes 6 arguments, the x coordinate of the centre, the y coordinate, the starting angle, the finishing angle, and a boolean indicating whether to draw clockwise or not. The angle is measured in radians, and 360° is 2 * pi radians.

Finishing it off

Now that you know the basics you can view the source code of the final snake game and see what's
going on. It adds the technicalities of collision detection and score-keeping.

(For those playing at home, remember to click into the canvas area so that it can capture your keyboard events. It's presented here in an iframe which cannot receive events from the outside page.)


Advertise here with BSA

Learning Canvas: Making a Snake Game is a post from CSS-Tricks

]]>
http://css-tricks.com/9876-learn-canvas-snake-game/feed/ 29 Sprite Cowhttp://www.spritecow.com/ http://css-tricks.com/9878-sprite-cow/#comments Wed, 22 Jun 2011 03:16:07 +0000 Chris Coyier http://css-tricks.com/?p=9878

Making a really good CSS sprite image usually isn't trivial work. There are all kinds of tools to help with it. My favorite of them has been SpriteMe. I describe my typical workflow for using that here. Sprite Cow might be my new favorite though, can't wait to try it. With it, you design your own sprite (♥) and you use the sweet Sprite cow interface to get precise CSS background positions for the different parts of it.…


Advertise here with BSA

Sprite Cow is a post from CSS-Tricks

]]>
Making a really good CSS sprite image usually isn't trivial work. There are all kinds of tools to help with it. My favorite of them has been SpriteMe. I describe my typical workflow for using that here. Sprite Cow might be my new favorite though, can't wait to try it. With it, you design your own sprite (♥) and you use the sweet Sprite cow interface to get precise CSS background positions for the different parts of it.

Direct Link to ArticlePermalink


Advertise here with BSA

Sprite Cow is a post from CSS-Tricks

]]>
http://css-tricks.com/9878-sprite-cow/feed/ 0
//AN_Xml: re it out in a few seconds. Like, go to Google, type in "for loop PHP", click on a promising result, copy and paste, then alter it.

//AN_Xml:

I'm mostly a front-end guy, but I'm essentially a professional programmer. Isn't that ridiculous and embarrassing? Meh.

//AN_Xml:

//AN_Xml:

I'm in and out of a lot of different languages in any given day. A for loop is different in all of them. Here they are:

//AN_Xml:
for i in 1..5
//AN_Xml:  puts i
//AN_Xml:end
//AN_Xml:
for (i = 0; i < 5; i++) {
//AN_Xml:  console.log(i);
//AN_Xml:}
//AN_Xml:
for ($i = 1; $i < 5; $i++) {
//AN_Xml:  echo $i;
//AN_Xml:}
//AN_Xml:
@for $i from 1 through 5 {
//AN_Xml:  .n-#{$i} { color: red; }
//AN_Xml:}
//AN_Xml:
- (1..16).each do |i|
//AN_Xml:  %div #{i}
//AN_Xml:
for i in [1...16]
//AN_Xml:  console.log(i)
//AN_Xml:

They are all different. None are very difficult to understand, but the for loop is probably the simplest construct you'll need to write in a language, so you can imagine it gets worse.

//AN_Xml:

So what.

//AN_Xml:

All those languages have perfectly good reasons for why they do that the way they do. It is a minor inconvenience to maneuver the correct characters into place to get them to do the job.

//AN_Xml:

What matters is:

//AN_Xml: //AN_Xml:

Nevermind the syntax, it's the spirit that counts.

//AN_Xml:


//AN_Xml: //AN_Xml:

The Syntax vs The Spirit is a post from CSS-Tricks

]]> //AN_Xml: http://css-tricks.com/syntax-vs-spirit/feed/ //AN_Xml: 53 //AN_Xml: //AN_Xml: //AN_Xml: Front End Ops //AN_Xml: http://www.ianfeather.co.uk/presentations/front-end-ops/ //AN_Xml: http://css-tricks.com/front-end-ops/#comments //AN_Xml: Wed, 08 Jan 2014 15:26:04 +0000 //AN_Xml: //AN_Xml: //AN_Xml: //AN_Xml: http://css-tricks.com/?p=159910 //AN_Xml:

As Alex Sexton laid out, it's a thing. More and more people will be hired to do it specifically and organizations will start thinking of it as an important piece of the pie. These slides by Ian Feather help explain what that might look like.

//AN_Xml:

Direct Link to ArticlePermalink


//AN_Xml: //AN_Xml:

Front End Ops is a post from CSS-Tricks

]]>
//AN_Xml: As Alex Sexton laid out, it's a thing. More and more people will be hired to do it specifically and organizations will start thinking of it as an important piece of the pie. These slides by Ian Feather help explain what that might look like.

//AN_Xml:

Direct Link to ArticlePermalink


//AN_Xml: //AN_Xml:

Front End Ops is a post from CSS-Tricks

]]>
//AN_Xml: http://css-tricks.com/front-end-ops/feed/ //AN_Xml: 0 //AN_Xml:
//AN_Xml: //AN_Xml: When To Use The Button Element //AN_Xml: http://css-tricks.com/use-button-element/ //AN_Xml: http://css-tricks.com/use-button-element/#comments //AN_Xml: Wed, 08 Jan 2014 02:32:19 +0000 //AN_Xml: //AN_Xml: //AN_Xml: //AN_Xml: http://css-tricks.com/?p=159789 //AN_Xml:

You use it when, uhm, you want a button on your page that users can click, right? Well, unfortunately it's a bit more complicated than that. It's not too bad though, let's figure it out.

//AN_Xml:

//AN_Xml:

It looks like this:

//AN_Xml:<button> //AN_Xml: Do Something //AN_Xml:</button> //AN_Xml:

What's the most common result of clicking something on a website? Moving to a new URL, like you would clicking a link (an <a href="/example/"></a>) element).

//AN_Xml:

The <button> element, by itself, can't do that. There have …


//AN_Xml: //AN_Xml:

When To Use The Button Element is a post from CSS-Tricks

]]>
//AN_Xml: You use it when, uhm, you want a button on your page that users can click, right? Well, unfortunately it's a bit more complicated than that. It's not too bad though, let's figure it out.

//AN_Xml:

//AN_Xml:

It looks like this:

//AN_Xml:
<button>
//AN_Xml:  Do Something
//AN_Xml:</button>
//AN_Xml:

What's the most common result of clicking something on a website? Moving to a new URL, like you would clicking a link (an <a href="/example/"></a>) element).

//AN_Xml:

The <button> element, by itself, can't do that. There have been various conversations about allowing "href anywhere" over the years, but nothing has came of it.

//AN_Xml:

Clicking on a button does do something though, when used in its natural environment...

//AN_Xml:

Button is a Form Element

//AN_Xml:

Web forms have submit buttons. You might think of that like this:

//AN_Xml:
<form action="/" method="post">
//AN_Xml:  <input type="submit" value="Submit">
//AN_Xml:</form>
//AN_Xml:

A <button> element in a <form>, by default, behaves identically to that submit input above.

//AN_Xml:
<form action="/" method="post">
//AN_Xml:  <button>Submit</button>
//AN_Xml:</form>
//AN_Xml:

However gross the UX, forms can have reset buttons as well. You can duplicate that behavior by changing the default submit type to reset.

//AN_Xml:
<form action="/" method="post">
//AN_Xml:  <button type="reset">Reset</button>
//AN_Xml:</form>
//AN_Xml:

Clicking that button will clear all the other inputs (and textareas) with the parent <form>.

//AN_Xml:

Buttons can have content

//AN_Xml:

The primary reason for using a <button> is that it has both and opening and closing (</button>) tag. Which means there can be stuff inside. A common use case would be something like:

//AN_Xml:
<button>
//AN_Xml:  <img src="tiny_birthday_cake.png" alt="">
//AN_Xml:  Submit
//AN_Xml:</button>
//AN_Xml:

While an input can be <input type="image">, this mixed content would be hard to pull off.

//AN_Xml:

As far as I can tell, there is no limit to what kind of content you can put in a button, so feel free to get real weird with it. Pseudo elements can be used too.

//AN_Xml:

Let's leave styling <button>s for another day, but different browsers generally have a special style they apply to buttons. You'll want to either leave that alone so the default comes through, or remove it thoroughly so your new styling can be consistent across browsers.

//AN_Xml:

Let's consider: "if a button doesn’t have a meaningful href, it’s a <button>"

//AN_Xml:

I said recently that I enjoyed that sentiment. That's what kicked off this article for me. At the time, I was thinking of how I enjoyed the semantics of it. As in:

//AN_Xml:
<a href="#0">
//AN_Xml:  I'm kinda sick of doing this for buttons.
//AN_Xml:</a>
//AN_Xml:

There is no meaningful href there. The 0 is just there so it doesn't jump the page, because ID's can't start with a number.

//AN_Xml:

Chances are, HTML like the above means: I'm going to make clicking that do something with JavaScript. Somehow that feels better than a <div> whatever, because you get the cursor change and whatever else default styles.

//AN_Xml:

If you don't like those meaningless href's, a <button> can seem like a nice alternative. But unfortunately outside of the context of a <form>, a <button> is equally meaningless.

//AN_Xml:
<button>
//AN_Xml:  Outside of a <form>, I'm just as useless.
//AN_Xml:</button>
//AN_Xml:

But <button> feels better anyway

//AN_Xml:

Even if a <button> doesn't do anything outside of a form without the help of JavaScript, it still feels better for things you can click that do stuff other than change pages. A bogus href link definitely doesn't feel right.

//AN_Xml:

Alright. Let's insert it with JavaScript then.

//AN_Xml:

That's probably the best solution. If JavaScript is required for the clickable-thing to do anything at all, it might as well not even be there at all unless JavaScript runs. We can do:

//AN_Xml:
// 1. Create the button
//AN_Xml:var button = document.createElement("button");
//AN_Xml:button.innerHTML = "Do Something";
//AN_Xml:
//AN_Xml:// 2. Append somewhere
//AN_Xml:var body = document.getElementsByTagName("body")[0];
//AN_Xml:body.appendChild(button);
//AN_Xml:
//AN_Xml:// 3. Add event handler
//AN_Xml:button.addEventListener ("click", function() {
//AN_Xml:  alert("did something");
//AN_Xml:});
//AN_Xml:

You could easily have "button adding" be a part of your JavaScript workflow.

//AN_Xml:

When links make more sense

//AN_Xml:

If there is any kind of href you could put on that link that makes sense, by all means, use an anchor. Even if you override that behavior with JavaScript. That's progressive enhancement at it's finest. For instance:

//AN_Xml: //AN_Xml:

If nothing makes sense, insert the button with JavaScript.

//AN_Xml:

Accessibility concerns

//AN_Xml:

Let's say using an anchor link does make sense. After you give yourself a nice little back-pat for being good at progressive enhancement, there is accessibility to consider as well.

//AN_Xml:

You might be like, I got this!

//AN_Xml:
<a href="#meaningful" class="button" role="button">
//AN_Xml:  I'm good
//AN_Xml:</a>
//AN_Xml:

But you aren't out of the woods yet. MDN covers it well:

//AN_Xml:

Warning: Be careful when marking up links with the button role. Buttons are expected to be triggered using the Space key, while links are expected to be triggered through the Enter key. In other words, when links are used to behave like buttons, adding role="button" alone is not sufficient. It will also be necessary to add a key event handler that listens for the Space key in order to be consistent with native buttons.

//AN_Xml:

Get that? You activate links and buttons with different keys, so consider that.

//AN_Xml:

Go forth and uhm, make clickable things correctly.

//AN_Xml:


//AN_Xml: //AN_Xml:

When To Use The Button Element is a post from CSS-Tricks

]]>
//AN_Xml: http://css-tricks.com/use-button-element/feed/ //AN_Xml: 94 //AN_Xml:
//AN_Xml: //AN_Xml: //AN_Xml: