Client Side

All the fancy frizz

3D Box using the HTML5 Canvas API

Written by: Peter Fisher on April 1, 2012
Tagged under: , ,
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn
HTML Hyper Text Markup Language

HTML is the basic building blocks of all web pages

I posted recently about the HTML5 work shop I went to at DevWeek and mentioned that I was going to write more about the subject when I had explored some of the API’s.  Well today I was playing with the canvas API and would like to demonstrate how to use paths.
Below is simple 3D box generator which creates 6 sides of a 3D cube. The box is transparent so you can see each of the sides.  The example doesn’t use any JavaScript frameworks and will alert the user if their browser does not support the canvas API.

Have a go and let me know what you think

Use the controls to build the 3D box. Once done, hit reset to start over!

Controls

How its done

First we need to make sure the browser supports the HTML5 canvas API.

As I mentioned earlier I don’t want to use any frameworks, so this is how to detect if a browser can handle canvas without using modernizr
[crayon lang=”javascript”]
if(!document.createElement(“canvas”).getContext){
alert(“canvas not supported in your browser”);
}
[/crayon]
Next we need to plot the six sides of the box like so:

[crayon lang=”javascript”]
// Top
topCoords = new Array(
“100,0”,
“200,50”,
“50,50”,
“0,0”
);

// Bottom
bottomCoords = new Array(
“50,200”,
“200,200”,
“100,100”,
“0,100”
);

// Left side
leftCoords = new Array(
“0,100”,
“50,200”,
“50,50”,
“0,0”
);

// Right side
rightCoords = new Array(
“100,100”,
“200,200”,
“200,50”,
“100,0”
);

// Front side
frontCoords = new Array(
“50,50”,
“200,50”,
“200,200”,
“50,200”
);

// Read side
rearCoords = new Array(
“100,0”,
“100,100”,
“0,100”,
“0,0”
);
[/crayon]
There are four functions which control the setup, building and reseting of the box.

[crayon lang=”javascript”]
/**
* Sets up the canvas
* Enables controls
*/
function setUp()
{
_canvas = document.getElementById(“output”);
_cube = _canvas.getContext(“2d”);

_cube.lineWidth = 1;
_cube.lineCap = “square”;

_cube.strokeStyle = “#0011aa”;
_cube.fillStyle = “rgba(0, 0, 150, 0.5)”;

var controls = document.getElementById(‘controls’);

for (var i=0;i{
controls.elements[i].disabled = false;
}

stage = document.getElementById(‘stage’);

}
[/crayon]

What we are doing here is:

  • Getting the canvas element
  • Setting the context to the variable _cube
  • Setting the line width, cap and stroke/fill styles
  • Looping over all the controls and making sure they are all enabled

[crayon lang=”javascript”]
/**
* Calls drawSide() passing in the coordinates based on the side chosen
* Disables the control button so the same side cannot be drawn again
*
* @param string side the side to draw
* @param dom element e the current dom element of the form
*/
function buildCubeSide(side, e)
{
//input = document.getElementById(e.id);
e.disabled = true;
switch(side)
{
case ‘front’:
drawSide(frontCoords);
break;
case ‘rear’:
drawSide(rearCoords);
break;
case ‘left’:
drawSide(leftCoords);
break;
case ‘right’:
drawSide(rightCoords);
break;
case ‘top’:
drawSide(topCoords);
break;
default:
drawSide(bottomCoords);
break;
}
}
[/crayon]
Here we are disabling the button once its been pressed and then calling the drawSide function with the relevant coordinate array

[crayon lang=”javascript”]

/**
* Draw a side of the cube
* @param array coords the coordinates for the panel
*/
function drawSide(coords)
{
//The starting positon is allways the last coordinate
startFrom = coords[3];
startCoords = startFrom.split(“,”);

_cube.beginPath();
_cube.moveTo(startCoords[0],startCoords[1]);
for(var i=0; i< coords.length; i++)
{
val = coords[i].split(“,”);
_cube.lineTo(val[0],val[1]);
}
_cube.stroke();
_cube.fill();
}
[/crayon]

The above function draws a side of the box. As the coordinates will always make up  four sides of a rectangle/square the last position will always meet  back at the start position. So we can use coords[3] as the startFrom position.

After each of the coordinates have been processed the stroke and fill methods of the context is called to paint the side.

[crayon lang=”javascript”]
/**
* Resets the canvas
* Sets up the stage
*/
function resetStage()
{
_canvas.width = _canvas.width;
setUp();
}
[/crayon]
The last function resets the stage when the reset button is pressed. This sets the canvas width to its self and wipes which results in wiping any context from the canvas. Finally the setUp function is called again to activate the controls etc…

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Peter Fisher is a web developer working in Gloucester UK. Founder of the digital agency Websomatic, author of this blog and the HowToCodeWell Youtube channel. Peter has over ten years of web development experience under his belt

Read all about Peter Fisher

Leave a Reply

Your email address will not be published. Required fields are marked *