article

Playing with canvas

I had a lot of fun the last few days while playing with the canvas element and now is the time to present the script I came up with.

Waves !

To test a few of the functionalities provided with the canvas I've decided to create a background generator. Currently, it generates multiple waves and you can set a few things like the number of oscillations or the shadow effect. Before going in details, I invite you to go a test it right away: The Wallpaper Generator
As you can see, this generator is limited in generating waves. In the future I may implement more generators as listed in the menu.

{ how }

I'll be mostly explaining and showing the Javascript code for this WebApp, I'm assuming you already know some HTML and the main thing you will need is a canvas element:
You may also want to set a default size and an id to it:

Resizing the Canvas

Sadly the styling of the element won't be enough to resize the canvas. In the app I'm not really resizing the element, I'm just recreating a new canvas with the desired dimensions. This requires the canvas to be contained in a parent we can refer to in our script, I'll be using #canvas-cont as the parent id.
function generate(){
	// getting the size from the inputs
	var sizex = parseInt($("#sizex").val(),10);
	var sizey = parseInt($("#sizey").val(),10);
	
	// replacing the canvas with a new one
	$("#canvas-cont").html('');
	
	// redefining the main variables
	canvas = document.getElementById("canvas");
	ctx = window.canvas.getContext("2d");
	height = sizey;
	width = sizex;
}

Randomizing

To get interesting outputs I've decided to be able to randomize some inputs. As you can see you can manage the randomness of certain inputs by setting an interval. Here's two Javascript functions I've made to generate random umbers (and also an unused function to set the drawing to a random colour):
function rdm(min, max){
	return ((Math.random()*(max-min))+min);
}

function rdmint(min, max){
	return Math.floor((Math.random()*(max+1-min))+min);
}

function rdmColor(){
	ctx.fillStyle = "rgb("+rdmint(0,255)+","+rdmint(0,255)+","+rdmint(0,255)+")";
}

The Waves

I've created a general function to draw a wave:
function wave(ys,nb,ht){
	ctx.beginPath();
	for(var x=0;x<=width;x++){
		var y=Math.sin(x*nb*Math.PI*2/width)*ht+ys;
		ctx.lineTo(x,y);
	}
	ctx.lineTo(width,Math.sin(x*nb*Math.PI*2/width)*ht+ys);
	ctx.lineTo(width,height);
	ctx.lineTo(0,height);
	ctx.lineTo(0,width,y);
	
	ctx.fill();
}
The function takes 3 arguments. ys is where the wave should start on the y axis, nb is the number of waves you will have and ht is the height of the waves.
After drawing the wave, we finish the shape which will fill the bottom part of the canvas with the same colour.

On the Side

In order to create this WebApp I've used Bootsrap and a few plugins with jQuery. I'm using Slider for Boostrap and Colorpicker for Bootstrap allowing user-friendly inputs.
comments powered by Disqus