Graphical Dice

To create a graphical dice, first of all, you need to create six images that resemble six sides of a dice. Save the images as 1.jpg, 2.jpg, 3.jpg, 4.jpg, 5.jpg and 6.jpg. To randomly load the images, you need to use the img and src attributes and the random method of the Math object.

We use the following syntax to generate random integers from 1 to 6.

Math.floor( 1 + Math.random() * 6 )

Note that the Math.random() method generates a random number from 0 to a number less than but not equal to 6. Therefore, 1+Math.random()*6 generate a number from 1 to less than but not equal to 7. Therefore, Math.floor( 1 + Math.random() * 6 ) genrates integer from 1 to 6.

The script to load the six images randomly is

<script language="javascript">
function rolldice()
{ document.write ( "<img src = \"" +
Math.floor( 1 + Math.random() * 6 ) +
".jpg\" width = \"50\" height = \"50\" />");

document.writeln("<br><hr>Click on the refresh button to reload the page"); }
</script>
<input type="button" value="Roll Dice" onclick="rolldice()">

View the Graphical Dice here.