The wonders of trigonometry using canvas

I have long wanted to start learning HTML5 canvas, and finally decidedly took up it. The first thing I decided to try was displaying various shapes using standard lines in “pseudo 3D”. Once upon a time I spied a very interesting way in the winamp plugin and decided to implement it myself. In 2002, I did this in C ++, but now it's time to port this miracle to HTML and JavaScript.

I decided to immediately use the jCanvasScript shell to more easily use the functions associated with Canvas, and explorercanvas to support the result in IE8.

Surprises began almost from the very beginning. I wanted the canvas to be stretched to full screen (more precisely, to the entire browser window), but since canvas sizes are set only in pixels had to be tricky already starting with the insertion of the canvas tag. Strictly speaking, you can set percentages, but then the image inside will be stretched. Here's what I had to do something like this:

$(window).load(function(){
	$("").attr({
		'width': $('body').width(),
		'height': $('body').height(),
		'id': idCanvas
	}).appendTo("body");
});


I started with a spiral that rotates in different planes. Because I did it earlier in C ++, then I took the "workpiece" and translated their logic into JavaScript. In order to display a graph of a function, you must enter a function that calculates the X and Y coordinates of each point. To display the rotation you need a function that changes the variables with which the angle of inclination in the planes depends on each frame.
image

Initialization Code:
var settings = {
	n : 500, // num of points
	tx: 0, ty: 0, tz: 0,
	x1: 0, y1: 0, z1: 0,
	dtx: 1, dty: 1, dtz: 1,
	dx: 2, dy: 2, dz: 2,
	clCol: 9, dir: 1
}


Code executed from frame to frame:
tx += 0.01*dtx;
ty += 0.01*dty;
tz += 0.01*dtz;


Code executed in each frame:
x1 = cos(tx+dx*i*PI)*i;
y1 = sin(ty-dy*i*PI)*i;
z1 = sin(tz-dz*i*PI)*i;
x = x1/(2+z1/2);
y = y1/(2+z1/2);

The variable i varies from 0 to n. The variables x and y will vary from 0 to 1 - this is convenient for translating into the coordinates of the screen depending on its width and height.

Having written one HTML file with a spiral, I decided to experiment with other shapes, as it’s not convenient to produce one file for each figure; I created an HTML file with a built-in editor of pieces of code (Initialization, Frame, Points and mixing variables). The latter sometimes allows you to portray such bizarre figures that I had not guessed to make. Pieces of code are inserted using eval and with an extended scope, which allows you to use trigonometric functions without writing the name of the Math object.

Well, when the editor was created, of course, the need arose to save and load what was done. See in action here. I think it will be useful for studying the behavior of trigonometric functions. CodeMirror

used to highlight code

Also popular now: