Yin Yang



This short program creates the ancient symbol describing the balance of opposite forces.

We need five and a half circles. :) Here are the dimensions:



<html>
<canvas id='myCanvaswidth='400height='300style='background-color:gray'></canvas>
<script>
let canvas = document.getElementById('myCanvas');
let context = canvas.getContext('2d');
let x0 = canvas.width / 2;
let y0 = canvas.height / 2;
 
function circle(yradiuscolor) {
  context.beginPath();
  context.fillStyle = color;
  context.arc(x0, y + y0, radius0Math.PI * 2);
  context.fill();
}
let radius = 120;
circle(0radius, 'white')
context.fillStyle = 'black';
context.beginPath();
context.arc(x0, y0, radius, -Math.PI * .5Math.PI * .5);
context.fill();
circle(radius / 2radius / 2, 'white');
circle(-radius / 2radius / 2, 'black');
circle(radius / 2radius / 8, 'black');
circle(-radius / 2radius / 8, 'white');
</script>
</html>


Let's analyze the code line by line:

[6-7] - calculate the coordinates of the center point of the Canvas
[9-14] - a function that draws a circle.
Because we will be drawing multiple circles and certain parts of code (beginning and ending the path, setting the color etc.) are the same for each circle, we can create a function that can be called by the main program.
The main program will pass the following parameters of the circle to the function:
- the y coordinate (we don't need the x coordinate because it is always in the center of the Canvas)
- radius of the circle
- fill color

[15-24] The main program:
[16] the main white circle



[17-20] black half-circle



[21] medium white circle



[22] medium black circle



[23] small black circle



[24] small white circle



And finally, a live Canvas and code you can execute and experiment with:





Next exercise: Animation
Back to main page