Animated menu buttons with html5 canvas.


Watching baseball yesterday they had many different video effects for the various text element boxes. Many of them are based on a sweep of light or a path of light across the element to bring attention to it. Canvas can do these effects very easily … below is the source code and the example is on http://wsmith-animations.tk/

By having the button animation be part of the page that means that interaction with another element of the screen can start the event.
<style>

/* button needs to have position relative to hold overlaying content */

.button {

width:160px;

height:45px;

background:#800;

color:white;

position:relative;

}

/* button divides both start at zero top and left inside the .button class divide */

.button div {

position:absolute;

top:0px;

left:0px;

padding:0px;

}

/* text is offset in the button note item CSS overrides class CSS */

#textOffset {

top:10px;

left:10px;

}

</style>
<div>

<div> <canvas id=”canvas1″ width=”160″ height=”45″>

<!– canvas width sets both CSS and width for javascript (they can be different) –>

</canvas>

</div>

<div id=”textOffset” >

Item

</div>

</div>
<script >
// set up loop
function newFrame() {

frame++;

if (frame > 300) { frame = 0; }

// slow fade: lower alpha by 16 every 25 milliseconds

var TheImage = ctx1.getImageData(0, 0, 160, 45);

var jpgdata = TheImage.data;

for (var i = 0, n = jpgdata.length; i < n; i += 4) {

jpgdata[i+3] = jpgdata[i+3]-16;

if (jpgdata[i+3] < 0) { jpgdata[i+3] = 0 }

}

ctx1.putImageData(TheImage, 0, 0);

// draw box at frames 101 though 120 progressive from left to right based on frame count.

if (frame > 100 && frame < 121) {

var left = (frame – 101) * 8 ;

ctx1.fillStyle = “rgb(0,0,255)”;

ctx1.fillRect(left,0,8,45);

}

setTimeout(newFrame, 25); // max fps is 40

}

// test for canvas setup and begin animation loop if exists.

var Canvas1 = document.getElementById(‘canvas1’);

if (canvas1.getContext){

var ctx1 = canvas1.getContext(‘2d’);

var frame = 0;

newFrame();

}
</script>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: