(Context View)

(Outside View)

Position: x: , y: ; angle: °; circle radius:

I draw the heart by rotating the drawing context 45° and drawing one square and two circles. The two circles have a radius of 40 pixels. Once I choose the radius of the circles, I know the dimensions and positions of all three shapes. The side length of the square is 80 pixels and its top left corner is at (-40, -40), putting its center at the origin of the context. The center of one circle is at (-40, 0) and the center of the other circle is at (0, -40).

Here is the code used to draw my heart:

ctx.fillRect(-40, -40, 80, 80);
 
ctx.beginPath();
ctx.arc(-40, 0, 40, 0, 2 * Math.PI, false);
ctx.fill();
 
ctx.beginPath();
ctx.arc(0, -40, 40, 0, 2 * Math.PI, false);
ctx.fill();

Changing the size of the heart means changing the eight values highlighted in green. That’s not too much work, but it was still enough to prevent me from playing around with the size of the heart and getting the size perfect. A heart with a circle radius of 40 was the second heart I drew, and—because it looked good enough—I never tried any other sizes.

By manually entering those eight values in my code, I “hard-coded” my program to only draw hearts with a circle radius of 40. Hard-coding a program is generally a bad practice—for both programmers and drawers. I can make it easier to change the size of the heart if I store the value of the radius in a variable. Then I can change the size of the heart by changing just one value.

function drawHeart() {
var radius = 40
 
ctx.fillRect(-radius, -radius, 2 * radius, 2 * radius);
 
ctx.beginPath();
ctx.arc(-radius, 0, radius, 0, 2 * Math.PI, false);
ctx.fill();
 
ctx.beginPath();
ctx.arc(0, -radius, radius, 0, 2 * Math.PI, false);
ctx.fill();
}

Another option is to pass the value of the radius to my drawHeart subroutine when I call it. I can rewrite the drawHeart subroutine to accept an input by giving it a parameter.

function drawHeart(radius) {
ctx.fillRect(-radius, -radius, 2 * radius, 2 * radius);
 
ctx.beginPath();
ctx.arc(-radius, 0, radius, 0, 2 * Math.PI, false);
ctx.fill();
 
ctx.beginPath();
ctx.arc(0, -radius, radius, 0, 2 * Math.PI, false);
ctx.fill();
}

Now we can call drawHeart(40) to draw a heart with a circle radius of 40. In fact, if I keep calling the drawHeart subroutine and pass it random numbers between 20 and 60, I can draw something like this:

Create a spiral effect.