HTML 5 Canvas – Writing Random Characters

November 22, 2013 6:43 am Published by Leave your thoughts

Here’s a little tutorial of HTML5’s Canvas + JavaScript to generate random fours.

Check out the demo!

First we’ll need a Canvas element.

<canvas id="myCanvas"></canvas>

In the head section of the document add

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(function(){
	init();
        //in here we set the width and height of canvas to whatever the available screen resolution is
        //using innerHeight and innerWidth
	$('#myCanvas').attr("height", window.innerHeight);
	$('#myCanvas').attr("width", window.innerWidth);
	w = $('#myCanvas').width();
	h = $('#myCanvas').height();
});

var context;
var w = 0;
var h = 0;
var x=0;
var y=0;
var col =0;
function init(){
        //init sets the canvas and starts an interval to be called every 10 milliseconds
	context= myCanvas.getContext('2d');
	setInterval(drawFour,10);
}
function random_hex_color()
{
	/* get random red, green, and blue from 0 to 255 */
	var randomred = 00;
	var randomgreen = 00;
	var randomblue = 00;
        //blue is not randomized here because i only wanted shades or red and green to add blue shades, simply add a third case statement.
	switch(col){
		case 1:	
			randomred = Math.floor(Math.random() * 255);
			col=2;
			break;
		case 2: 
			randomgreen = Math.floor(Math.random() * 255);
			col=3;
			break;
		default:
			col=1;
			break;
	}
	/* convert each decimal number to hexadecimal */
	var hred = new String(randomred.toString(16));
	var hgreen = new String(randomgreen.toString(16));
	var hblue = new String(randomblue.toString(16));
	/* pad with 0 if necessary
	(e.g. make sure to output 05 instead of just 5) */
	hred = String('00'+hred).slice(-2);
	hgreen = String('00'+hgreen).slice(-2);
	hblue = String('00'+hblue).slice(-2);
	return '#'+hred+hgreen+hblue;
} 

function drawFour(){
        //this is the function that gets called on interval.
        //here x, y, fontsize, alpha, and color are randomized then drawn on the canvas with fillText()
	x = (Math.random()*w);
	y = (Math.random()*h);
	var fontsize = (Math.random()*75);
	var randomalpha = Math.random()*1;
	context.fillStyle=random_hex_color();
	context.font = fontsize + "px Arial";
	context.fillText("4",x,y);
	context.globalAlpha = randomalpha;
}
<script/>
Tags: , , , , , , ,

Categorised in: ,

This post was written by admin

Leave a Reply

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