November 3, 2020

Coding3 - 2D Graphics

In this part, I will record some methods of drawing 2D graphics through canvas, and also briefly state how to draw graphics, through polar coordinates and Cartesian coordinates.


1.Visualisation Wave

First, we can learn something from the audio visualization in the previous chapter.

We buffered the audio sample data into an array, and then passed the corresponding value to the draw function to draw on the canvas.

2.Coordinates

We usually use the Cartesian coordinate system to draw graphics.

Wiki - Cartesian_coordinate_system

If we need to draw curves other than straight lines, or try to do more things, we may need to use other coordinate systems, such as polar coordinates.

In polar coordinates, we only need to pass an angle and a radius to draw a sector and a circle. Of course, in the canvas, we can use functions such as arc or p5 circle ellipse.

In order to draw polar coordinates, we need to do a coordinate conversion:

1
2
x = (r * cos( θ ))
y = (r * sin( θ ))

θ is radians and r is the radius, so we can express any point on the Cartesian coordinate system through two new parameters.

Similarly, we can also use Cartesian coordinates to express polar coordinates:

1
2
3
tan( θ) = y / x
θ = tan-1 (y / x)
r^2 = x^2 + y^2

Now we can go back to the audio waveform we talked about earlier. We can also draw the waveform by polar coordinates, as in the following example:

https://mimicproject.com/code/a7e2f833-49c8-d71f-99bd-19a993321e7e


This is another example of mine:

https://mimicproject.com/code/c1d6ebc6-d7dd-79b4-3b81-1ef6eab57473


3.John Whitney Senior

John Whitney Senior is an important figure in computer graphics. He created great works in 1957:

https://www.youtube.com/watch?v=4CZfSc6nJ8U

In this movie in 1961, he created the first computer animation:

One of John Whitney’s favourite algorithms is The Rose of Grandii. There is an introduction article on mathworld.

The main code to implement it is this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let canvas = document.querySelector("canvas");
let context = canvas.getContext("2d");
canvas.width = 800;
canvas.height = 600;

var radius = 100;
var penSize = 5;
var positionX = 200

var draw = function() {

for (var i = 0; i<500; i++) {

context.fillRect(positionX+Math.cos(i*Math.sin(i))*radius,positionX+ Math.sin(i *Math.sin(i))*radius,penSize,penSize);
}
requestAnimationFrame(draw);

}

requestAnimationFrame(draw);

I also want to share some excellent work of my classmates:

by@Minyue Lin

by@Nan

About this Post

This post is written by Siqi Shu, licensed under CC BY-NC 4.0.