SiteExperts.com Logo Home | Community | Developer's Paradise | Jobs
User Groups | Site Tools | Site Information | Search

Inside Technique : Mega Scratch
By Jon Perry

This is my latest and greatest Scratch variant capable of allowing a viewer to scratch off an image to reveal yet another image! This is achieved by creating a series of clipped images, each 1/16th of the original, and each faded by an alpha filter.

Demonstration (IE5+)

The Code

This code is heavily optimized. The images are absolutely positioned in fixed places on the screen. This has allowed me to use numbers instead of variables, but the code is harder to adapt.

<HTML>
<HEAD>
<TITLE>Mega Scratch</TITLE>
<STYLE>
IMG {position:absolute;width:100;height:100;top:100}
</STYLE>

The image pre-loading routine.

<SCRIPT>
sc=new Array('crown.jpg','x.jpg','seven.jpg','diamond.jpg','ruby.jpg','magic.jpg');
img=new Array();
for (i=0;i<6;i++) {
img[i]=new Image();
img[i].src=sc[i];
}

The mega() routine creates 16 images, each one containing a unique clip of the top layer image. Once the image is created, we attach an event to capture onmouseover events, and then append it to the body element.

function mega() {
for (h=0;h<4;h++)
for (v=0;v<4;v++) {
newImg=document.createElement("IMG");
newImg.id='I'+eval(h*4+v);
newImg.style.left=350;
newImg.style.filter='alpha(opacity=100)';
t=v*25;
l=h*25;
r=l+25;
b=t+25;
imSq='rect('+t+','+r+','+b+','+l+')';
newImg.src=document.images[2].src;
newImg.style.clip=imSq;
newImg.attachEvent('onmouseover',fade);
document.body.appendChild(newImg);
}
}

fade() controls the appearance of a given clip.

function fade() {
eS=event.srcElement;
if (eS.filters[0].opacity>0) eS.filters[0].opacity-=10;
}

rnd() returns a random number between 0 and 5. Used to determine random images.

function rnd() {
return Math.floor(Math.random()*6);
}

This loads the images. If the top image and bottom image are the same, the effect is nullified, so the do...while loop countermands this.

function megaimgld() {
document.images[0].src=document.images[1].src=img[rnd()].src;
do document.images[2].src=img[rnd()].src;
while (document.images[2].src==document.images[0].src)
mega();
}

remove() removes all the top layer, so that we can create a fresh layer safely.

function remove() {
for (i=0;i<16;i++)
document.body.removeChild(document.images['I'+i]);
}
</SCRIPT>
</HEAD>

Fairly obvious HTML.

<BODY onload="megaimgld();">
<H1 align="center">Mega Scratch</H1>
<IMG SRC="" STYLE="left:225">
<IMG SRC="" STYLE="left:350">
<IMG SRC="" STYLE="left:475">
<BUTTON 
   STYLE="position:absolute;top:250;left:350;width:100;height:100" 
   onclick="remove();megaimgld();">Again</BUTTON>
</BODY>
</HTML>

Have Mega fun!

Be sure to also check out another version of Speed Scratch Cards.


Jon Perry is a freelance Author and Programmer from the UK. Contact him at perry@globalnet.co.uk and visit his web-site http://www.users.globalnet.co.uk/~perry.

Page 1:Mega Scratch
Page 2:Demonstration (IE5+)