Coding hints II: Drawing on canvas using JavaScript

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

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).

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.

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

background("navy");

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

background("#F012D3");

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

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

circle(400, 300, 200);

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

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

rect(400, 300, 300, 200);

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

line(400, 300, 500, 500);

Draw a triangle by specifying each corner coordinates

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.

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

Draw a point at coordinates 400 x 300

point(400, 300);

Draw text JavaScript at coordinates 400 x 300

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

textSize(20);

text("JavaScript", 400, 300);

Set "Magenta" as the color to fill shapes

fill('Magenta');

circle(400, 300, 100);

Set "Teal" as the color to draw shapes

stroke('Teal');

circle(400, 300, 100);

Set the line thickness to 2 px

strokeWeight(2);

circle(400, 300, 100);

Draw empty shapes, without fill color

noFill();

circle(400, 300, 100);

Draw shapes without an outline

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

home();

Sets to Red the pen color of the default turtle

pencolor("Red");

Sets to 2 the pen size of the default turtle

pensize(2);

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

pendown();

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

penup();

Move the turtle to an arbitrary position on the canvas

setposition(100, 100);

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

left(30);

Turns the default turtle to the right by 30 degrees

right(30);

Sets the turtle heading (direction) to an arbitrary angle

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.

forward(100);

Moves the turtle back by number of specified pixels.

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

back(100);

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

let p = position();

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

Retrieve the default turtle direction in degrees

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

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

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.

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:

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

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

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

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

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.

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.

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

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

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

frameRate(30);
textSize(40);

let n = 0;

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

    n++;
}

Obtain the frame rate

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


This article is part of a series of mini-articles containing JavaScript coding hints applicable to codeguppy.com environment:

Read more blog articles Browse JavaScript projects

About codeguppy

CodeGuppy is a FREE coding platform for schools and independent learners. If you don't have yet an account with codeguppy.com, you can start by visiting the registration page and sign-up for a free account. Registered users can access tons of fun projects!


Follow @codeguppy on Twitter for coding tips and news about codeguppy platform. For more information, please feel free to contact us.