Coding Hints. Part II: Drawing
Tags: javascript, codeguppy, codenewbie, beginners
Published: 2020-10-23 03:01:24

[codeguppy.com](https://codeguppy.com) is a great environment for graphical based activities using both cartesian and turtle graphics. Please refer to this page for a quick overview of graphical based commands:

- [About canvas](#about-canvas)
- [Clearing the canvas](#clearing-the-canvas)
- [Background color](#background-color)
- [Drawing shapes](#drawing-shapes)
- [Shape settings](#shape-settings)
- [Turtle Graphics](#turtle-graphics)
- [Colors](#colors)
- [Angles](#angles)
- [Animations](#animations)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1850hfpjup76oa7uyxhr.png)

# About canvas

In codeguppy.com, the graphical canvas is 800 x 600 pixels.
The system is automatically initializing the `width` and `height` variables with the dimensions of the canvas

It is recommended to use these variables in your program instead of hardcoding constants (whenever is possible).

```javascript
println(width);
println(height);
```

# Clearing the canvas

clear() is used to clear the drawing canvas. This function is very useful for animations, inside the `loop()` event, to clear the frame before the next draw.

```javascript
clear();
```

# Background color

The `background` command is used to set the background color of the canvas.

💡 The `background` command is not erasing the shapes drawn on the canvas. To erase the canvas, use `clear()` instead.

### Set the background color to a built-in color specified as a string

```javascript
background("navy");
```

### Set the background color to a color specified as a hex "#RRGGBB" string

```javascript
background("#F012D3");
```

### Set the background color to a gray color (0 - black, 255 - white)

```javascript
background(255);
```

> Note: In codeguppy.com you can set even an image as the background. Please refer to the "Games" page for more details about how to set an image as a background.


# Drawing shapes

### Draw a circle at coordinates 400 x 300 and radius of 200 pixels

```javascript
circle(400, 300, 200);
```

### Draw an ellipse at coordinates 400 x 300 and width and height of 300 x 200 pixels

```javascript
ellipse(400, 300, 300, 200);
```

### Draw a rectangle having the top-left corner at coordinates 400 x 300 and width and height of 300 x 200 pixels

```javascript
rect(400, 300, 300, 200);
```

### Draw a line between coordinates 400 x 300 and 500 x 500

```javascript
line(400, 300, 500, 500);
```

### Draw a triangle by specifying each corner coordinates

```javascript
triangle(400, 100, 200, 400, 600, 500);
```

### Draw an arc

To draw an arc, you specify the coordinates as for an ellipse (center position, width and height) and in addition you specify the start and end angle.

```javascript
arc(400, 300, 300, 200, 0, 180);
```

### Draw a point at coordinates 400 x 300

```javascript
point(400, 300);
```

### Draw text JavaScript at coordinates 400 x 300

```javascript
text('JavaScript', 400, 300);
```

# Shape settings

> Note: Once set, these settings will be applied to all successive shape drawn on the canvas

### Set the size of text to 20

```javascript
textSize(20);

text("JavaScript", 400, 300);
```

### Set "Magenta" as the color to fill shapes

```javascript
fill('Magenta');

circle(400, 300, 100);
```

### Set "Teal" as the color to draw shapes

```javascript
stroke('Teal');

circle(400, 300, 100);
```

### Set the line thickness to 2 px

```javascript
strokeWeight(2);

circle(400, 300, 100);
```

### Draw empty shapes, without fill color

```javascript
noFill();

circle(400, 300, 100);
```

### Draw shapes without an outline

```javascript
noStroke();

fill("lightblue");
circle(400, 300, 100);
```

# Turtle Graphics

codeguppy.com allows you to combine cartesian graphics with turtle graphics.

When working with Turtle Graphics, you can use the default turtle (recommended for beginners and regular programs) or create additional turtles (for complex programs).

## Working with the default Turtle

To use the default turtle, all you need to do is to use the following global `instructions`.

### Reset the default turtle to home position

```javascript
home();
```

### Sets to `Red` the pen color of the default turtle

```javascript
pencolor("Red");
```

### Sets to 2 the pen size of the default turtle

```javascript
pensize(2);
```

### Put the pen on the paper. The turtle will draw.

```javascript
pendown();
```

### Raise the pen from the paper. The turtle will advance but not draw

```javascript
penup();
```

### Move the turtle to an arbitrary position on the canvas

```javascript
setposition(100, 100);
```

### Turns the default turtle to the left by the number of specified degrees

```javascript
left(30);
```

### Turns the default turtle to the right by 30 degrees

```javascript
right(30);
```

### Sets the turtle heading (direction) to an arbitrary angle

```javascript
setheading(180);
```

### Moves the turtle forward by number of specified pixels.

Note: The turtle moves in the direction that was previosly set with `left`, `right` or `setheading`. If the pen is on the paper, the turtle will draw.

```javascript
forward(100);
```

### Moves the turtle back by number of specified pixels.

Note: The turtle moves in the oposite direction than would move with `forward`

```javascript
back(100);
```

### Retrieve the x and y position of the default turtle as an array of 2 numbers

```javascript
let p = position();

println(p[0]);
println(p[1]);
```

### Retrieve the default turtle direction in degrees

```javascript
let angle = heading();

println(angle);
```

## Working with multiple turtles

In complex programs, you may find useful to work with multiple turtles, since each of them maintains their own state such as position, color, etc.

### Create multiple turtles

```javascript
let t1 = createTurtle();
let t2 = createTurtle();

t1.pencolor("Red");
t1.forward(100);

t2.pencolor("Blue");
t2.right(90);
t2.forward(100);
```

### Get the default turtle

```javascript
let t = getDefaultTurtle();
t.forward(100);
```

# Colors

As observed in the above examples, codeguppy.com allow users to specify colors in a variaty of ways. In this way, you can use the most convenient method for your program.

### Named colors

There are a variaty of colors with predefined names in codeguppy.com You can explore all of them on the "Backgrounds" pallete.

```javascript
fill("Red");
circle(400, 300, 100);
```

### RGB / HTML style colors

When predefined colors are not enough, you can create any color by specifying the `Red`, `Green` and `Blue` ammounts. You can pass these colors as strings to `fill` and `stroke` functions using the `#RRGGBB` format:

```javascript
fill("#F3E2B5");
circle(400, 300, 100);
```

### Quick gray colors

If you need to quickly create a shade of gray, just pass a number from `0` to `255` to any function that expects a color such as `fill` or `stroke`

```javascript
fill(100);
circle(400, 300, 100);
```

### Colors using the `color()` function

Another way to create a color is by using the `color` function and the R, G, B ammounts. These ammounts are in the range of `0` to `255`

```javascript
let myColor = color(100, 200, 150);
fill(myColor);

circle(400, 300, 100);
```

## Changing to `HSB` mode

By default, codeguppy.com color system is using the RGB mode, where colors are specified by R, G, B ammounts (as seen above).
However, advanced users can switch to `HSB` mode, where colors are specified by Hue, Saturation and Brightness.

In `HSB` mode, the values for `color` function are in the interval `0` - `360`

```javascript
colorMode(HSB);

let c1 = color(100, 50, 300);
fill(c1);
circle(300, 300, 50);

let c2 = color(100, 300, 300);
fill(c2);
circle(500, 300, 50);
```

## Changing back to `RGB` mode

```javascript
colorMode(RGB);
```

# Angles

All the trigonometric functions, as well as certain drawing functions such as `arc` are working with angles.

To appeal to young coders and beginners, all angles in codeguppy.com are in "DEGREES" by default. 

However, advanced users can switch to "RADIANS" mode by using `angleMode`. Don't forget to switch back to "DEGREES" when done working with RADIANS.

```javascript
angleMode(RADIANS);
arc(400, 150, 300, 200, 0, PI);

angleMode(DEGREES);
arc(400, 350, 300, 200, 0, 180);
```

### Using trigonometric functions

Via the p5.js library, codeguppy.com offers users a series of easy to use trigonometric functions such as `sin`, `cos`, etc.

```javascript
textSize(40);
let x = 0;

function loop()
{
    let y = 300 + 50 * sin(frameCount);
    x++;
    
    clear();
    text("Hello, World", x, y);
}
```

# Animations

To implement animations, codeguppy.com offers users a method similar to the one use by "cartoons": think of your animation as a series of frames! All you have to do is to draw the first frame, then erase and draw the second frame in a slightly different position, and so on!

## loop() is at the base of animations

In codeguppy.com, function `loop()` is special. All you have to do is to define this function in your code, and the codeguppy.com engine will run it for you up to 60 times per second! There is no need to call it yourself.

### Move an horizontal line on the screen

```javascript
let y = 0;

function loop()
{
    // Clear the frame
    clear();

    // Draw the frame
    line(0, y, 800, y);
    
    // Update the state
    y++;
    if (y > 600)
        y = 0;
}
```

### Bounce a circle on the screen

```javascript
let x = 400;
let y = 300;

let dx = 1;
let dy = 1;

let speed = 3;

function loop()
{
    // Clear the frame
    clear();

    // Draw the frame
    circle(x, y, 10);
    
    // Update the state
    x += speed * dx;
    y += speed * dy;
    
    if (x < 0 || x > width)
        dx *= -1;
        
    if (y < 0 || y > height)
        dy *= -1;
}
```

### Change the default frame rate

```javascript
frameRate(30);
textSize(40);

let n = 0;

function loop()
{
    clear();
    text(n, 400, 300);

    n++;
}
```

### Obtain the frame rate

```javascript
function loop()
{
    clear();
    text(frameRate(), 400, 300);
}
```

---

codeguppy.com is using the [p5.js](https://p5js.org/) library at runtime. Advanced users can leverage almost the entire p5.js functionality. If you are familiar with p5.js, please check [codeguppy for p5.js connoisseurs](https://codeguppy.com/code.html?t=_p5&list=coding) to see how to properly use it in your codeguppy.com programs.

---

This article is part of a series of mini-articles containing JavaScript coding hints applicable to [codeguppy.com](https://codeguppy.com) environment.

- [Coding Hints. Part I: JavaScript syntax](https://dev.to/codeguppy/coding-hints-part-i-javascript-syntax-264m)

- [Coding Hints. Part II: Drawing]
(https://dev.to/codeguppy/coding-hints-part-ii-drawing-2ok9)

- [Coding Hints. Part III: User Input]
(https://dev.to/codeguppy/coding-hints-part-ii-user-input-13ec)

- [Coding Hints. Part IV: Game Development]
(https://dev.to/codeguppy/coding-hints-part-iv-game-development-42l2)

- [Coding Hints. Part V: Other hints]
(https://dev.to/codeguppy/coding-hints-part-v-other-hints-3amb)