# About the Project

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MRAnvm4-8698tzAzIyg%2Fuploads%2FRRlQyf83ZebbhdxMAYpr%2FEasy%20Draw%20Icon.png?alt=media\&token=de6a25b8-a34e-4bfa-9d4f-250fe64f0b21)

## What is Easy Draw?

Easy Draw is an easy to use Python and Java module that allows you to create simple graphics primitives (rectangles, circles, polygons, etc.) with just method calls.

It is designed to be used with students that only know how to make function/method calls with Python or Java code.

After learning more about coding (conditionals, iteration, and procedural definitions), students can use Easy Draw to make simple animations and games!

{% hint style="success" %}
**New in Easy Draw 2.0:** Your drawing shows in your web browser, so there is nothing to install besides Python or Java. And Easy Draw now has a Java version! See [What's New in 2.0](https://easy-draw.joemazzone.net/python/whats-new-in-2.0).
{% endhint %}

## Python - Where do I start?

{% content-ref url="/pages/-MRBD2V42DP9IcR9Kt1u" %}
[Setup and Install](https://easy-draw.joemazzone.net/python/setup-and-install)
{% endcontent-ref %}

{% content-ref url="/pages/-MRAu4wnLQml09m5a9T-" %}
[Starter Template](https://easy-draw.joemazzone.net/python/starter-template)
{% endcontent-ref %}

{% content-ref url="/pages/-MRAu8hE1mBCDQ\_TKEjk" %}
[Example Code](https://easy-draw.joemazzone.net/python/example-code)
{% endcontent-ref %}

{% content-ref url="/pages/-MRAwF3q9dGDRhu7\_SaR" %}
[Style Guide](https://easy-draw.joemazzone.net/python/style-guide)
{% endcontent-ref %}

## Java - Where do I start?

{% content-ref url="/pages/ZUecfp8mPBQJ0bRkNvmv" %}
[Setup and Install](https://easy-draw.joemazzone.net/java/setup-and-install)
{% endcontent-ref %}

{% content-ref url="/pages/1Z82YhiT6gM5KNIgtlkG" %}
[Starter Template](https://easy-draw.joemazzone.net/java/starter-template)
{% endcontent-ref %}

{% content-ref url="/pages/V6WtjAZbJnzznI0IHJw2" %}
[Example Code](https://easy-draw.joemazzone.net/java/example-code)
{% endcontent-ref %}

{% content-ref url="/pages/chknJDBMeY14StLYLbvf" %}
[Module Reference](https://easy-draw.joemazzone.net/java/module-reference)
{% endcontent-ref %}

## Want to Contribute? Find an Issue/Error? Have a Feature Request?

Visit the GitHub page to file an issue or contribute to the project! The Python (`easy_draw.py`) and Java (`EasyDraw.java`) versions are both in the same repository.

{% embed url="<https://github.com/MrMazzone/easy-draw>" %}

## About the Project

Easy Draw was created by [Joe Mazzone](https://www.linkedin.com/in/joe-mazzone/), Computer and Software Engineering instructor at William M. Davies, Jr. Career and Technical High School in Lincoln, Rhode Island.

The project was created to introduce Davies' students to GUI development early in an introductory Python course. Then, I thought it would be great to use in AP Computer Science A (Java)! GUIs are how students interact with software. Let's get them to build GUIs earlier and generate more interest in Computer Science and programming!

Looking for a simple way to create an app with Python or Java? Check out the Easy App project: <https://easy-app.joemazzone.net/>

For more information about Davies Career and Technical High School, visit <https://www.daviestech.org/>

Like what Joe created? ☕ Buy him a coffee: <https://www.buymeacoffee.com/JoeMazzone>


# Student Developed Art

## Submit your artwork!

We want to see what you make with Easy Draw!  Submit some artwork so we can post it here: <https://forms.gle/AngY7SviXCPoozre8>

## Gotta Catch 'em All

Jacob Turchetta, Davies Career and Technical High School, Class of 2023 -- Python Module

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MRuX4tSFO5dekxsBvpd%2F-MRuZfd4FBNnjVflxgI0%2FScreenshot%202021-01-23%20165919.png?alt=media\&token=2776fb14-73e2-401d-aa55-9163493cc34a)

## Sponge Bob Square Pants

Arianna White, Davies Career and Technical High School, Class of 2023 -- Python Module

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MRuX4tSFO5dekxsBvpd%2F-MRuZmQdXr0iyPn1QtTv%2FScreenshot%202021-01-23%20170012.png?alt=media\&token=96adef5c-3a37-4ee2-b84c-aeff1c9078d8)

## Hoodie

Rodilson Borges, Davies Career and Technical High School, Class of 2023 -- Python Module

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MRuX4tSFO5dekxsBvpd%2F-MRuZqE4gYkAzO1qglCc%2FScreenshot%202021-01-23%20170131.png?alt=media\&token=65b7718c-d589-408c-b92f-07081e247e51)

## Dinner

Emma Ainsburg, Davies Career and Technical High School, Class of 2023 -- Python Module

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MRuX4tSFO5dekxsBvpd%2F-MRuZruBPTUXyAKNzrSO%2FScreenshot%202021-01-23%20164452.png?alt=media\&token=09e0d8e9-2980-40c4-9e3e-46d57bed68c4)

## Through a Window

David Cabreja, Davies Career and Technical High School, Class of 2023 -- Python Module

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MRuX4tSFO5dekxsBvpd%2F-MRuZx5sUxWbcFPnQZD-%2FScreenshot%202021-01-23%20164622.png?alt=media\&token=e272cbcb-ae2e-4a21-be24-3bb00138404c)

## Baseball

Noah Campanelli, Davies Career and Technical High School, Class of 2023 -- Python Module

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MRuX4tSFO5dekxsBvpd%2F-MRuZzxsWxPqVK42MJX3%2FScreenshot%202021-01-23%20165637.png?alt=media\&token=53820ded-c58f-457f-83a5-b68b5b382792)

## My House

Victoria DeLaCruz, Davies Career and Technical High School, Class of 2023 -- Python Module

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MRuX4tSFO5dekxsBvpd%2F-MRu_2BFR8_x_r81HzEZ%2FScreenshot%202021-01-23%20170300.png?alt=media\&token=35493f2b-e552-452f-95e8-283dbaf1b7dc)

## Sunset

Jonathan Picon Ruiz, Davies Career and Technical High School, Class of 2023 -- Python Module

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MRuX4tSFO5dekxsBvpd%2F-MRu_8DKhJHjtfi_bIt4%2FScreenshot%202021-01-23%20170928.png?alt=media\&token=3a56429b-d2f5-4d80-b451-56b8e7194f66)

## The Oldies

Daunte Costa, Davies Career and Technical High School, Class of 2023 -- Python Module

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MRuX4tSFO5dekxsBvpd%2F-MRu_I5KaKFbRAqKqVrG%2FScreenshot%202021-01-23%20170214.png?alt=media\&token=e60a821e-e53c-4140-be48-478de5a17fd6)

## The Bridge

Ethan Wijerathnayapa, Davies Career and Technical High School, Class of 2023 -- Python Module

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MRuX4tSFO5dekxsBvpd%2F-MRu_KtxBbaH8ft5IblR%2FScreenshot%202021-01-23%20170404.png?alt=media\&token=686f6aed-5138-4a90-995d-c9965a3d3571)


# Setup and Install

Easy Draw is not on PyPI just yet, so you cannot `pip` install it. To use it you will need the `easy_draw.py` file which can be found and downloaded from GitHub.

{% embed url="<https://github.com/MrMazzone/easy-draw/releases/download/v2.0.0/easy_draw.py>" %}

## Easy Draw File

Once you have the `easy_draw.py` file, you can include it in your project directory (the same folder as your project files).

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MRFmaFsbu67ASjbyQ_S%2F-MRH8gFD6FLTalSQhtIW%2Fimage.png?alt=media\&token=588cea85-1478-46c9-a388-b3063b22170e)

## Dependencies

None! Easy Draw only uses the Python standard library, so there is nothing else to install.

You do need a web browser. Easy Draw shows your drawing in your web browser instead of in a separate window. When your program runs, Easy Draw:

1. Writes your drawing to an `index.html` file in the same folder as your program.
2. Opens the live drawing in your web browser (<http://localhost:8765/>).

See the [Starter Template](https://easy-draw.joemazzone.net/python/starter-template) to write your first program.

{% hint style="info" %}
**Upgrading from version 1?** Your programs should work without any changes. See [What's New in 2.0](https://easy-draw.joemazzone.net/python/whats-new-in-2.0) for everything that changed.
{% endhint %}

## Desktop Version

The original Tkinter window version of Easy Draw is still available as `easy_draw_desktop.py`.

{% embed url="<https://github.com/MrMazzone/easy-draw/releases/download/v2.0.0/easy_draw_desktop.py>" %}

It needs `Tkinter` and `PIL` (Pillow) installed. Use it in place of `easy_draw.py` like this:

```python
import easy_draw_desktop as easy_draw
```

If you get an error like `ImportError: No module named tkinter`, you may need to install Tkinter on your system: <https://tkdocs.com/tutorial/install.html>

If you get an error like `ImportError: No module named PIL`, you may need to install Pillow: <https://pillow.readthedocs.io/en/stable/installation.html>


# What's New in 2.0

Easy Draw 2.0 draws in your web browser instead of a Tkinter window. Programs written for version 1 should keep working.

* **Drawings show in the browser.** Easy Draw writes your drawing to `index.html` next to your program and opens a live copy at <http://localhost:8765/>. Nothing else needs to be installed.
* **`Oval` objects now rotate properly.**
* **`Rectangle` can rotate around its top-left corner:** `rect.rotate(45, from_top_left=True)`
* **`Image` objects can rotate.**
* **`.rotate()` turns every object clockwise**, including `Arc` and `Text`, which used to turn counterclockwise.
* **Properties can be changed directly:** `circle.radius = 50` works like `circle.set_property(radius = 50)`.
* **`open_image()` works with public image links:** `easy_draw.open_image("https://example.com/cat.png")`. The browser loads the image straight from the link, so viewing the drawing needs an internet connection.
* **Animations made with `time.sleep()` loops now show while they run.**
* **Every drawing object shares a `Shape` parent class.**
* **`end(print_html=True)`** prints the finished page's HTML code.
* **`load_canvas()` has new options:** `port` (default `8765`) picks the port for the live drawing, and `open_browser=False` lets you open the page yourself.

## Still want the Tkinter window?

The original version is still available as `easy_draw_desktop.py`. See [Setup and Install](https://easy-draw.joemazzone.net/python/setup-and-install).

## Java

Easy Draw now has a Java version too! See [Java Setup and Install](https://easy-draw.joemazzone.net/java/setup-and-install).


# Starter Template

To start drawing with Easy Draw, all you need is three lines of code. It is that easy!

```python
# Learn how to use Easy Draw!
# https://easy-draw.joemazzone.net/python/module-reference

import easy_draw           # Import the module to use it

easy_draw.load_canvas()    # Always start your program with this

# --- Your main program below here ---



# --- Your main program ends here ---

easy_draw.end()            # Always end your program with this
```

When you run the program above, Easy Draw opens your drawing in your web browser at <http://localhost:8765/>.

Easy Draw also writes your drawing to an `index.html` file in the same folder as your program. Open `index.html` any time to see your drawing again.

{% hint style="info" %}
While your program is running, clicks, mouse movement, and key presses in the browser are sent to your event handlers. The badge in the top-right corner of the page says **Live** when the page is connected to your program and **Offline** when it is not.

Close the browser tab (or press Ctrl+C) to stop your program. Run your program again and the page goes live again.
{% endhint %}

Here is the Easy Draw page with a drawing on it and the grid turned on:

![The Easy Draw page in a web browser](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MRAMSGwqRIdQ2ADsTkz%2Fuploads%2F0FH3GcROqAGhldKd0USi%2Feasy-draw-browser.webp?alt=media)

#### Features of the Easy Draw page:

1\. Grid on and off

To help learners visualize the coordinate system, a grid can be turned on and off with the **Grid** button. The grid has a line every 50 pixels and numbers along the top and left side of the canvas.

2\. Coordinates

To help learners position shapes on the drawing canvas, the bottom-right corner of the page shows the x, y coordinates of your mouse as you move it around the canvas.

3\. Color Picker

To help learners identify color values to use in their code, they can open a color picker with the **Color Picker** button. When you choose a color, the page shows its hex and RGB values to use in your program.

*Note: The color picker comes from your web browser and will look different in different browsers.*

4\. Save the Canvas Drawing

You can save your drawing as a PNG file by clicking the **Save Canvas** button. Just be sure to provide the image with a file name. Your browser downloads the picture, so it will be in your Downloads folder.

To save the picture in your project folder instead, see [Saving Your Drawing](https://easy-draw.joemazzone.net/python/module-reference/saving-your-drawing).


# Example Code

## Example 1:  A Tree!

Here is a simple example drawing a tree with a rectangle and three triangles. The background is set to sky blue with a hex color value, and the triangles are rotated 30 degrees.

```python
import easy_draw

easy_draw.load_canvas()

easy_draw.set_canvas_color("#87CEEB")

trunk = easy_draw.Rectangle(
    xy = (250, 300), 
    width = 100, 
    height = 310,
    color = (160, 82, 45)
)

top = easy_draw.RegPolygon(
    nsides = 3,
    center_xy = (300, 175), 
    radius = 125, 
    color = (0, 255, 0)
)
top.rotate(30)

middle = easy_draw.RegPolygon(
    nsides = 3,
    center_xy = (300, 275), 
    radius = 175, 
    color = (0, 255, 0)
)
middle.rotate(30)

bottom = easy_draw.RegPolygon(
    nsides = 3,
    center_xy = (300, 400), 
    radius = 250, 
    color = (0, 255, 0)
)
bottom.rotate(30)

easy_draw.end()
```

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MRHN5hgZYKKGE0yrPL_%2F-MRHX6zyKRTdaLV-G_Wr%2Ftree.png?alt=media\&token=84101837-80fa-4dde-8c7c-a082ce459dd1)

## Example 2:  Property Change and Event Handling

Here is an example of drawing a square and an octagon, then animating them when clicked.

When the square is clicked, it changes color to a new random value and rotates by 10 degrees.&#x20;

When the octagon is clicked, it changes color to a new random value and rotates by 10 degrees.

```python
import easy_draw
import random

easy_draw.load_canvas()

colors = ["blue", "red", "yellow", "green", "orange", "purple"]

square = easy_draw.Rectangle(
    xy = (100, 100), 
    width = 200, 
    height = 200
)

def click_square(event):
    global square
    random_color = random.choice(colors)
    square.set_property(color = random_color)
    square.rotate(10)

square.event_setup("<Button-1>", click_square)

octagon = easy_draw.RegPolygon(
    center_xy = (400, 400),
    radius = 100, 
    nsides = 8
)

def click_octagon(event):
    global octagon
    random_color = random.choice(colors)
    octagon.set_property(color = random_color)
    octagon.rotate(10)

octagon.event_setup("<Button-1>", click_octagon)

easy_draw.end()
```

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MRHqZV53luLlC66FBKK%2F-MRIK86ep5BeCiFh1c3l%2Fanimation_example.gif?alt=media\&token=decb4b17-0160-4209-b71c-1873ce25f3e7)

## Example 3: Decagon Islamic Design

Provided by *Jackie Lin* *from Taiwan CSHS (Chung-shan Senior High School)*

```python
import easy_draw
import math
from shapely import affinity
from shapely.geometry import LineString, Point, Polygon

def out_n_polygon_of_circle(line_1, line_2, n):
    its_0 = line_1.intersection(line_2)
    its_0_xy = (its_0.x, its_0.y)
    poly_xy = [its_0_xy]
    for i in range(1, n+1, 1):
        its_i = affinity.rotate(its_0, i*360/n, (0, 0))
        its_i_xy = (its_i.x, its_i.y)
        poly_xy.append(its_i_xy)
    return poly_xy

factor = 37
cxy = (0, 0)
r0 = 8*factor
r1 = r0/2

p0_xy = (r1*math.cos(0*math.pi/10), r1*math.sin(0*math.pi/10))
p2_xy = (r1*math.cos(2*math.pi/10), r1*math.sin(2*math.pi/10))
p3_xy = (r1*math.cos(3*math.pi/10), r1*math.sin(3*math.pi/10))
p4_xy = (r1*math.cos(4*math.pi/10), r1*math.sin(4*math.pi/10))
p6_xy = (r1*math.cos(6*math.pi/10), r1*math.sin(6*math.pi/10))
p8_xy = (r1*math.cos(8*math.pi/10), r1*math.sin(8*math.pi/10))
p10_xy = (r1*math.cos(10*math.pi/10), r1*math.sin(10*math.pi/10))
p18_xy = (r1*math.cos(18*math.pi/10), r1*math.sin(18*math.pi/10))

line_p2_p8 = LineString([p2_xy, p8_xy])
line_p2_00 = LineString([p2_xy, (0, 0)])
line_p3_00 = LineString([p3_xy, (0, 0)])
line_p4_00 = LineString([p4_xy, (0, 0)])

its_21 = line_p3_00.intersection(line_p2_p8)
its_22 = affinity.rotate(its_21, 36, (0, 0))
its_23 = affinity.rotate(its_21, 72, (0, 0))
its_21_xy = (its_21.x, its_21.y)
its_22_xy = (its_22.x, its_22.y)
its_23_xy = (its_23.x, its_23.y)

star_edge_xy = [p2_xy, its_21_xy, p4_xy]
star_edge = LineString(star_edge_xy)

its_41 = line_p4_00.intersection(line_p2_p8)
its_41_xy = (its_41.x, its_41.y)
star_edge_xy = [its_21_xy, its_41_xy, its_22_xy]
star_edge = LineString(star_edge_xy)

H_line = LineString([(0, 0), (8*factor, 0)])
r_H_line = affinity.rotate(H_line, 18, cxy)
V_Rline = LineString([(r1, 0), (r1, 8*factor)])
returned_xy_list = out_n_polygon_of_circle(r_H_line, V_Rline, 10)
decagon_xy = returned_xy_list
decagon = LineString(decagon_xy)

line_p0_p6 = LineString([p0_xy, p6_xy])
line_p4_p18 = LineString([p4_xy, p18_xy])

its_1 = r_H_line.intersection(V_Rline)
its_2 = r_H_line.intersection(line_p0_p6)
its_3 = H_line.intersection(line_p4_p18)
its_4 = line_p0_p6.intersection(line_p4_p18)
its_1_xy = (its_1.x, its_1.y)
its_2_xy = (its_2.x, its_2.y)
its_3_xy = (its_3.x, its_3.y)
its_4_xy = (its_4.x, its_4.y)

its_5_xy = (its_1.x, -its_1.y)
its_5 = Point(its_5_xy)
its_6 = affinity.rotate(its_1, -108, its_5_xy)
its_6_xy = (its_6.x, its_6.y)
its_7 = affinity.rotate(its_5, -108, its_6_xy)
its_7_xy = (its_7.x, its_7.y)
its_8 = affinity.rotate(its_6, -108, its_7_xy)
its_8_xy = (its_8.x, its_8.y)

pentagon_line = LineString([its_1_xy, its_5_xy, its_6_xy, its_7_xy, its_8_xy])

pentagon = Polygon([its_1_xy, its_5_xy, its_6_xy, its_7_xy, its_8_xy, its_1_xy])

pentagon_cen = pentagon.centroid
pentagon_cen_xy = (pentagon_cen.x, pentagon_cen.y)

pen_line_5_to_6 = LineString([its_5_xy, its_6_xy])
mid = pen_line_5_to_6.interpolate(0.5, normalized=True)
mid_xy = (mid.x, mid.y)
pen_line_1 = LineString([p0_xy, pentagon_cen_xy])
pen_line_2 = LineString([mid_xy, pentagon_cen_xy])

dart_line_1_extend = affinity.rotate(pen_line_1, -36, p0_xy)
dart_line_2_extend = affinity.rotate(pen_line_2, 36, mid_xy)

its_dart = dart_line_1_extend.intersection(dart_line_2_extend)
its_dart_xy = (its_dart.x, its_dart.y)
dart_xy = [p0_xy, its_dart_xy, mid_xy, pentagon_cen_xy, p0_xy]
dart = LineString(dart_xy)
dart_edge = LineString([p0_xy, its_dart_xy, mid_xy])

dart_edge_1 = LineString([p0_xy, its_dart_xy, mid_xy])
dart_edge_2 = affinity.rotate(dart_edge_1, 72, pentagon_cen_xy)
dart_edge_3 = affinity.rotate(dart_edge_1, 144, pentagon_cen_xy)
dart_edge_4 = affinity.rotate(dart_edge_1, 216, pentagon_cen_xy)
dart_edge_5 = affinity.rotate(dart_edge_1, 288, pentagon_cen_xy)

star_p01 = dart_edge_1.coords[:][0]
star_p02 = dart_edge_1.coords[:][1]
star_p03 = dart_edge_1.coords[:][2]
star_p04 = dart_edge_2.coords[:][1]
star_p05 = dart_edge_2.coords[:][2]
star_p06 = dart_edge_3.coords[:][1]
star_p07 = dart_edge_3.coords[:][2]
star_p08 = dart_edge_4.coords[:][1]
star_p09 = dart_edge_4.coords[:][2]
star_p10 = dart_edge_5.coords[:][1]
star_p11 = dart_edge_5.coords[:][2]

star_xy = [star_p01, star_p02, star_p03, star_p04, star_p05, star_p06, star_p07, star_p08, star_p09, star_p10, star_p11]
star = LineString(star_xy)

pentagon = LineString([its_1_xy, its_5_xy, its_6_xy, its_7_xy, its_8_xy])

easy_draw.load_canvas()

colors = ["black", "blue", "red", "yellow", "green", "orange", "purple"]

cir_r1 = easy_draw.Circle(
    center_xy=(300, 300),
    radius=r1,
    color=(100, 149, 237)
)

r2 = its_2.distance(Point(0, 0))
s01_xy = (r2*math.cos(1*math.pi/10), r2*math.sin(1*math.pi/10))
kite_xy = [p0_xy, its_1_xy, p2_xy, s01_xy]
kite = LineString(kite_xy)

for degree in (0, 36, 72, 108, 144, 180, 216, 252, 288, 324):
    r_kite = affinity.rotate(kite, degree, (0, 0))
    t_r_kite = affinity.translate(r_kite, 300, 300, 0)
    xy_list = []
    for xy in t_r_kite.coords[:]:
        xy_list.append(xy[0])
        xy_list.append(xy[1])
    poly_kite = easy_draw.Polygon(points_list=xy_list, color=(153, 50, 204), border_color=colors[0], border_width=2)

out_star_edge_xy = [p2_xy, its_21_xy, p4_xy]
out_star_edge = LineString(out_star_edge_xy)
for i in range(1, 10+1, 1):
    r_star_edge = affinity.rotate(out_star_edge, i*36, (0, 0))
    t_star_edge = affinity.translate(r_star_edge, 300, 300, 0)
    xy_list = []
    for xy in t_star_edge.coords[:]:
        xy_list.append(xy[0])
        xy_list.append(xy[1])
    edge_line = easy_draw.Line(points_list=xy_list, thickness=2, color=colors[0], style="cut")

in_star_edge_xy = [its_21_xy, its_41_xy, its_22_xy]
in_star_edge = LineString(in_star_edge_xy)
for i in range(1, 10+1, 1):
    r_star_edge = affinity.rotate(in_star_edge, i*36, (0, 0))
    t_star_edge = affinity.translate(r_star_edge, 300, 300, 0)
    xy_list = []
    for xy in t_star_edge.coords[:]:
        xy_list.append(xy[0])
        xy_list.append(xy[1])
    edge_line = easy_draw.Line(points_list=xy_list, thickness=2, color=colors[0], style="cut")

for degree in (0, 36, 72, 108, 144, 180, 216, 252, 288, 324):
    r_pentagon_line = affinity.rotate(pentagon_line, degree, (0, 0))
    t_r_pentagon_line = affinity.translate(r_pentagon_line, 300, 300, 0)
    xy_list = []
    for xy in t_r_pentagon_line.coords[:]:
        xy_list.append(xy[0])
        xy_list.append(xy[1])
    poly_petagon = easy_draw.Polygon(points_list=xy_list, color=(173, 216, 230), border_color=colors[0], border_width=2)
    r_star = affinity.rotate(star, degree, (0, 0))
    t_r_star = affinity.translate(r_star, 300, 300, 0)
    xy_list = []
    for xy in t_r_star.coords[:]:
        xy_list.append(xy[0])
        xy_list.append(xy[1])
    poly_star = easy_draw.Polygon(points_list=xy_list, color=(255, 215, 0), border_color=colors[0], border_width=2)

dy = 2 * its_1.y
up_tmp = affinity.rotate(its_1, 72, (0, 0))
pentagon_right_tip = affinity.rotate(Point(its_5_xy), 144, pentagon_cen_xy)
up_point_1 = affinity.rotate(pentagon_right_tip, 72, (0, 0))
up_point_1_xy = (up_point_1.x, up_point_1.y)
up_point_2_xy = (-up_point_1.x, up_point_1.y)
up_point_3_xy = (up_tmp.x, up_tmp.y + dy)

up_tri = LineString([up_point_1_xy, up_point_2_xy, up_point_3_xy])
for degree in (0, 36, 72, 108, 144, 180, 216, 252, 288, 324):
    r_up_tri = affinity.rotate(up_tri, degree, (0, 0))
    t_r_up_tri = affinity.translate(r_up_tri, 300, 300, 0)
    xy_list = []
    for xy in t_r_up_tri.coords[:]:
        xy_list.append(xy[0])
        xy_list.append(xy[1])
    poly_tri = easy_draw.Polygon(points_list=xy_list, color=(143, 188, 143), border_color=colors[0], border_width=2)

easy_draw.end()
```

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MU0ldkrR_HtCyrMe4du%2F-MU0oTrFNLI-VbMzKVeH%2Fdecagon.png?alt=media\&token=901c5f48-0c8d-473f-85cb-c488ed521e81)

*More examples coming soon!*

{% embed url="<https://repl.it/@MrMazzone/Easy-Draw-Examples#main.py>" %}


# Style Guide

The documentation will show examples a certain way, but it doesn't mean you have to write your code that way.

I have designed the documentation for what I believe is best for beginner students to work with the module and learn certain concepts.

Below I outline some examples of this:

## Importing Easy Draw

In all examples Easy Draw is imported the following way:

```python
import easy_draw

easy_draw.load_canvas()

square = easy_draw.Rectangle(
    xy = (100, 100), 
    width = 200, 
    height = 200
)

easy_draw.end()
```

This means in order to use any of the Easy Draw commands, you need to use the module name and a dot operator.

Example: `easy_draw.load_canvas()`

My philosophy: It is best practice to have students work with modules using full module name first, but it does not prevent you from doing the following examples.

It is possible to indiscriminately `import` everything from a module at one fell swoop. This is called a wildcard import and it is done like this `from module import *` . It makes it so you do not need to reference the module to use its commands. See below:

```python
from easy_draw import *

load_canvas()

square = Rectangle(
    xy = (100, 100), 
    width = 200, 
    height = 200
)

end()
```

Yes, the code is much less complex looking now. However, this is not Python best practice and wildcard imports should be avoided according to [PEP 8](https://www.python.org/dev/peps/pep-0008/). I want students to know they are working with a module and not abstract that experience too much.

You can also nickname the module when importing so you do not have to type `easy_draw` each time. You do this by using the `import module as nickname` structure.

```python
import easy_draw as ed

ed.load_canvas()

square = ed.Rectangle(
    xy = (100, 100), 
    width = 200, 
    height = 200
)

ed.end()
```

I have done this with modules before and students seem to get confused about what the module's actual name is. Then when they come across code online that doesn't nickname the way they expect, they are confused. So, I only show this trick later on when they are more experienced or when a student asks "do I really have to type `easy_draw` each time?"

## Using Object Constructors

In the examples you will notice that the object constructor functions are stylized to have each argument (property value) on separate lines:

```python
square = easy_draw.Rectangle(
    xy = (100, 100), 
    width = 200, 
    height = 200
)
```

I have students stylize the constructor method calls this way so it is easier for them to see the individual property values of the object they are instantiating.

Of course you can put these values all on one line which is the typical way to call functions and pass argument values.

```python
square = easy_draw.Rectangle(xy = (100, 100), width = 200, height = 200)
```

You may also notice that each example explicitly states the instance variable (property) name when assigning it a value in the constructor function call. I use this practice to help students learn the parameter needed to construct the object. Previous to doing this students would plug in values and not really know what the value was for. Explicitly using the name ensures the student knows what each value is used for. Example:

```python
square = easy_draw.Rectangle(
    xy = (100, 100), 
    width = 200, 
    height = 200
)
```

But, of course, you can use positional arguments and provide the values in the order the constructor function expects them. `Rectangle(xy, width, height)`

```python
square = easy_draw.Rectangle((100, 100), 200, 200)
```

However, the optional properties of an object (like `color`) are not positional arguments. These properties are keyword arguments and need to use the instance variable (property) name to set the value.

```python
square = easy_draw.Rectangle((100, 100), 200, 200, color = "red")
```

## Function and Property Names

All constructor functions start with a capital letter and use CamelCasing.

Examples: `Rectangle()`, `Oval()`, `Text()`, `RegPolygon()`

All other functions and instance variables/property names use all lowercase letters and snake\_casing.

Examples: `load_canvas()`, `color`, `.rotate()`, `border_width`

## Changing Properties

The examples use `.set_property()` to change a property, so students see that they are calling a method on the object:

```python
square.set_property(color = "red")
```

You can also assign the property directly. It does the same thing:

```python
square.color = "red"
```

## Storing Objects in Variables

All examples show objects being stored in a variable. If you want to be able to use a method on an object or change a property of that object, you must store it in a variable to reference the object later. So, all examples show objects being stored and referenced from a variable.

```python
square = easy_draw.Rectangle(
    xy = (100, 100), 
    width = 200, 
    height = 200
)

square.rotate(45)
```

The above example shows the `Rectangle` object is stored in a variable named `square`. Because it is stored in a variable, we can use the `.rotate()` method on it.

However, the shape will be drawn without storing the object in a variable.

```python
easy_draw.Rectangle(
    xy = (100, 100), 
    width = 200, 
    height = 200
)
```

If you try the above, it still creates the square.

You can call methods on an object without storing it in a variable by immediately following the constructor function call with the method call.

```python
easy_draw.Rectangle(
    xy = (100, 100), 
    width = 200, 
    height = 200
).rotate(45)
```

OR

```python
easy_draw.Rectangle(xy = (100, 100), width = 200, height = 200).rotate(45)
```

## Coordinates as Tuples

Lots of shape drawing and game Python libraries will require x and y coordinates as separate values. I have found that students see these values as a pair, so Easy Draw objects expect x and y coordinates to be coupled as a tuple.

Example: This -- `xy = (100, 200)` | Not this -- `x = 100, y = 200`

The examples show the `points_list` for `Polygon` and `Line` as pairs of x and y (an even amount of numbers) simply listed, not in tuples:

* `points_list = [50, 210, 180, 250, 300, 210]`

A list of tuples works too:

* `points_list = [(50, 210), (180, 250), (300, 210)]`


# Module Reference

Everything you can do with the Python version of Easy Draw (`easy_draw.py`, version 2.0).

{% content-ref url="/pages/-MRAu\_WoWipwKuyuupsF" %}
[The Drawing Canvas](https://easy-draw.joemazzone.net/python/module-reference/the-drawing-canvas)
{% endcontent-ref %}

{% content-ref url="/pages/-MRAv4THLzk2KzBvDpW7" %}
[Colors](https://easy-draw.joemazzone.net/python/module-reference/colors)
{% endcontent-ref %}

{% content-ref url="/pages/-MRAudFQsNUoXpOAhjPJ" %}
[Drawing Shapes](https://easy-draw.joemazzone.net/python/module-reference/drawing-shapes)
{% endcontent-ref %}

{% content-ref url="/pages/-MRAuqOmGihW-Utw2dnj" %}
[Text and Images](https://easy-draw.joemazzone.net/python/module-reference/text-and-images)
{% endcontent-ref %}

{% content-ref url="/pages/-MRAvKSob\_wbDI1gz9NW" %}
[Property Getting and Setting](https://easy-draw.joemazzone.net/python/module-reference/property-getters-and-setters)
{% endcontent-ref %}

{% content-ref url="/pages/-MRAvOvjwwCpPpBRrszw" %}
[Object Methods](https://easy-draw.joemazzone.net/python/module-reference/object-methods)
{% endcontent-ref %}

{% content-ref url="/pages/-MRAvSb83fmXckFG2fA6" %}
[Event Handling](https://easy-draw.joemazzone.net/python/module-reference/event-handling)
{% endcontent-ref %}

{% content-ref url="/pages/-MRAvatEhUnNTptruF-R" %}
[Saving Your Drawing](https://easy-draw.joemazzone.net/python/module-reference/saving-your-drawing)
{% endcontent-ref %}


# The Drawing Canvas

All shapes will be drawn on a canvas.

The Easy Draw canvas is 600 x 600 pixels (600 pixels wide by 600 pixels tall). So (300, 300) is the middle of the canvas, and (600, 600) is the bottom-right corner.

The coordinate system origin (0, 0) is the top-left corner of the canvas.

As x increases, objects move right. As y increases, objects move down (not up!).

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MRSz1hx0nb7qnoNWat3%2F-MRT-Gv1H7yZTFGl5LLU%2Fimage.png?alt=media\&token=a4585fe9-c159-4731-8a5e-7929c28c2f13)

{% hint style="info" %}
Turn on the **Grid** button in the Easy Draw page to see the coordinates on the canvas.
{% endhint %}

## Loading the Canvas

`load_canvas()`

Every Easy Draw program must start with this function call. It writes your drawing to an `index.html` file in the same folder as your program and opens the live drawing in your web browser.

Load canvas has one optional argument - `background`. The background property allows you to identify a color value for the canvas on load.

Example:

```python
easy_draw.load_canvas(background = (255, 0, 0))
```

There are also two optional settings for the live drawing:

| Setting        | Default Value | Description                                                             |
| -------------- | ------------- | ----------------------------------------------------------------------- |
| `port`         | 8765          | The port for the live drawing, which opens at <http://localhost:8765/>. |
| `open_browser` | True          | Set to `False` if you want to open the page in your browser yourself.   |

Example:

```python
easy_draw.load_canvas(port = 8000, open_browser = False)
```

## **Changing the Background Color**

`set_canvas_color(color)`

Used to change the canvas background color at any point in the program.

Example:

```python
easy_draw.set_canvas_color(color = (0, 0, 255))
```

## Ending the Program

`end()`

Every Easy Draw program must end with this function call. It keeps your program running so the browser can send events (like clicks and key presses) to your program.

Closing the Easy Draw browser tab (or pressing Ctrl+C) stops your program.

```python
easy_draw.end()
```

To print the finished page's HTML code, use `print_html=True`:

```python
easy_draw.end(print_html = True)
```


# Colors

There are 3 ways you can use colors in Easy Draw:

## 1. Name of the Color

The easiest way to represent a color is by using the color's name in a string.

Examples:

```python
color = "red"
color = "green"
color = "blue"
color = "white"
color = "black"
```

Easy Draw uses the color names your web browser knows. Here is the full list of color names:

{% embed url="<https://developer.mozilla.org/en-US/docs/Web/CSS/named-color>" %}

{% hint style="info" %}
Color names with spaces, like `"sky blue"`, work the same as `"skyblue"`. Gray shades from `"gray0"` (black) to `"gray100"` (white) also work.
{% endhint %}

## 2. RGB Value

You can define a color as a tuple with 3 color values representing red, green, and blue. This is known as “RGB”. RGB stands for Red, Green, and Blue. We specify how much red, green, and blue to use by a number range of 0-255. No light is zero. Turn the light on all the way on and it is 255. We need three numbers to specify three colors, so (0, 0, 0) means no red, no green, no blue -- Black.

Here are some other examples:

| **Red** | **Green** | **Blue** | **Color** |
| ------- | --------- | -------- | --------- |
| 0       | 0         | 0        | Black     |
| 255     | 255       | 255      | White     |
| 127     | 127       | 127      | Gray      |
| 255     | 0         | 0        | Red       |
| 0       | 255       | 0        | Green     |
| 0       | 0         | 255      | Blue      |
| 255     | 255       | 0        | Yellow    |

Examples:

```python
color = (255, 0, 0)
color = (0, 255, 0)
color = (0, 0, 255)
color = (255, 255, 255)
color = (0, 0, 0)
```

To turn an RGB value into a hex value, use `rgb_convert()`:

```python
hex_color = easy_draw.rgb_convert((255, 0, 0))    # "#ff0000"
```

## 3. Hex Value

Hex color values represent color in the same way as RGB, but instead of decimal (base 10) number values they use hexadecimal (base 16) values.

A hexadecimal color is specified with: `#RRGGBB`.

RR (red), GG (green) and BB (blue) are hexadecimal integers between 00 and FF specifying the intensity of the color.

For example, `#0000FF` is displayed as blue, because the blue component is set to its highest value (FF) and the others are set to 00.

Examples:

```python
color = "#FF0000"
color = "#00FF00"
color = "#0000FF"
color = "#FFFFFF"
color = "#000000"
```

## Easy Draw's Color Picker

To make it easy to discover colors, the Easy Draw page has a **Color Picker** button.

The color picker comes from your web browser, so it will look different in different browsers.

When you select a color, the Easy Draw page displays the Hex and RGB value for you to record and use in your program.


# Drawing Shapes

When drawing shapes, the sequence matters. That is how the layering system works.

The first object in sequence that is drawn in your code will be at the bottom most layer of your drawing. The last object in sequence that is drawn in your code will be the top most layer of your drawing.

Every shape is a child class of `Shape`, so they all share the same [object methods](https://easy-draw.joemazzone.net/python/module-reference/object-methods).

## Rectangle

`Rectangle(xy, width, height)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MR_X4Wtqc7FkpTp_iKw%2F-MR_brBio-EXXyHCGBw8%2Fimage.png?alt=media\&token=a11a1446-bff5-41de-bb68-69687d7b414d)

| **Property**   | **Default Value**     | **Description**                                                                              |
| -------------- | --------------------- | -------------------------------------------------------------------------------------------- |
| `xy`           | REQUIRED (No default) | The x and y coordinate of the rectangle's top-left corner as a tuple.                        |
| `width`        | REQUIRED (No default) | The width of the rectangle in pixels.                                                        |
| `height`       | REQUIRED (No default) | The height of the rectangle in pixels.                                                       |
| `color`        | "black"               | RGB tuple color value, hexadecimal color value, or string containing color name can be used. |
| `border_color` | None                  | Color of the border.                                                                         |
| `border_width` | 0                     | Size of the border in pixels.                                                                |
| `dashes`       | None                  | Size of the dashes for the border in pixels.                                                 |
| `visible`      | True                  | <p>True = Shape can be seen.</p><p>False = Shape cannot be seen.</p>                         |

Example:

```python
rect1 = easy_draw.Rectangle(
    xy = (300, 300), 
    width = 200, 
    height = 150,
    color = (255, 0, 0),          # Optional Property
    border_color = (0, 0, 0),     # Optional Property
    border_width = 10,            # Optional Property
    dashes = 25,                  # Optional Property
    visible = True                # Optional Property
)
```

{% hint style="info" %}
A Rectangle can rotate around its center or its top-left corner: `rect1.rotate(45, from_top_left = True)`
{% endhint %}

## Regular Polygon

`RegPolygon(nsides, center_xy, radius)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MR_X4Wtqc7FkpTp_iKw%2F-MR_cru4Phqg61haLd1f%2Fimage.png?alt=media\&token=328f7cf3-9628-43e9-ad94-853cd45011f1)

| Property       | Default Value         | Description                                                                                  |
| -------------- | --------------------- | -------------------------------------------------------------------------------------------- |
| `nsides`       | REQUIRED (No default) | The number of sides the polygon has.                                                         |
| `center_xy`    | REQUIRED (No default) | The x and y coordinate of the polygon's center as a tuple.                                   |
| `radius`       | REQUIRED (No default) | The distance in pixels from the center to any outer point.                                   |
| `color`        | "black"               | RGB tuple color value, hexadecimal color value, or string containing color name can be used. |
| `border_color` | None                  | Color of the border.                                                                         |
| `border_width` | 0                     | Size of the border in pixels.                                                                |
| `dashes`       | None                  | Size of the dashes for the border in pixels.                                                 |
| `visible`      | True                  | <p>True = Shape can be seen.</p><p>False = Shape cannot be seen.</p>                         |

Example:

```python
reg_poly1 = easy_draw.RegPolygon(
    nsides = 8,
    center_xy = (300, 300), 
    radius = 100, 
    color = (255, 0, 0),      # Optional Property
    border_color = (0, 0, 0), # Optional Property
    border_width = 10,        # Optional Property
    dashes = 25               # Optional Property
)
```

## Polygon

`Polygon(points_list)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MR_cunQqfAZ7Fzz-G2D%2F-MR_fjwaZO4mP9XlS2rC%2Fimage.png?alt=media\&token=5780ee7e-667c-4a32-b299-a95d92b83d35)

*The above image is just an example. The Polygon can have as many sides as you want, and is dependent on the number of xy coordinates you provide.*

| Property       | Default Value         | Description                                                                                               |
| -------------- | --------------------- | --------------------------------------------------------------------------------------------------------- |
| `points_list`  | REQUIRED (No default) | A list of x y coordinates identifying the points of the polygon. List must have an even number of values. |
| `color`        | "black"               | RGB tuple color value, hexadecimal color value, or string containing color name can be used.              |
| `border_color` | None                  | Color of the border.                                                                                      |
| `border_width` | 0                     | Size of the border in pixels.                                                                             |
| `dashes`       | None                  | Size of the dashes for the border in pixels.                                                              |
| `visible`      | True                  | <p>True = Shape can be seen.</p><p>False = Shape cannot be seen.</p>                                      |

The `points_list` property MUST have an even number of values. It must consist of xy pairs for each point.

Example:

```python
poly1 = easy_draw.Polygon(
    points_list = [25, 25, 150, 25, 200, 200, 100, 250, 25, 200], 
    color = (255, 0, 0),       # Optional Property
    border_color = (0, 0, 0),  # Optional Property
    border_width = 10,         # Optional Property
    dashes = 25                # Optional Property
)
```

## Line

`Line(xy1, xy2)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MU-P9t60n8INhnBrz6e%2F-MU-ZaAMGoIFqzFnz8El%2Fimage.png?alt=media\&token=433a7851-d0ce-4911-8bdf-3488daa6d6fe)

OR

`Line(points_list = [...])`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MU-P9t60n8INhnBrz6e%2F-MU-ZJGBV1J0VGjttyKV%2Fimage.png?alt=media\&token=2cf2488d-c786-45e1-87a8-0153e6d938ce)

| Property      | Default Value                                             | Description                                                                                            |
| ------------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| `xy1`         | REQUIRED if `points_list` is not provided (No default)    | The starting xy coordinate of the line as a tuple.                                                     |
| `xy2`         | REQUIRED if `points_list` is not provided (No default)    | The ending xy coordinate of the line as a tuple.                                                       |
| `points_list` | REQUIRED if `xy1` and `xy2` are not provided (No default) | A list of x y coordinates identifying the points of the line. List must have an even number of values. |
| `color`       | "black"                                                   | RGB tuple color value, hexadecimal color value, or string containing color name can be used.           |
| `thickness`   | 5                                                         | The width of the line.                                                                                 |
| `dashes`      | None                                                      | Size of the dashes for the line in pixels.                                                             |
| `arrow_start` | False                                                     | Add an arrow to the start of the line.                                                                 |
| `arrow_end`   | False                                                     | Add an arrow to the end of the line.                                                                   |
| `style`       | "round"                                                   | Set property to `"round"` for round edges and joints and `"cut"` for squared/cut-off edges and joints. |
| `visible`     | True                                                      | <p>True = Shape can be seen.</p><p>False = Shape cannot be seen.</p>                                   |

Example:

```python
line1 = easy_draw.Line(
    xy1 = (100, 100), 
    xy2 = (200, 200),
    thickness = 8,          # Optional Property
    color = (255, 0, 0),    # Optional Property
    dashes = 25             # Optional Property
)

# OR

line1 = easy_draw.Line(
    points_list = [50, 500, 100, 450, 150, 500, 200, 450],
    thickness = 8,          # Optional Property
    color = (0, 255, 0),    # Optional Property
    dashes = 25,            # Optional Property
    style = "cut"           # Optional Property
)
```

## Circle

`Circle(center_xy, radius)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MR_gAyOFo4wA1T_3cRr%2F-MR_i0W_lHdud28t__p9%2Fimage.png?alt=media\&token=cd71f25b-7435-40c9-9c31-9ba540ba0a52)

| Property       | Default Value         | Description                                                                                  |
| -------------- | --------------------- | -------------------------------------------------------------------------------------------- |
| `center_xy`    | REQUIRED (No default) | The center coordinate (x, y) of the circle.                                                  |
| `radius`       | REQUIRED (No default) | The measurement in pixels from the center of the circle to the edge.                         |
| `color`        | "black"               | RGB tuple color value, hexadecimal color value, or string containing color name can be used. |
| `border_color` | None                  | Color of the border.                                                                         |
| `border_width` | 0                     | Size of the border in pixels.                                                                |
| `dashes`       | None                  | Size of the dashes for the border in pixels.                                                 |
| `visible`      | True                  | True = Shape can be seen. False = Shape cannot be seen.                                      |

Example:

```python
cir1 = easy_draw.Circle(
    center_xy = (300, 300), 
    radius = 100, 
    color = (255, 0, 0),          # Optional Property
    border_color = (0, 0, 0),     # Optional Property
    border_width = 10,            # Optional Property
    dashes = 25                   # Optional Property
)
```

## Oval

`Oval(center_xy, width, height)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MR_gAyOFo4wA1T_3cRr%2F-MR_ioK19DUZDAWjeepO%2Fimage.png?alt=media\&token=810c11cf-a128-4495-b61c-2224fdaaa984)

| Property       | Default Value         | Description                                                                                  |
| -------------- | --------------------- | -------------------------------------------------------------------------------------------- |
| `center_xy`    | REQUIRED (No default) | The center coordinate (x, y) of the oval.                                                    |
| `width`        | REQUIRED (No default) | The measurement in pixels of the left edge to the right edge of the oval.                    |
| `height`       | REQUIRED (No default) | The measurement in pixels of the top edge to the bottom edge of the oval.                    |
| `color`        | "black"               | RGB tuple color value, hexadecimal color value, or string containing color name can be used. |
| `border_color` | None                  | Color of the border.                                                                         |
| `border_width` | 0                     | Size of the border in pixels.                                                                |
| `dashes`       | None                  | Size of the dashes for the border in pixels.                                                 |
| `visible`      | True                  | <p>True = Shape can be seen.</p><p>False = Shape cannot be seen.</p>                         |

Example:

```python
oval1 = easy_draw.Oval(
    center_xy = (300, 300), 
    width = 100, 
    height = 200, 
    color = (255, 0, 0),       # Optional Property
    border_color = (0, 0, 0),  # Optional Property
    border_width = 10,         # Optional Property
    dashes = 25                # Optional Property
)
```

## Arc

`Arc(center_xy, width, height, sweep_angle)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MR_j3WiqNf06YQqsd1G%2F-MR_nS8Sjg0QA5oZFX7U%2Fimage.png?alt=media\&token=3d9458ea-cdd3-4dd7-b3e8-288e347ff887)

There are 3 different styles:

![](https://tkdocs.com/shipman/img/chord.png)

*Note: The "arc" style is only an outline. It uses the `border_color` (or the `color` if there is no `border_color`) and the `border_width` (at least 1 pixel).*

| Property       | Default Value         | Description                                                                                  |
| -------------- | --------------------- | -------------------------------------------------------------------------------------------- |
| `center_xy`    | REQUIRED (No default) | The center coordinate (x, y) of the circle used to create the arc.                           |
| `width`        | REQUIRED (No default) | The width of the circle used to create the arc.                                              |
| `height`       | REQUIRED (No default) | The height of the circle used to create the arc.                                             |
| `sweep_angle`  | REQUIRED (No default) | The amount of the arc to show. From 0 to the angle in degrees identified.                    |
| `color`        | "black"               | RGB tuple color value, hexadecimal color value, or string containing color name can be used. |
| `border_color` | None                  | Color of the border.                                                                         |
| `border_width` | 0                     | Size of the border in pixels.                                                                |
| `dashes`       | None                  | Size of the dashes for the border in pixels.                                                 |
| `style`        | "pieslice"            | The arc comes in three styles choices: "pieslice", "chord", and "arc"                        |
| `visible`      | True                  | True = Shape can be seen. False = Shape cannot be seen.                                      |

Example:

```python
arc1 = easy_draw.Arc(
    center_xy = (300, 300), 
    width = 100, 
    height = 100, 
    sweep_angle = 90,
    style = "chord",           # Optional Property
    color = (255, 0, 0),       # Optional Property
    border_color = (0, 0, 0),  # Optional Property
    border_width = 10,         # Optional Property
    dashes = 25                # Optional Property
) 
```


# Text and Images

## Text

`Text(center_xy, text)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MR_npajpEZf8wpIj8HL%2F-MRaFmdYU9IGnMtLINHu%2Fimage.png?alt=media\&token=d19c999e-dfc5-4ad0-920b-73d86b65957a)

| Property        | Default Value         | Description                                                                                    |
| --------------- | --------------------- | ---------------------------------------------------------------------------------------------- |
| `center_xy`     | REQUIRED (No default) | The center coordinate (x, y) of where to draw the text.                                        |
| `text`          | `""` - empty string   | The text you want to display.                                                                  |
| `color`         | "black"               | RGB tuple color value, hexadecimal color value, or string containing color name can be used.   |
| `font`          | "Arial"               | The font family used for the text. Font must be installed on the computer viewing the drawing. |
| `size`          | 16                    | The font size of the text.                                                                     |
| `bold`          | False                 | When set to True, it bolds the text.                                                           |
| `italic`        | False                 | When set to True, it italicizes the text.                                                      |
| `underline`     | False                 | When set to True, it underlines the text.                                                      |
| `strikethrough` | False                 | When set to True, it strikes-out the text.                                                     |
| `visible`       | True                  | <p>True = Text can be seen.</p><p>False = Text cannot be seen.</p>                             |

Example:

```python
words = easy_draw.Text(
    center_xy = (300,100), 
    text = "I Love Python",  
    color = (0, 200, 50),          # Optional Property
    font = "Times",                # Optional Property
    size = 32,                     # Optional Property
    bold = True,                   # Optional Property
    italic = True,                 # Optional Property
    underline = True,              # Optional Property
    strikethrough = True,          # Optional Property
    visible = True                 # Optional Property
)
```

## Images

First thing that needs to be done to use an image is open it in Easy Draw with the `open_image()` function.

The `open_image()` function requires 1 positional argument - `filename`. The image file should be in the same folder as your program.

```python
pic = easy_draw.open_image("super_cool_image.png")
```

Easy Draw can open `.png`, `.gif`, `.jpg`, `.webp`, `.bmp`, and `.svg` images.

### Images from the Internet

`open_image()` also works with a public image link that starts with `http://` or `https://`.

```python
pic = easy_draw.open_image("https://example.com/cat.png")
```

{% hint style="info" %}
Make sure you copy the image's address (right-click the image and choose "Copy image address"), not the web page's address.

The browser loads the image straight from the link, so viewing the drawing needs an internet connection.
{% endhint %}

### Drawing the Image

Then you can create an image object.

`Image(center_xy, image)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MR_npajpEZf8wpIj8HL%2F-MRaGEPex2n6zJasiFXn%2Fimage.png?alt=media\&token=4ad09f11-5064-4217-b1ea-0e630e426741)

| Property    | Default Value                      | Description                                                                                                           |
| ----------- | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `center_xy` | <p>REQUIRED</p><p>(No default)</p> | The center coordinate (x, y) of where to draw the image.                                                              |
| `image`     | <p>REQUIRED</p><p>(No default)</p> | <p>The image file to draw.</p><p>Use the <code>open\_image()</code> function to create the required image object.</p> |
| `visible`   | True                               | <p>True = Image can be seen.</p><p>False = Image cannot be seen.</p>                                                  |

Example:

```python
pic = easy_draw.open_image("super_cool_image.png")

img = easy_draw.Image(
    center_xy = (300,300),
    image = pic
)
```

Images can rotate, just like every other Easy Draw object:

```python
img.rotate(45)
```


# Property Getting and Setting

## Property Getting

`object.property_name`

To get any property from an Easy Draw object, simply use the variable name storing the object dot the name of the property.

Example: Getting the `radius` property from a Regular Polygon object named `pentagon`

```python
pentagon.radius
```

Example: Getting the `color` property from a Text object named `title`

```python
title.color
```

## Property Setting

`object.set_property(property_name = new_value)`

To set a property to a new value, you can call the `.set_property()` method on the object you want to change, identifying the property you want to change and its new value.

Example: Changing the `text` property of a Text object named `title`

```python
title.set_property(text = "Player 1 has selected a character...")
```

Example: Changing the `width` property of a Rectangle object named `box`

```python
box.set_property(width = 200)
```

You can change more than one property at a time:

```python
box.set_property(width = 200, color = "red")
```

### Setting a Property Directly

`object.property_name = new_value`

You can also change a property by assigning it a new value. This works the same as `.set_property()`.

```python
box.width = 200
title.text = "Player 1 has selected a character..."
```

{% hint style="info" %}
If you misspell a property name in `.set_property()`, Easy Draw shows an error that lists the properties you can set.
{% endhint %}

## Examples

In this example we will create a square with a random color and an octagon with default color, `"black"`. Whenever the octagon is clicked, its color will change to the square's color.

To do this, we need to get the `color` property of the square and set the `color` property of the octagon.

Get the square's color property -- `square.color`

Set the octagon's property -- `octagon.set_property()`

```python
import easy_draw
import random

easy_draw.load_canvas()

square = easy_draw.Rectangle(
    xy = (100, 100), 
    width = 200, 
    height = 200,
    color = random.choice(["blue", "red", "yellow", "green", "orange", "purple"])
)

octagon = easy_draw.RegPolygon(
    center_xy = (400, 400),
    radius = 100, 
    nsides = 8
)

def click_octagon(event):
    global square
    global octagon
    octagon.set_property(color = square.color)

octagon.event_setup("<Button-1>", click_octagon)

easy_draw.end()
```

In this example, we create a growing circle by increasing the circle's radius by 10 each time it is clicked.

Notice how the Circle object's `radius` property is set to the current `cir.radius` plus 10.

```python
import easy_draw

easy_draw.load_canvas()

cir = easy_draw.Circle(
    center_xy = (300, 300),
    radius = 20
)

def click_circle(event):
    global cir
    cir.set_property(radius = cir.radius + 10)

cir.event_setup("<Button-1>", click_circle)

easy_draw.end()
```


# Object Methods

## `.rotate(angle)`

Rotates an Easy Draw object by a specified amount of degrees around its center.

Positive numbers rotate the shape clockwise (to the right). Negative numbers rotate the shape counter-clockwise (to the left). This is the same for every object, including `Arc` and `Text`.

Example:

```python
rect1.rotate(45)
```

A `Rectangle` can also rotate around its top-left corner instead of its center:

```python
rect1.rotate(45, from_top_left = True)
```

The `angle` property tells you how far an object has been rotated in total.

```python
print(rect1.angle)
```

**Unsupported objects:** None

## `.erase()`

Deletes the object from the canvas. Once erased, an object can no longer be referenced.

Example:

```python
rect1.erase()
```

**Unsupported objects:** None

## `.to_string()`

Returns the string representation of the object. The string will include the object type and ID number used by Easy Draw.

Example:

```python
print(rect1.to_string())
```

**Unsupported objects:** None

## The `Shape` Parent Class

Every Easy Draw drawing object (`Rectangle`, `Circle`, `Text`, `Image`, and the rest) is a child class of `Shape`. That is why they all share the methods on this page.

```python
print(isinstance(rect1, easy_draw.Shape))    # True
```

## Others

For information on the `.set_property()` method see:

{% content-ref url="/pages/-MRAvKSob\_wbDI1gz9NW" %}
[Property Getting and Setting](https://easy-draw.joemazzone.net/python/module-reference/property-getters-and-setters)
{% endcontent-ref %}

For information on the `.event_setup()` method see:

{% content-ref url="/pages/-MRAvSb83fmXckFG2fA6" %}
[Event Handling](https://easy-draw.joemazzone.net/python/module-reference/event-handling)
{% endcontent-ref %}


# Event Handling

## Events List

Easy Draw uses Tkinter-style event names. The browser sends these events to your program while it is running. Here is a detailed list of event formats:

* `<Button-1>`
  * A mouse button is pressed over the object. Button 1 is the leftmost button, button 2 is the middle button (where available), and button 3 the rightmost button. The current position of the mouse pointer (relative to the canvas) is provided in the x and y members of the event object passed to the handler.
  * You can use ButtonPress instead of Button, or even leave it out completely: `<Button-1>`, `<ButtonPress-1>`, and `<1>` are all synonyms. For clarity, I prefer the `<Button-1>` syntax.
* `<B1-Motion>`
  * The mouse is moved, with mouse button 1 being held down (use B2 for the middle button, B3 for the right button). The current position of the mouse pointer is provided in the x and y members of the event object passed to the handler.
* `<Motion>`
  * The mouse is moved over the object.
* `<ButtonRelease-1>`
  * Button 1 was released. The current position of the mouse pointer is provided in the x and y members of the event object passed to the handler.
* `<Double-Button-1>`
  * Button 1 was double clicked. You can use Double or Triple as prefixes. If you bind both a single click (`<Button-1>`) and a double click, the double click runs the `<Double-Button-1>` handler instead of a second `<Button-1>`.
* `<Enter>`
  * The mouse pointer entered the object (this event doesn’t mean that the user pressed the Enter key!).
* `<Leave>`
  * The mouse pointer left the object.
* `<MouseWheel>`
  * The mouse wheel was turned. How far it moved is in the delta member of the event object.
* `<FocusIn>`
  * Keyboard focus was moved to the Easy Draw page.
* `<FocusOut>`
  * Keyboard focus was moved from the Easy Draw page to another window or tab.
* `<Return>`
  * The user pressed the Enter key. You can bind to virtually all keys on the keyboard. The special keys are BackSpace, Tab, Return (the Enter key), Escape, Shift\_L / Shift\_R, Control\_L / Control\_R, Alt\_L / Alt\_R, Caps\_Lock, Prior (Page Up), Next (Page Down), End, Home, Left, Up, Right, Down, Insert, Delete, and F1 through F12.
* `<Key>`
  * The user pressed any key. The key is provided in the char member of the event object passed to the handler (this is an empty string for special keys).
* `<KeyRelease>`
  * The user let go of a key. You can add a key name, like `<KeyRelease-Up>`.
* `a`
  * The user typed an “a”. Most printable characters can be used as is. The exceptions are space (`<space>`) and less than (`<less>`). Note that `1` is a keyboard binding, while `<1>` is a button binding.
* `<Shift-Up>`
  * The user pressed the Up arrow, while holding the Shift key pressed. You can use prefixes like Alt, Shift, and Control.

{% hint style="info" %}
Key presses only reach Easy Draw when the Easy Draw page is the active browser tab. Click on the page first if your key events are not working.
{% endhint %}

Each of these events have useful properties that can be retrieved in the event handler function:

* `x`, `y`
  * The current mouse position on the canvas, in pixels.
* `x_root`, `y_root`
  * The current mouse position relative to the upper left corner of the screen, in pixels.
* `char`
  * The character typed (keyboard events only), as a string.
* `keysym`
  * The key symbol, like `"a"`, `"Up"`, or `"space"` (keyboard events only).
* `keycode`
  * The key code (keyboard events only).
* `num`
  * The button number (mouse button events only).
* `delta`
  * How far the mouse wheel moved (mouse wheel events only).
* `type`
  * The event type, like `"ButtonPress"` or `"KeyPress"`.

## Event Handlers

To create an event handler, you simply just create a function definition and provide it with `event` as a parameter. Inside the definition, you provide the statements you wish to be executed when the event is triggered.

**Example:**

```python
def click_octagon(event):
    global octagon
    color = random.choice(["blue", "red", "yellow", "green", "orange", "purple"])
    octagon.set_property(color=color)
    octagon.rotate(10)

octagon.event_setup("<Button-1>", click_octagon)
```

Event handlers run one at a time, in the order the events happen.

## Binding an Event to an Easy Draw Object

`object.event_setup(event, handler)`

To attach or bind an event and handler to an Easy Draw object you must use the `.event_setup()` method and provide the event name and handler function name as parameters.

**Example:** Bind a `<Button-1>` event with handler named `click_octagon` to the object stored in `octagon`.

```python
octagon.event_setup("<Button-1>", click_octagon)
```

## Binding an Event to the Canvas

`canvas_event_setup(event, handler)`

To attach or bind an event and handler to the entire Easy Draw canvas you must use the `canvas_event_setup()` function and provide the event name and handler function name as parameters.

*It is recommended to bind keyboard events to the entire canvas instead of binding key events to a specific object.*

**Example:** Bind a `<Up>` arrow key event with handler named `move_up` .

```python
easy_draw.canvas_event_setup("<Up>", move_up)
```

## Animations

You can animate a drawing with a loop and `time.sleep()`. The browser shows each change while the loop runs.

```python
import easy_draw
import time

easy_draw.load_canvas()

ball = easy_draw.Circle(
    center_xy = (50, 300),
    radius = 25,
    color = "red"
)

for i in range(50):
    ball.center_xy = (ball.center_xy[0] + 10, 300)
    time.sleep(0.05)

easy_draw.end()
```


# Saving Your Drawing

## Your Drawing is Already Saved

Every time your program runs, Easy Draw writes your drawing to an `index.html` file in the same folder as your program. Open `index.html` in a web browser any time to see your drawing again.

## Using the Button

You can save your drawing as a PNG file by clicking the **Save Canvas** button in the Easy Draw page. Just be sure to provide the image with a file name.

Your web browser downloads the picture, so it will save wherever your browser saves downloads (most likely your Downloads folder).

## `save_canvas()` Function

If you want to programmatically save the canvas, you can use the `save_canvas()` function. The picture saves as a .png file in the same folder as your program.

```python
easy_draw.save_canvas()
```

Without a file name, the function asks for the file's name in the terminal.

If you want to use the `save_canvas()` function without asking each time, you must provide a file name to save the image as.

```python
easy_draw.save_canvas("my_pic")
```

{% hint style="info" %}
The picture is created by your web browser, so your drawing must be open in a browser tab. If it is not open yet, Easy Draw waits and saves the picture once the page opens.
{% endhint %}

Images loaded from a link with `open_image()` are copied into the saved picture. If the image's website does not allow that, Easy Draw downloads the image itself to include it.


# Power Users

## How the Browser Version Works

When you call `load_canvas()`, Easy Draw starts a small web server on your computer (<http://localhost:8765/>) and opens it in your web browser. Your program sends drawing changes to the page, and the page sends clicks and key presses back to your event handlers.

The drawing is also written to `index.html` in the same folder as your program. It is a single file with everything it needs, so you can share it or post it online to show off your drawing. The page only reacts to events while your program is running.

## Options

Use a different port, or open the page yourself:

```python
easy_draw.load_canvas(port = 8000, open_browser = False)
```

Print the finished page's HTML code:

```python
easy_draw.end(print_html = True)
```

## Using other Tkinter capabilities

The browser version does not use Tkinter, so `easy_draw.WINDOW` and `easy_draw.CANVAS` are not available.

If you need Tkinter, use the desktop version, `easy_draw_desktop.py`. It is the original Tkinter window version of Easy Draw.

```python
import easy_draw_desktop as easy_draw
```

Easy Draw's desktop version is just a Tkinter GUI window. It has all the capabilities of any Tkinter app.

{% embed url="<https://tkdocs.com/shipman/>" %}

You can modify or add to Easy Draw's Tkinter window by referencing the Easy Draw variable `easy_draw.WINDOW`

You can modify or add to Easy Draw's canvas by referencing the Easy Draw variable `easy_draw.CANVAS`


# Issues and Features Coming Soon...

Found a bug or have an idea? File an issue on GitHub: <https://github.com/MrMazzone/easy-draw/issues>

## Fixed in 2.0

* [x] Oval object does not rotate properly. <https://github.com/MrMazzone/easy-draw/issues/1>
* [x] Option to rotate the Rectangle by top-left instead of center. <https://github.com/MrMazzone/easy-draw/issues/2>
* [x] `Image` object - `rotate()` method support.

## Here are some features that are planned:

### Drawing

* [ ] Motion methods to animate objects more easily.
* [ ] Overlap event handling for games and animation.
* [ ] Method for calculating distance between two shapes for games and animation.
* [ ] Gradients for shape object color.
* [ ] Opacity / Transparency for shape objects.

### Inspecting Your Drawing

* [ ] Ctrl + Click on shape to see properties (in pop-up window or to the right of canvas)
* [ ] Ctrl + Click generates red dots on each point of the selected shape. Hovering over the point will give you x and y value.


# Unit 1: Drawing Basics

In this unit students write their first Easy Draw programs. They only need to know how to **call functions** and pass **arguments**. By the end, students can plan and code a full drawing made of shapes, colors, text, and images.

{% hint style="info" %}
**Teacher notes**

* **Time:** 11 class periods: 6 lessons (1 class each) and 5 classes for the unit project
* **Before this unit:** students can run a Python program and know what `print("Hello")` does.
* **Setup:** each student needs `easy_draw.py` in their project folder. See [Setup and Install](https://easy-draw.joemazzone.net/python/setup-and-install).
  {% endhint %}

## Learning Objectives

Students will be able to:

1. Import a module and call its functions using the dot operator.
2. Locate points on the Easy Draw coordinate plane, where (0, 0) is the top-left corner and y grows downward.
3. Create shapes by calling constructor functions with required and optional (keyword) arguments.
4. Describe colors with names, RGB tuples, and hex values.
5. Store an object in a variable and change it with methods like `.rotate()` and `.set_property()`.
6. Explain why the order of statements controls which shapes are on top.

## Lesson 1.1: Your First Drawing

Every Easy Draw program has the same three parts: import the module, load the canvas, and end the program.

```python
import easy_draw

easy_draw.load_canvas()

sun = easy_draw.Circle(
    center_xy = (300, 300),
    radius = 100,
    color = "yellow"
)

easy_draw.end()
```

Run the program. Your drawing opens in your web browser. Point out to students:

* `import easy_draw` lets us use the module. Every Easy Draw command starts with `easy_draw.`
* `load_canvas()` must come first and `end()` must come last.
* Easy Draw also saves the drawing to `index.html` in the project folder.
* Closing the browser tab stops the program.

**Practice:** Change the circle's `radius` and `color`. Run the program again after each change.

## Lesson 1.2: The Coordinate Plane

The canvas is 600 pixels wide and 600 pixels tall. (0, 0) is the **top-left** corner and (600, 600) is the **bottom-right** corner. As y gets bigger, things move **down**.

Have students click the **Grid** button on the Easy Draw page and move the mouse around the canvas. The bottom-right corner of the page shows the mouse's coordinates.

**Practice:** Draw a small circle in each corner of the canvas and one in the middle.

```python
import easy_draw

easy_draw.load_canvas()

top_left = easy_draw.Circle(center_xy = (50, 50), radius = 25)
top_right = easy_draw.Circle(center_xy = (550, 50), radius = 25)
bottom_left = easy_draw.Circle(center_xy = (50, 550), radius = 25)
bottom_right = easy_draw.Circle(center_xy = (550, 550), radius = 25)
middle = easy_draw.Circle(center_xy = (300, 300), radius = 25, color = "red")

easy_draw.end()
```

**Discussion:** Why is the circle at (550, 50) at the *top* of the canvas and not the bottom?

## Lesson 1.3: Shapes and Arguments

Introduce each shape and its **required** arguments. Every other argument is **optional** and has a default value.

| Shape        | Required arguments                            |
| ------------ | --------------------------------------------- |
| `Rectangle`  | `xy`, `width`, `height`                       |
| `Circle`     | `center_xy`, `radius`                         |
| `Oval`       | `center_xy`, `width`, `height`                |
| `RegPolygon` | `nsides`, `center_xy`, `radius`               |
| `Polygon`    | `points_list`                                 |
| `Line`       | `xy1`, `xy2`                                  |
| `Arc`        | `center_xy`, `width`, `height`, `sweep_angle` |

Point out that a `Rectangle` is placed by its **top-left corner**, while circles, ovals, and polygons are placed by their **center**.

```python
import easy_draw

easy_draw.load_canvas()

box = easy_draw.Rectangle(xy = (50, 50), width = 200, height = 100, color = "blue")
ball = easy_draw.Circle(center_xy = (450, 100), radius = 50, color = "orange")
egg = easy_draw.Oval(center_xy = (150, 300), width = 80, height = 120, color = "tan")
stop_sign = easy_draw.RegPolygon(nsides = 8, center_xy = (450, 300), radius = 70, color = "red")
roof = easy_draw.Polygon(points_list = [50, 550, 150, 450, 250, 550], color = "brown")
path = easy_draw.Line(xy1 = (300, 450), xy2 = (550, 550), thickness = 8)
pie = easy_draw.Arc(center_xy = (450, 500), width = 100, height = 100, sweep_angle = 270, color = "gold")

easy_draw.end()
```

**Practice:**

1. Draw a square with a thick black border (`border_color` and `border_width`).
2. Draw a triangle with `RegPolygon` and a triangle with `Polygon`. Which one was easier to place?
3. Draw a dashed line using `dashes`.

Students can look up every property in the [Module Reference](https://easy-draw.joemazzone.net/python/module-reference).

## Lesson 1.4: Colors

Colors can be written three ways:

```python
color = "skyblue"         # A color name
color = (135, 206, 235)   # An RGB tuple: red, green, blue from 0 to 255
color = "#87CEEB"         # A hex value
```

Have students use the **Color Picker** button on the Easy Draw page to find a color and copy its hex or RGB value into their code.

**Practice:** Draw three squares that are the same color, using a name for the first, RGB for the second, and hex for the third.

See [Colors](https://easy-draw.joemazzone.net/python/module-reference/colors) for more.

## Lesson 1.5: Layers, Text, and Images

Shapes are drawn in the order the code runs. The **first** shape is on the **bottom**. The **last** shape is on **top**.

```python
import easy_draw

easy_draw.load_canvas(background = "skyblue")

grass = easy_draw.Rectangle(xy = (0, 450), width = 600, height = 150, color = "green")
sun = easy_draw.Circle(center_xy = (500, 100), radius = 60, color = "yellow")
cloud = easy_draw.Oval(center_xy = (450, 120), width = 160, height = 60, color = "white")
title = easy_draw.Text(center_xy = (300, 40), text = "A Sunny Day", size = 32, bold = True)

easy_draw.end()
```

**Discussion:** The cloud covers part of the sun. How would you put the sun in front of the cloud?

Images work in two steps: open the image file, then draw it.

```python
pic = easy_draw.open_image("my_pet.png")
pet = easy_draw.Image(center_xy = (300, 300), image = pic)
```

The image file must be in the same folder as the program. A public image link that starts with `https://` also works.

## Lesson 1.6: Objects, Methods, and Properties

When we store a shape in a variable, we can change it later.

```python
import easy_draw

easy_draw.load_canvas()

box = easy_draw.Rectangle(xy = (200, 200), width = 200, height = 200, color = "purple")

box.rotate(45)                           # A method: do something
box.set_property(color = "orange")       # Change a property
print(box.width)                         # Get a property

easy_draw.end()
```

Vocabulary to introduce:

* **Object** - a thing we made, like the rectangle stored in `box`.
* **Property** - information about an object, like `width` or `color`.
* **Method** - something an object can do, like `.rotate()` or `.erase()`.

**Practice:** Draw a rectangle, then use `.rotate()` to turn it into a diamond. Print its `color` property.

## Unit Project: My Scene

Students plan and code an original scene, like a landscape, a room, a city skyline, or a favorite place.

**Steps:**

1. Sketch the scene on graph paper (or a printed 600 x 600 grid) and label the coordinates of each shape.
2. Code the scene. Run it often to check each new shape.
3. Use the **Save Canvas** button to save a picture of the finished drawing.

**Requirements:**

* At least 15 shapes using at least 5 different kinds of shapes.
* At least one color written as RGB and one written as hex.
* At least one shape uses `border_color`, `border_width`, or `dashes`.
* At least one `Text` object.
* At least one object changed with `.rotate()` or `.set_property()`.
* Comments that explain each part of the scene.

| Category     | 4 - Exceeds                                     | 3 - Meets                   | 2 - Approaching                    | 1 - Beginning              |
| ------------ | ----------------------------------------------- | --------------------------- | ---------------------------------- | -------------------------- |
| Shapes       | 20+ shapes, 6+ kinds, carefully placed          | 15+ shapes, 5+ kinds        | 10+ shapes or fewer kinds          | Fewer than 10 shapes       |
| Colors       | Names, RGB, and hex used thoughtfully           | RGB and hex both used       | Only one way of writing colors     | Default colors only        |
| Objects      | Several objects changed with methods/properties | At least one object changed | Variables used but nothing changed | No variables               |
| Code quality | Clear variable names and comments throughout    | Comments explain each part  | Few comments                       | No comments                |
| Design       | Original, detailed, and polished                | Scene is clear and complete | Scene is unfinished                | Scene is hard to recognize |

{% hint style="success" %}
Want to share the best work? Students can submit their drawings to the [Student Developed Art](https://easy-draw.joemazzone.net/student-developed-art) page.
{% endhint %}


# Unit 2: Drawing Algorithms

In this unit students let the computer do the repetitive work. They use **variables**, **loops**, **conditionals**, **lists**, and the **random** module to draw patterns that would take hundreds of lines to write by hand.

{% hint style="info" %}
**Teacher notes**

* **Time:** 11 class periods: 6 lessons (1 class each) and 5 classes for the unit project
* **Before this unit:** students have finished [Unit 1: Drawing Basics](https://easy-draw.joemazzone.net/python-curriculum/unit-1-drawing-basics).
* **Big idea:** an *algorithm* is a step-by-step plan. If students can describe a drawing as steps that repeat, they can code it with a loop.
  {% endhint %}

## Learning Objectives

Students will be able to:

1. Use variables and arithmetic to position shapes relative to each other.
2. Use `for` loops with `range()` to repeat a drawing step.
3. Use nested loops to draw rows and grids.
4. Use `if`, `elif`, and `else` to make decisions inside a loop.
5. Use lists to store colors and points.
6. Use the `random` module to draw something different each time the program runs.

## Lesson 2.1: Variables Make Drawings Move Together

If every shape in a face uses its own numbers, moving the face means changing every number. If every shape is placed **relative** to `x` and `y`, we only change two numbers.

```python
import easy_draw

easy_draw.load_canvas()

x = 300
y = 300
size = 100

head = easy_draw.Circle(center_xy = (x, y), radius = size, color = "gold")
left_eye = easy_draw.Circle(center_xy = (x - size / 3, y - size / 4), radius = size / 8)
right_eye = easy_draw.Circle(center_xy = (x + size / 3, y - size / 4), radius = size / 8)
mouth = easy_draw.Arc(
    center_xy = (x, y + size / 4),
    width = size,
    height = size / 2,
    sweep_angle = 180,
    style = "arc",
    border_width = 5
)

easy_draw.end()
```

**Practice:** Change `x`, `y`, and `size` and run the program. Does the face stay together? Then add a nose that also uses `x`, `y`, and `size`.

## Lesson 2.2: Loops

A `for` loop repeats code. The loop variable changes each time, so we can use it to move each shape.

```python
import easy_draw

easy_draw.load_canvas()

for i in range(10):
    easy_draw.Circle(center_xy = (30 + i * 60, 300), radius = 25, color = "blue")

easy_draw.end()
```

Walk through the first few times the loop runs as a table: when `i` is 0 the x is 30, when `i` is 1 the x is 90, and so on.

The loop variable can change size and color too. Drawing big shapes first keeps the small ones on top:

```python
import easy_draw

easy_draw.load_canvas()

for i in range(10):
    shade = i * 25
    easy_draw.Circle(center_xy = (300, 300), radius = 250 - i * 25, color = (shade, 0, 255 - shade))

easy_draw.end()
```

**Practice:**

1. Draw a staircase of 8 squares.
2. Draw 12 lines that all start at (300, 300) and end at different points along the bottom of the canvas.
3. Draw a "fan" by rotating a long thin rectangle a little more each time through the loop.

## Lesson 2.3: Nested Loops and Grids

A loop inside another loop draws rows and columns.

```python
import easy_draw

easy_draw.load_canvas()

for row in range(8):
    for col in range(8):
        if (row + col) % 2 == 0:
            color = "black"
        else:
            color = "red"
        easy_draw.Rectangle(xy = (col * 75, row * 75), width = 75, height = 75, color = color)

easy_draw.end()
```

**Discussion:** What does `(row + col) % 2 == 0` check? Fill in a small table of `row`, `col`, and `(row + col) % 2` to find out.

**Practice:**

1. Change the checkerboard to 10 x 10. What else has to change?
2. Draw a grid of circles where every circle in the top half is blue and every circle in the bottom half is green.

## Lesson 2.4: Lists

A list can hold the colors for a pattern. `%` (remainder) makes the colors repeat.

```python
import easy_draw

easy_draw.load_canvas()

rainbow = ["red", "orange", "yellow", "green", "blue", "purple"]

for i in range(12):
    easy_draw.Rectangle(xy = (i * 50, 0), width = 50, height = 600, color = rainbow[i % len(rainbow)])

easy_draw.end()
```

A loop can also build a `points_list`. This draws a star by alternating between a far point and a close point around a circle.

```python
import easy_draw
import math

easy_draw.load_canvas(background = "midnightblue")

points = []
for i in range(10):
    angle = math.radians(i * 36 - 90)
    if i % 2 == 0:
        distance = 200
    else:
        distance = 80
    points.append(300 + distance * math.cos(angle))
    points.append(300 + distance * math.sin(angle))

star = easy_draw.Polygon(points_list = points, color = "gold")

easy_draw.end()
```

**Practice:** Change the star to have 8 points. Which numbers have to change?

## Lesson 2.5: Random

The `random` module makes every run different.

```python
import easy_draw
import random

easy_draw.load_canvas(background = "black")

for i in range(200):
    x = random.randint(0, 600)
    y = random.randint(0, 600)
    size = random.randint(1, 4)
    easy_draw.Circle(center_xy = (x, y), radius = size, color = "white")

moon = easy_draw.Circle(center_xy = (480, 120), radius = 60, color = "lightyellow")

easy_draw.end()
```

**Practice:**

1. Make 5% of the stars yellow. (Hint: `if random.randint(1, 100) <= 5:`)
2. Pick each star's color with `random.choice()` from a list of colors.

## Lesson 2.6: Simple Animation

A loop with `time.sleep()` changes a shape a little at a time. The browser shows each change.

```python
import easy_draw
import time

easy_draw.load_canvas()

ball = easy_draw.Circle(center_xy = (50, 300), radius = 30, color = "red")
speed = 10

for step in range(200):
    x = ball.center_xy[0] + speed
    if x > 570 or x < 30:
        speed = -speed
    ball.set_property(center_xy = (x, 300))
    time.sleep(0.02)

easy_draw.end()
```

**Discussion:** What does `speed = -speed` do? What would happen without the `if` statement?

## Unit Project: Generative Art

Students write a program that creates an original piece of art with loops and randomness. Every time the program runs, the art should look a little different, but always in the same style.

Ideas: a city skyline with random building heights, a field of flowers, a quilt pattern, a galaxy, abstract art inspired by a famous artist.

**Requirements:**

* At least one `for` loop and one nested loop.
* At least one `if` statement inside a loop.
* At least one list (of colors, points, or sizes).
* Uses `random` so that each run is different.
* At least 100 shapes drawn, using no more than 60 lines of code.
* Save three different runs with the **Save Canvas** button and turn them in with the code.

| Category       | 4 - Exceeds                                       | 3 - Meets                          | 2 - Approaching                  | 1 - Beginning   |
| -------------- | ------------------------------------------------- | ---------------------------------- | -------------------------------- | --------------- |
| Loops          | Nested loops create a complex, purposeful pattern | A loop and a nested loop are used  | Loops used, but no nested loop   | No loops        |
| Decisions      | Conditionals create several clear effects         | At least one conditional in a loop | Conditional is not inside a loop | No conditionals |
| Lists & random | Lists and random work together in creative ways   | Both a list and random are used    | Only one is used                 | Neither is used |
| Code quality   | Variables for all "magic numbers," clear comments | Clear names and comments           | Few comments                     | Hard to read    |
| Art            | Original, consistent style across runs            | Runs look different but related    | Runs look the same               | Incomplete      |


# Unit 3: Functions and Events

In this unit students write their own **functions** and use **event handlers** to make drawings that respond to the mouse and keyboard. The unit ends with students building a small game.

{% hint style="info" %}
**Teacher notes**

* **Time:** 11 class periods: 6 lessons (1 class each) and 5 classes for the unit project
* **Before this unit:** students have finished [Unit 2: Drawing Algorithms](https://easy-draw.joemazzone.net/python-curriculum/unit-2-drawing-algorithms).
* **Keyboard events** only reach the program when the Easy Draw page is the active browser tab. Remind students to click on the page before pressing keys.
  {% endhint %}

## Learning Objectives

Students will be able to:

1. Define functions with parameters to draw reusable pictures.
2. Return an object from a function and use it later.
3. Write event handler functions and bind them with `.event_setup()` and `canvas_event_setup()`.
4. Use the `event` object's `x`, `y`, and `keysym` information.
5. Use `global` variables to keep track of game information like a score.
6. Use the distance formula to check whether two shapes touch.

## Lesson 3.1: Functions That Draw

In Unit 2 students drew a face with `x`, `y`, and `size` variables. Turning that code into a function means we can draw as many faces as we want.

```python
import easy_draw

def draw_tree(x, y, size):
    trunk = easy_draw.Rectangle(
        xy = (x - size / 8, y),
        width = size / 4,
        height = size / 2,
        color = "saddlebrown"
    )
    leaves = easy_draw.Circle(center_xy = (x, y - size / 4), radius = size / 2, color = "forestgreen")

easy_draw.load_canvas(background = "lightblue")

draw_tree(100, 400, 120)
draw_tree(300, 350, 200)
draw_tree(500, 420, 80)

easy_draw.end()
```

Point out that the function must be **defined** before it is **called**, and that `x`, `y`, and `size` are **parameters** that get their values from the **arguments** in each call.

**Practice:**

1. Write `draw_house(x, y)` and draw a street of 4 houses with a loop.
2. Add a `color` parameter to `draw_tree()` so each tree can have a different color.

## Lesson 3.2: Functions That Return Objects

A function can `return` the object it made so the program can change it later.

```python
import easy_draw

def make_button(x, y, label):
    box = easy_draw.Rectangle(xy = (x - 75, y - 25), width = 150, height = 50, color = "steelblue")
    easy_draw.Text(center_xy = (x, y), text = label, color = "white", size = 20)
    return box

easy_draw.load_canvas()

start = make_button(300, 250, "Start")
quit_button = make_button(300, 350, "Quit")

start.set_property(color = "seagreen")

easy_draw.end()
```

## Lesson 3.3: Click Events

An **event** is something the user does, like clicking. An **event handler** is a function that runs when the event happens. Every event handler has an `event` parameter.

```python
import easy_draw
import random

easy_draw.load_canvas()

square = easy_draw.Rectangle(xy = (200, 200), width = 200, height = 200, color = "purple")

def click_square(event):
    square.set_property(color = random.choice(["red", "orange", "green", "blue"]))
    square.rotate(15)

square.event_setup("<Button-1>", click_square)

easy_draw.end()
```

Common mistake: `square.event_setup("<Button-1>", click_square())` with parentheses calls the function right away. We want to give Easy Draw the function's **name** so it can call it later.

**Practice:**

1. Make a circle that grows by 10 every time it is clicked.
2. Make a "light switch": clicking a rectangle changes the background between `"black"` and `"white"` with `easy_draw.set_canvas_color()`.

## Lesson 3.4: Using the Event's Information

Bind an event to the whole canvas with `canvas_event_setup()`. The `event` object tells us where the mouse was.

```python
import easy_draw
import random

easy_draw.load_canvas()

def place_dot(event):
    color = random.choice(["red", "orange", "gold", "green", "blue", "purple"])
    easy_draw.Circle(center_xy = (event.x, event.y), radius = 15, color = color)

easy_draw.canvas_event_setup("<Button-1>", place_dot)
easy_draw.canvas_event_setup("<B1-Motion>", place_dot)

easy_draw.end()
```

Now students have a paint program! `<B1-Motion>` runs while the mouse moves with the button held down.

**Practice:** Press `c` to change the brush color. (Hint: use a global `brush_color` variable and bind `"c"` with `canvas_event_setup()`.)

## Lesson 3.5: Keyboard Events and Global Variables

Arrow keys can move a player. A **global** variable keeps the score between events.

```python
import easy_draw

easy_draw.load_canvas()

player = easy_draw.Circle(center_xy = (300, 300), radius = 25, color = "blue")
score_text = easy_draw.Text(center_xy = (300, 30), text = "Moves: 0", size = 24)
moves = 0

def move(event):
    global moves
    x, y = player.center_xy
    if event.keysym == "Up" and y > 25:
        y = y - 20
    elif event.keysym == "Down" and y < 575:
        y = y + 20
    elif event.keysym == "Left" and x > 25:
        x = x - 20
    elif event.keysym == "Right" and x < 575:
        x = x + 20
    player.set_property(center_xy = (x, y))
    moves = moves + 1
    score_text.set_property(text = "Moves: " + str(moves))

easy_draw.canvas_event_setup("<Key>", move)

easy_draw.end()
```

**Discussion:**

* Why does `move()` need `global moves`, but not `global player`? (Changing a property of an object is not the same as assigning a new value to the variable.)
* What do the `y > 25` and `x < 575` checks do?

## Lesson 3.6: Collisions

Two circles touch when the distance between their centers is less than the sum of their radii.

```python
import math

def touching(circle1, circle2):
    distance = math.dist(circle1.center_xy, circle2.center_xy)
    return distance < circle1.radius + circle2.radius
```

Add a coin to the Lesson 3.5 program. After each move, check `touching(player, coin)`. If they touch, add to the score and move the coin to a random spot.

## Unit Project: Build a Game

Students design and build a small game. Ideas:

* **Click the Target** - a target jumps to a random spot each time it is clicked. Missed clicks on the canvas cost points.
* **Coin Collector** - move with the arrow keys and collect coins while avoiding enemies.
* **Whack-a-Mole** - holes are drawn with a function and a loop. Clicking a mole scores a point.
* **Dress Up / Builder** - click buttons to change the colors and parts of a character.

**Requirements:**

* At least two functions you wrote that draw something, with parameters.
* At least one function that returns an object.
* At least two different kinds of events (for example, clicks and keys).
* Uses the `event` object's information (`x`, `y`, or `keysym`).
* Keeps track of the game with at least one global variable, shown on the screen with a `Text` object.
* Has a way to win, lose, or finish.

| Category     | 4 - Exceeds                                            | 3 - Meets                                    | 2 - Approaching                    | 1 - Beginning  |
| ------------ | ------------------------------------------------------ | -------------------------------------------- | ---------------------------------- | -------------- |
| Functions    | Several well-named functions with parameters & returns | 2+ drawing functions and 1 returns an object | Functions without parameters       | No functions   |
| Events       | 3+ kinds of events that feel smooth to play            | 2 kinds of events, using event information   | 1 kind of event                    | No events work |
| Game state   | Score, levels, or timer all update correctly           | Score is tracked and displayed               | Score is tracked but not displayed | No game state  |
| Code quality | Clear structure, names, and comments                   | Comments explain each function               | Few comments                       | Hard to read   |
| Gameplay     | Fun, polished, has clear instructions                  | Playable with a clear goal                   | Partly playable                    | Not playable   |

{% hint style="success" %}
Have students play each other's games and give feedback before the final version is due.
{% endhint %}


# Setup and Install

The Java version of Easy Draw is a single file, `EasyDraw.java`, which can be found and downloaded from GitHub.

{% embed url="<https://github.com/MrMazzone/easy-draw/releases/download/v2.0.0/EasyDraw.java>" %}

## Easy Draw File

Once you have the `EasyDraw.java` file, put it in the same folder as your program (for example, next to `Main.java`).

```
my-project/
├── EasyDraw.java
└── Main.java
```

## Requirements

* **Java 17 or newer.** Check your version with `java -version`.
* **A web browser.** Easy Draw shows your drawing in your web browser.

Easy Draw only uses the Java standard library, so there is nothing else to install.

## Compiling and Running

Compile both files and run your program from the folder they are in:

```
javac *.java
java Main
```

When your program runs, Easy Draw:

1. Writes your drawing to an `index.html` file in the folder you run your program from.
2. Opens the live drawing in your web browser (<http://localhost:8765/>).

{% hint style="info" %}
Most editors (VS Code, IntelliJ, Replit, BlueJ, and others) compile every `.java` file in the folder for you, so pressing Run works as long as `EasyDraw.java` is in the same folder as your program.
{% endhint %}

See the [Starter Template](https://easy-draw.joemazzone.net/java/starter-template) to write your first program.


# Starter Template

To start drawing with Easy Draw, all you need is two method calls inside `main`. It is that easy!

```java
// Learn how to use Easy Draw!
// https://easy-draw.joemazzone.net/java/module-reference

public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();    // Always start your program with this

        // --- Your main program below here ---



        // --- Your main program ends here ---

        EasyDraw.end();           // Always end your program with this
    }
}
```

When you run the program above, Easy Draw opens your drawing in your web browser at <http://localhost:8765/>.

Easy Draw also writes your drawing to an `index.html` file in the folder you run your program from. Open `index.html` any time to see your drawing again.

{% hint style="info" %}
While your program is running, clicks, mouse movement, and key presses in the browser are sent to your event handlers. The badge in the top-right corner of the page says **Live** when the page is connected to your program and **Offline** when it is not.

Close the browser tab (or press Ctrl+C) to stop your program.
{% endhint %}

The Java version uses the same Easy Draw page as the Python version:

![The Easy Draw page in a web browser](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MRAMSGwqRIdQ2ADsTkz%2Fuploads%2F0FH3GcROqAGhldKd0USi%2Feasy-draw-browser.webp?alt=media)

#### Features of the Easy Draw page:

1. **Grid** - Turns a grid on and off, with a line every 50 pixels and numbers along the top and left side of the canvas.
2. **Coordinates** - The bottom-right corner of the page shows the x, y coordinates of your mouse as you move it around the canvas.
3. **Color Picker** - Choose a color and the page shows its hex and RGB values to use in your program.
4. **Save Canvas** - Downloads your drawing as a PNG file.

## A First Drawing

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        EasyDraw.Rectangle square = new EasyDraw.Rectangle(100, 100, 200, 200);
        square.setColor("red");
        square.eventSetup("<Button-1>", event -> square.rotate(10));

        EasyDraw.end();
    }
}
```

This draws a red square. Click it and it turns 10 degrees.


# Example Code

## Example 1: A Tree!

Here is a simple example drawing a tree with a rectangle and three triangles. The background is set to sky blue with a hex color value, and the triangles are rotated 30 degrees.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        EasyDraw.setCanvasColor("#87CEEB");

        EasyDraw.Rectangle trunk = new EasyDraw.Rectangle(250, 300, 100, 310);
        trunk.setColor(160, 82, 45);

        EasyDraw.RegPolygon top = new EasyDraw.RegPolygon(3, 300, 175, 125);
        top.setColor(0, 255, 0);
        top.rotate(30);

        EasyDraw.RegPolygon middle = new EasyDraw.RegPolygon(3, 300, 275, 175);
        middle.setColor(0, 255, 0);
        middle.rotate(30);

        EasyDraw.RegPolygon bottom = new EasyDraw.RegPolygon(3, 300, 400, 250);
        bottom.setColor(0, 255, 0);
        bottom.rotate(30);

        EasyDraw.end();
    }
}
```

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MRHN5hgZYKKGE0yrPL_%2F-MRHX6zyKRTdaLV-G_Wr%2Ftree.png?alt=media\&token=84101837-80fa-4dde-8c7c-a082ce459dd1)

## Example 2: Property Change and Event Handling

Here is an example of drawing a square and an octagon, then animating them when clicked.

When the square is clicked, it changes color to a new random value and rotates by 10 degrees.

When the octagon is clicked, it changes color to a new random value and rotates by 10 degrees.

```java
import java.util.Random;

public class Main {
    static String[] colors = {"blue", "red", "yellow", "green", "orange", "purple"};
    static Random random = new Random();

    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        EasyDraw.Rectangle square = new EasyDraw.Rectangle(100, 100, 200, 200);
        square.eventSetup("<Button-1>", event -> {
            square.setColor(colors[random.nextInt(colors.length)]);
            square.rotate(10);
        });

        EasyDraw.RegPolygon octagon = new EasyDraw.RegPolygon(8, 400, 400, 100);
        octagon.eventSetup("<Button-1>", event -> {
            octagon.setColor(colors[random.nextInt(colors.length)]);
            octagon.rotate(10);
        });

        EasyDraw.end();
    }
}
```

## Example 3: Moving with the Arrow Keys

The arrow keys move the blue circle. Clicking the circle adds 1 to the score.

```java
public class Main {
    static int score = 0;

    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        EasyDraw.Circle player = new EasyDraw.Circle(300, 300, 25);
        player.setColor("blue");

        EasyDraw.Text scoreText = new EasyDraw.Text(300, 30, "Score: 0");
        scoreText.setSize(24);
        scoreText.setBold(true);

        EasyDraw.canvasEventSetup("<Up>", event -> player.setCenter(player.getCenterX(), player.getCenterY() - 10));
        EasyDraw.canvasEventSetup("<Down>", event -> player.setCenter(player.getCenterX(), player.getCenterY() + 10));
        EasyDraw.canvasEventSetup("<Left>", event -> player.setCenter(player.getCenterX() - 10, player.getCenterY()));
        EasyDraw.canvasEventSetup("<Right>", event -> player.setCenter(player.getCenterX() + 10, player.getCenterY()));

        player.eventSetup("<Button-1>", event -> {
            score = score + 1;
            scoreText.setText("Score: " + score);
        });

        EasyDraw.end();
    }
}
```

{% hint style="info" %}
`score` is a `static` variable of the class, not a local variable in `main`. A lambda can only change variables like this one. See [Event Handling](https://easy-draw.joemazzone.net/java/module-reference/event-handling).
{% endhint %}


# Module Reference

Everything you can do with the Java version of Easy Draw (`EasyDraw.java`).

Everything in Easy Draw is inside the `EasyDraw` class:

* Methods are called on the class, like `EasyDraw.loadCanvas()`.
* Shapes are made with `new EasyDraw.ShapeName(...)` and the required values in order, like `new EasyDraw.Circle(centerX, centerY, radius)`.
* Optional properties use setters and getters, like `setColor("red")` and `getRadius()`.

{% content-ref url="/pages/8rZQe9iiCJEpgOffKhLV" %}
[The Drawing Canvas](https://easy-draw.joemazzone.net/java/module-reference/the-drawing-canvas)
{% endcontent-ref %}

{% content-ref url="/pages/Vyl4JrYd6YdvcrGGgd5d" %}
[Drawing Shapes](https://easy-draw.joemazzone.net/java/module-reference/drawing-shapes)
{% endcontent-ref %}

{% content-ref url="/pages/3KopHUyNWBa8REKEgY43" %}
[Text and Images](https://easy-draw.joemazzone.net/java/module-reference/text-and-images)
{% endcontent-ref %}

{% content-ref url="/pages/VGe4gM6J5K2lhlbXFtbY" %}
[Object Methods](https://easy-draw.joemazzone.net/java/module-reference/object-methods)
{% endcontent-ref %}

{% content-ref url="/pages/iraFdBKELwRsEfo3xrvb" %}
[Event Handling](https://easy-draw.joemazzone.net/java/module-reference/event-handling)
{% endcontent-ref %}

{% content-ref url="/pages/mr8UnfKjRhvp2STZzmd1" %}
[Saving Your Drawing](https://easy-draw.joemazzone.net/java/module-reference/saving-your-drawing)
{% endcontent-ref %}

## Coming from the Python version?

The Java version can do everything the Python version can. Here is how they differ:

| Python                                                         | Java                                                    |
| -------------------------------------------------------------- | ------------------------------------------------------- |
| `easy_draw.load_canvas()`                                      | `EasyDraw.loadCanvas()`                                 |
| `easy_draw.Circle(center_xy = (300, 300), radius = 50)`        | `new EasyDraw.Circle(300, 300, 50)`                     |
| `color = "red"` or `color = (255, 0, 0)`                       | `setColor("red")` or `setColor(255, 0, 0)`              |
| `circle.radius`                                                | `circle.getRadius()`                                    |
| `circle.set_property(radius = 80)`                             | `circle.setRadius(80)`                                  |
| `circle.set_property(center_xy = (100, 200))`                  | `circle.setCenter(100, 200)`                            |
| `points_list = [100, 100, 200, 200]`                           | `new EasyDraw.Line(100, 100, 200, 200)`                 |
| `dashes = None` / `border_color = None`                        | `setDashes(0)` / `setBorderColor(null)`                 |
| `def handler(event):` and `event_setup("<Button-1>", handler)` | `eventSetup("<Button-1>", event -> { ... })`            |
| `event.char`                                                   | `event.character`                                       |
| `EasyDrawError`                                                | `EasyDraw.EasyDrawException`                            |
| Files are found next to your program                           | Files are found in the folder you run your program from |

The canvas, [colors](https://easy-draw.joemazzone.net/python/module-reference/colors), and event names are the same in both versions.


# The Drawing Canvas

All shapes will be drawn on a canvas.

The Easy Draw canvas is 600 x 600 pixels (600 pixels wide by 600 pixels tall). So (300, 300) is the middle of the canvas, and (600, 600) is the bottom-right corner.

The coordinate system origin (0, 0) is the top-left corner of the canvas.

As x increases, objects move right. As y increases, objects move down (not up!).

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MRSz1hx0nb7qnoNWat3%2F-MRT-Gv1H7yZTFGl5LLU%2Fimage.png?alt=media\&token=a4585fe9-c159-4731-8a5e-7929c28c2f13)

{% hint style="info" %}
Turn on the **Grid** button in the Easy Draw page to see the coordinates on the canvas.
{% endhint %}

## Loading the Canvas

`EasyDraw.loadCanvas()`

Every Easy Draw program must start with this method call. It writes your drawing to an `index.html` file in the folder you run your program from and opens the live drawing in your web browser.

You can give it a background color:

```java
EasyDraw.loadCanvas("black");
```

You can also pick the port for the live drawing (default `8765`) and set `openBrowser` to `false` if you want to open the page yourself:

```java
EasyDraw.loadCanvas("white", 8000, false);
```

## Changing the Background Color

`EasyDraw.setCanvasColor(color)`

Used to change the canvas background color at any point in the program.

```java
EasyDraw.setCanvasColor("blue");
EasyDraw.setCanvasColor(0, 0, 255);
```

## Ending the Program

`EasyDraw.end()`

Every Easy Draw program must end with this method call. It keeps your program running so the browser can send events (like clicks and key presses) to your program.

Closing the Easy Draw browser tab (or pressing Ctrl+C) stops your program.

```java
EasyDraw.end();
```

To print the finished page's HTML code, pass `true`:

```java
EasyDraw.end(true);
```

## Colors

There are 3 ways you can use colors in Easy Draw:

```java
shape.setColor("red");          // 1. Name of the color
shape.setColor(255, 0, 0);      // 2. RGB value
shape.setColor("#FF0000");      // 3. Hex value
```

To turn an RGB value into a hex value, use `EasyDraw.rgbConvert()`:

```java
String red = EasyDraw.rgbConvert(255, 0, 0);    // "#ff0000"
```

Colors work the same as in the Python version. See the Colors page for more about each kind of color value:

{% content-ref url="/pages/-MRAv4THLzk2KzBvDpW7" %}
[Colors](https://easy-draw.joemazzone.net/python/module-reference/colors)
{% endcontent-ref %}

## Errors

When Easy Draw is not used properly, it throws an `EasyDraw.EasyDrawException` with a message that explains what went wrong.


# Drawing Shapes

When drawing shapes, the sequence matters. That is how the layering system works.

The first object that is drawn in your code will be at the bottom most layer of your drawing. The last object that is drawn in your code will be the top most layer of your drawing.

Shapes are made with `new EasyDraw.ShapeName(...)` and the required values in order. Optional properties are changed with setters after the shape is made.

These setters work on every shape except `Line`, `Text`, and `Image`:

| Setter                                              | Default | Description                                                            |
| --------------------------------------------------- | ------- | ---------------------------------------------------------------------- |
| `setColor(color)` / `setColor(r, g, b)`             | "black" | The color of the shape.                                                |
| `setBorderColor(color)` / `setBorderColor(r, g, b)` | null    | Color of the border. Use `null` for no border.                         |
| `setBorderWidth(width)`                             | 0       | Size of the border in pixels.                                          |
| `setDashes(size)`                                   | 0       | Size of the dashes for the border in pixels. Use 0 for a solid border. |
| `setVisible(visible)`                               | true    | true = Shape can be seen. false = Shape cannot be seen.                |

## Rectangle

`new EasyDraw.Rectangle(x, y, width, height)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MR_X4Wtqc7FkpTp_iKw%2F-MR_brBio-EXXyHCGBw8%2Fimage.png?alt=media\&token=a11a1446-bff5-41de-bb68-69687d7b414d)

| Value    | Description                                                |
| -------- | ---------------------------------------------------------- |
| `x`, `y` | The x and y coordinate of the rectangle's top-left corner. |
| `width`  | The width of the rectangle in pixels.                      |
| `height` | The height of the rectangle in pixels.                     |

Getters and setters: `getX()`, `getY()`, `setXY(x, y)`, `setX(x)`, `setY(y)`, `getWidth()`, `setWidth(width)`, `getHeight()`, `setHeight(height)`

Example:

```java
EasyDraw.Rectangle rect1 = new EasyDraw.Rectangle(300, 300, 200, 150);
rect1.setColor(255, 0, 0);       // Optional
rect1.setBorderColor(0, 0, 0);   // Optional
rect1.setBorderWidth(10);        // Optional
rect1.setDashes(25);             // Optional
```

{% hint style="info" %}
A Rectangle can rotate around its center or its top-left corner: `rect1.rotate(45, true)`
{% endhint %}

## Regular Polygon

`new EasyDraw.RegPolygon(nsides, centerX, centerY, radius)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MR_X4Wtqc7FkpTp_iKw%2F-MR_cru4Phqg61haLd1f%2Fimage.png?alt=media\&token=328f7cf3-9628-43e9-ad94-853cd45011f1)

| Value                | Description                                                |
| -------------------- | ---------------------------------------------------------- |
| `nsides`             | The number of sides the polygon has (3 or more).           |
| `centerX`, `centerY` | The x and y coordinate of the polygon's center.            |
| `radius`             | The distance in pixels from the center to any outer point. |

Getters and setters: `getNsides()`, `setNsides(nsides)`, `getCenterX()`, `getCenterY()`, `setCenter(x, y)`, `getRadius()`, `setRadius(radius)`

Example:

```java
EasyDraw.RegPolygon octagon = new EasyDraw.RegPolygon(8, 300, 300, 100);
octagon.setColor(255, 0, 0);     // Optional
```

## Polygon

`new EasyDraw.Polygon(x1, y1, x2, y2, x3, y3, ...)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MR_cunQqfAZ7Fzz-G2D%2F-MR_fjwaZO4mP9XlS2rC%2Fimage.png?alt=media\&token=5780ee7e-667c-4a32-b299-a95d92b83d35)

Give the x and y coordinates of each point, in order. The Polygon can have as many sides as you want. There MUST be an even number of values.

Getters and setters: `getPoints()`, `setPoints(x1, y1, x2, y2, ...)`

Example:

```java
EasyDraw.Polygon poly1 = new EasyDraw.Polygon(25, 25, 150, 25, 200, 200, 100, 250, 25, 200);
poly1.setColor(255, 0, 0);       // Optional
poly1.setBorderColor(0, 0, 0);   // Optional
poly1.setBorderWidth(10);        // Optional
```

You can also give the points as a `double[]` array:

```java
double[] points = {25, 25, 150, 25, 200, 200};
EasyDraw.Polygon triangle = new EasyDraw.Polygon(points);
```

## Line

`new EasyDraw.Line(x1, y1, x2, y2)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MU-P9t60n8INhnBrz6e%2F-MU-ZaAMGoIFqzFnz8El%2Fimage.png?alt=media\&token=433a7851-d0ce-4911-8bdf-3488daa6d6fe)

Give more x y coordinates to draw a line through many points:

`new EasyDraw.Line(x1, y1, x2, y2, x3, y3, ...)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MU-P9t60n8INhnBrz6e%2F-MU-ZJGBV1J0VGjttyKV%2Fimage.png?alt=media\&token=2cf2488d-c786-45e1-87a8-0153e6d938ce)

| Setter                                  | Default | Description                                                                 |
| --------------------------------------- | ------- | --------------------------------------------------------------------------- |
| `setColor(color)` / `setColor(r, g, b)` | "black" | The color of the line.                                                      |
| `setThickness(thickness)`               | 5       | The width of the line in pixels.                                            |
| `setDashes(size)`                       | 0       | Size of the dashes in pixels. Use 0 for a solid line.                       |
| `setArrowStart(true)`                   | false   | Add an arrow to the start of the line.                                      |
| `setArrowEnd(true)`                     | false   | Add an arrow to the end of the line.                                        |
| `setStyle(style)`                       | "round" | `"round"` for round edges and joints and `"cut"` for squared/cut-off edges. |
| `setVisible(visible)`                   | true    | true = Line can be seen. false = Line cannot be seen.                       |

Other getters and setters: `getPoints()`, `setPoints(...)`, `setXY1(x, y)` (moves the start), `setXY2(x, y)` (moves the end)

Example:

```java
EasyDraw.Line line1 = new EasyDraw.Line(100, 100, 200, 200);
line1.setThickness(8);           // Optional
line1.setColor(255, 0, 0);       // Optional
line1.setDashes(25);             // Optional

EasyDraw.Line zigzag = new EasyDraw.Line(50, 500, 100, 450, 150, 500, 200, 450);
zigzag.setStyle("cut");          // Optional
zigzag.setArrowEnd(true);        // Optional
```

## Circle

`new EasyDraw.Circle(centerX, centerY, radius)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MR_gAyOFo4wA1T_3cRr%2F-MR_i0W_lHdud28t__p9%2Fimage.png?alt=media\&token=cd71f25b-7435-40c9-9c31-9ba540ba0a52)

| Value                | Description                                                          |
| -------------------- | -------------------------------------------------------------------- |
| `centerX`, `centerY` | The center coordinate of the circle.                                 |
| `radius`             | The measurement in pixels from the center of the circle to the edge. |

Getters and setters: `getCenterX()`, `getCenterY()`, `setCenter(x, y)`, `getRadius()`, `setRadius(radius)`

Example:

```java
EasyDraw.Circle cir1 = new EasyDraw.Circle(300, 300, 100);
cir1.setColor(255, 0, 0);        // Optional
cir1.setBorderColor(0, 0, 0);    // Optional
cir1.setBorderWidth(10);         // Optional
```

## Oval

`new EasyDraw.Oval(centerX, centerY, width, height)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MR_gAyOFo4wA1T_3cRr%2F-MR_ioK19DUZDAWjeepO%2Fimage.png?alt=media\&token=810c11cf-a128-4495-b61c-2224fdaaa984)

| Value                | Description                                                   |
| -------------------- | ------------------------------------------------------------- |
| `centerX`, `centerY` | The center coordinate of the oval.                            |
| `width`              | The measurement in pixels of the left edge to the right edge. |
| `height`             | The measurement in pixels of the top edge to the bottom edge. |

Getters and setters: `getCenterX()`, `getCenterY()`, `setCenter(x, y)`, `getWidth()`, `setWidth(width)`, `getHeight()`, `setHeight(height)`

Example:

```java
EasyDraw.Oval oval1 = new EasyDraw.Oval(300, 300, 100, 200);
oval1.setColor(255, 0, 0);       // Optional
```

## Arc

`new EasyDraw.Arc(centerX, centerY, width, height, sweepAngle)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MR_j3WiqNf06YQqsd1G%2F-MR_nS8Sjg0QA5oZFX7U%2Fimage.png?alt=media\&token=3d9458ea-cdd3-4dd7-b3e8-288e347ff887)

There are 3 different styles, set with `setStyle()`: `"pieslice"` (the default), `"chord"`, and `"arc"`.

![](https://tkdocs.com/shipman/img/chord.png)

*Note: The "arc" style is only an outline. It uses the border color (or the color if there is no border color) and the border width (at least 1 pixel).*

| Value                | Description                                                               |
| -------------------- | ------------------------------------------------------------------------- |
| `centerX`, `centerY` | The center coordinate of the circle used to create the arc.               |
| `width`              | The width of the circle used to create the arc.                           |
| `height`             | The height of the circle used to create the arc.                          |
| `sweepAngle`         | The amount of the arc to show. From 0 to the angle in degrees identified. |

Getters and setters: `getCenterX()`, `getCenterY()`, `setCenter(x, y)`, `getWidth()`, `setWidth(width)`, `getHeight()`, `setHeight(height)`, `getSweepAngle()`, `setSweepAngle(angle)`, `getStyle()`, `setStyle(style)`

Example:

```java
EasyDraw.Arc arc1 = new EasyDraw.Arc(300, 300, 100, 100, 90);
arc1.setStyle("chord");          // Optional
arc1.setColor(255, 0, 0);        // Optional
```


# Text and Images

## Text

`new EasyDraw.Text(centerX, centerY, text)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MR_npajpEZf8wpIj8HL%2F-MRaFmdYU9IGnMtLINHu%2Fimage.png?alt=media\&token=d19c999e-dfc5-4ad0-920b-73d86b65957a)

| Setter                                  | Default | Description                                                                                    |
| --------------------------------------- | ------- | ---------------------------------------------------------------------------------------------- |
| `setText(text)`                         | -       | The text you want to display.                                                                  |
| `setColor(color)` / `setColor(r, g, b)` | "black" | The color of the text.                                                                         |
| `setFont(font)`                         | "Arial" | The font family used for the text. Font must be installed on the computer viewing the drawing. |
| `setSize(size)`                         | 16      | The font size of the text.                                                                     |
| `setBold(true)`                         | false   | Bolds the text.                                                                                |
| `setItalic(true)`                       | false   | Italicizes the text.                                                                           |
| `setUnderline(true)`                    | false   | Underlines the text.                                                                           |
| `setStrikethrough(true)`                | false   | Strikes-out the text.                                                                          |
| `setVisible(visible)`                   | true    | true = Text can be seen. false = Text cannot be seen.                                          |

Getters: `getText()`, `getColor()`, `getFont()`, `getSize()`, `isBold()`, `isItalic()`, `isUnderline()`, `isStrikethrough()`, `getCenterX()`, `getCenterY()`. Move it with `setCenter(x, y)`.

Example:

```java
EasyDraw.Text words = new EasyDraw.Text(300, 100, "I Love Java");
words.setColor(0, 200, 50);      // Optional
words.setFont("Times");          // Optional
words.setSize(32);               // Optional
words.setBold(true);             // Optional
words.setItalic(true);           // Optional
```

## Images

First open the image with `EasyDraw.openImage()`. The image file should be in the folder you run your program from.

```java
EasyDraw.ImageFile pic = EasyDraw.openImage("super_cool_image.png");
```

Easy Draw can open `.png`, `.gif`, `.jpg`, `.webp`, `.bmp`, and `.svg` images.

`openImage()` also works with a public image link that starts with `http://` or `https://`:

```java
EasyDraw.ImageFile pic = EasyDraw.openImage("https://example.com/cat.png");
```

{% hint style="info" %}
Make sure you copy the image's address (right-click the image and choose "Copy image address"), not the web page's address. The browser loads the image straight from the link, so viewing the drawing needs an internet connection.
{% endhint %}

Then you can create an image object.

`new EasyDraw.Image(centerX, centerY, image)`

![](https://651142499-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MRAMSGwqRIdQ2ADsTkz%2F-MR_npajpEZf8wpIj8HL%2F-MRaGEPex2n6zJasiFXn%2Fimage.png?alt=media\&token=4ad09f11-5064-4217-b1ea-0e630e426741)

| Value                | Description                                                                   |
| -------------------- | ----------------------------------------------------------------------------- |
| `centerX`, `centerY` | The center coordinate of where to draw the image.                             |
| `image`              | An `ImageFile` from `EasyDraw.openImage()`, or the image's file name or link. |

Getters and setters: `getCenterX()`, `getCenterY()`, `setCenter(x, y)`, `getImage()`, `setImage(image)`, `setVisible(visible)`

Example:

```java
EasyDraw.ImageFile pic = EasyDraw.openImage("super_cool_image.png");
EasyDraw.Image img = new EasyDraw.Image(300, 300, pic);

// OR, in one step:
EasyDraw.Image img2 = new EasyDraw.Image(300, 300, "super_cool_image.png");
```

Images can rotate, just like every other Easy Draw object:

```java
img.rotate(45);
```


# Object Methods

Every Easy Draw drawing object is a child class of `EasyDraw.Shape`, so they all share these methods.

## `rotate(angle)`

Rotates an Easy Draw object by a specified amount of degrees around its center.

Positive numbers rotate the shape clockwise (to the right). Negative numbers rotate the shape counter-clockwise (to the left).

```java
rect1.rotate(45);
```

A `Rectangle` can also rotate around its top-left corner instead of its center:

```java
rect1.rotate(45, true);
```

`getAngle()` tells you how far an object has been rotated in total, and `setAngle(angle)` sets it.

## `erase()`

Deletes the object from the canvas.

```java
rect1.erase();
```

## `setVisible(visible)` and `isVisible()`

Hides or shows the object without erasing it.

```java
rect1.setVisible(false);
```

## `toString()`

Returns the string representation of the object. The string will include the object type and ID number used by Easy Draw.

```java
System.out.println(rect1);
```

`getType()` returns just the type, like `"Rectangle"`, and `getId()` returns just the ID number.

## `eventSetup(event, handler)`

Binds an event to the object. See [Event Handling](https://easy-draw.joemazzone.net/java/module-reference/event-handling).

## Getters and Setters

Every property of an object has a getter and a setter. Getters return the property's value. Setters change the property and update the drawing right away.

```java
EasyDraw.Circle cir = new EasyDraw.Circle(300, 300, 20);

cir.setRadius(cir.getRadius() + 10);     // Grow the circle by 10
cir.setCenter(cir.getCenterX() + 5, cir.getCenterY());    // Move it right 5
```

`true` / `false` properties use `is` instead of `get`, like `isVisible()` and `isBold()`. See [Drawing Shapes](https://easy-draw.joemazzone.net/java/module-reference/drawing-shapes) and [Text and Images](https://easy-draw.joemazzone.net/java/module-reference/text-and-images) for the getters and setters of each shape.


# Event Handling

## Events List

The Java version uses the same event names as the Python version, like `"<Button-1>"`, `"<B1-Motion>"`, `"<Key>"`, and `"<Up>"`. See the full list here:

{% content-ref url="/pages/-MRAvSb83fmXckFG2fA6" %}
[Event Handling](https://easy-draw.joemazzone.net/python/module-reference/event-handling)
{% endcontent-ref %}

{% hint style="info" %}
Key presses only reach Easy Draw when the Easy Draw page is the active browser tab. Click on the page first if your key events are not working.
{% endhint %}

## Event Handlers

An event handler is the code that runs when the event happens. Write it as a lambda: `event -> { ... }`

```java
square.eventSetup("<Button-1>", event -> {
    square.setColor("blue");
    square.rotate(10);
});
```

If the handler is only one statement, you can leave out the curly braces:

```java
square.eventSetup("<Button-1>", event -> square.rotate(10));
```

You can also write the handler as a `static` method that takes an `EasyDraw.Event`, and pass it with `ClassName::methodName`:

```java
public class Main {
    static EasyDraw.Rectangle square;

    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        square = new EasyDraw.Rectangle(100, 100, 200, 200);
        square.eventSetup("<Button-1>", Main::clickSquare);

        EasyDraw.end();
    }

    static void clickSquare(EasyDraw.Event event) {
        square.rotate(10);
    }
}
```

Event handlers run one at a time, in the order the events happen.

### Changing Variables in a Handler

A lambda cannot change a local variable from `main`. Use a `static` variable of your class instead:

```java
public class Main {
    static int clicks = 0;

    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        EasyDraw.Text counter = new EasyDraw.Text(300, 300, "Clicks: 0");
        EasyDraw.canvasEventSetup("<Button-1>", event -> {
            clicks = clicks + 1;
            counter.setText("Clicks: " + clicks);
        });

        EasyDraw.end();
    }
}
```

## Event Information

The `event` passed to your handler has useful information about the event:

| Field                        | Description                                                              |
| ---------------------------- | ------------------------------------------------------------------------ |
| `event.x`, `event.y`         | The mouse position on the canvas, in pixels.                             |
| `event.xRoot`, `event.yRoot` | The mouse position on the screen, in pixels.                             |
| `event.character`            | The character typed, as a `String` (keyboard events only).               |
| `event.keysym`               | The key symbol, like `"a"`, `"Up"`, or `"space"` (keyboard events only). |
| `event.keycode`              | The key code (keyboard events only).                                     |
| `event.num`                  | The mouse button number (mouse button events only).                      |
| `event.delta`                | How far the mouse wheel moved (mouse wheel events only).                 |
| `event.type`                 | The event type, like `"ButtonPress"` or `"KeyPress"`.                    |

```java
EasyDraw.canvasEventSetup("<Button-1>", event -> {
    System.out.println("You clicked at " + event.x + ", " + event.y);
});
```

## Binding an Event to an Easy Draw Object

`object.eventSetup(event, handler)`

```java
octagon.eventSetup("<Button-1>", event -> octagon.rotate(10));
```

## Binding an Event to the Canvas

`EasyDraw.canvasEventSetup(event, handler)`

*It is recommended to bind keyboard events to the entire canvas instead of binding key events to a specific object.*

```java
EasyDraw.canvasEventSetup("<Up>", event -> player.setCenter(player.getCenterX(), player.getCenterY() - 10));
```

## Animations

You can animate a drawing with a loop and `Thread.sleep()`. The browser shows each change while the loop runs.

```java
public class Main {
    public static void main(String[] args) throws InterruptedException {
        EasyDraw.loadCanvas();

        EasyDraw.Circle ball = new EasyDraw.Circle(50, 300, 25);
        ball.setColor("red");

        for (int i = 0; i < 50; i++) {
            ball.setCenter(ball.getCenterX() + 10, 300);
            Thread.sleep(50);
        }

        EasyDraw.end();
    }
}
```


# Saving Your Drawing

## Your Drawing is Already Saved

Every time your program runs, Easy Draw writes your drawing to an `index.html` file in the folder you run your program from. Open `index.html` in a web browser any time to see your drawing again.

## Using the Button

You can save your drawing as a PNG file by clicking the **Save Canvas** button in the Easy Draw page. Just be sure to provide the image with a file name. Your web browser downloads the picture, so it will be in your Downloads folder.

## `EasyDraw.saveCanvas()`

To save the canvas from your code, use `EasyDraw.saveCanvas()`. The picture saves as a .png file in the folder you run your program from.

```java
EasyDraw.saveCanvas("my_pic");
```

Without a file name, it asks for the file's name in the terminal:

```java
EasyDraw.saveCanvas();
```

{% hint style="info" %}
The picture is created by your web browser, so your drawing must be open in a browser tab. If it is not open yet, Easy Draw waits and saves the picture once the page opens.
{% endhint %}


# Unit 1: Using Easy Draw Objects

In this unit students learn to **create objects** and **call methods** by drawing with Easy Draw. Every shape is an object, which makes classes, constructors, references, and methods visible on the screen.

{% hint style="info" %}
**Teacher notes**

* **Time:** 11 class periods: 6 lessons (1 class each) and 5 classes for the unit project
* **AP Computer Science A:** Primitive Types and Using Objects (creating objects, calling void and non-void methods, the `Math` class).
* **Setup:** each student needs `EasyDraw.java` in the same folder as their program. See [Java Setup and Install](https://easy-draw.joemazzone.net/java/setup-and-install).
  {% endhint %}

## Learning Objectives

Students will be able to:

1. Explain the difference between a class and an object.
2. Create objects with `new` and a constructor, passing arguments in the right order.
3. Store a reference to an object in a variable of the class's type.
4. Call `void` methods (setters) and non-void methods (getters) on an object and use the returned value.
5. Use `int` and `double` variables and arithmetic expressions to place shapes.
6. Use `Math.random()` and `Math.sqrt()` in a drawing.

## Lesson 1.1: Classes and Objects

A **class** is a blueprint. An **object** is one thing built from that blueprint. `EasyDraw.Circle` is a class. Each circle on the canvas is an object.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        EasyDraw.Circle sun = new EasyDraw.Circle(300, 300, 100);
        EasyDraw.Circle moon = new EasyDraw.Circle(500, 100, 40);

        EasyDraw.end();
    }
}
```

Break the line `EasyDraw.Circle sun = new EasyDraw.Circle(300, 300, 100);` into parts:

* `EasyDraw.Circle` - the type of the variable (the class).
* `sun` - the variable that stores a **reference** to the object.
* `new` - creates a new object.
* `EasyDraw.Circle(300, 300, 100)` - calls the **constructor** with arguments: center x, center y, and radius.

**Discussion:** We made two objects from one class. What is the same about them? What is different?

## Lesson 1.2: The Coordinate Plane and Constructors

The canvas is 600 x 600 pixels. (0, 0) is the **top-left** corner and y grows **down**. Turn on the **Grid** button on the Easy Draw page and hover over the canvas to see coordinates.

Each constructor expects its arguments in a certain **order**:

| Constructor                                                 | Arguments in order              |
| ----------------------------------------------------------- | ------------------------------- |
| `new EasyDraw.Rectangle(x, y, width, height)`               | top-left corner, then size      |
| `new EasyDraw.Circle(centerX, centerY, radius)`             | center, then radius             |
| `new EasyDraw.Oval(centerX, centerY, width, height)`        | center, then size               |
| `new EasyDraw.RegPolygon(nsides, centerX, centerY, radius)` | number of sides, center, radius |
| `new EasyDraw.Polygon(x1, y1, x2, y2, x3, y3, ...)`         | each point                      |
| `new EasyDraw.Line(x1, y1, x2, y2)`                         | start point, end point          |
| `new EasyDraw.Text(centerX, centerY, text)`                 | center, then the text           |

**Practice:** Swap the order of two arguments in a constructor call. What happens? What happens if you leave one out? (The compiler error is the lesson!)

## Lesson 1.3: Calling Methods

**Methods** are what an object can do. Setters are `void` methods: they change the object and do not return anything.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        EasyDraw.Rectangle box = new EasyDraw.Rectangle(200, 200, 200, 100);
        box.setColor("orange");
        box.setBorderColor("black");
        box.setBorderWidth(5);
        box.rotate(30);

        EasyDraw.end();
    }
}
```

Getters are **non-void** methods: they **return** a value we can store or use.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        EasyDraw.Circle ball = new EasyDraw.Circle(300, 300, 50);

        double r = ball.getRadius();
        System.out.println("The radius is " + r);

        ball.setRadius(ball.getRadius() * 2);
        System.out.println("Now the radius is " + ball.getRadius());
        System.out.println(ball);

        EasyDraw.end();
    }
}
```

**Discussion:** `ball.setRadius(ball.getRadius() * 2);` uses a non-void method call as the argument of a void method call. Which method runs first?

**Practice:** Draw a square, then use its getters to place a circle exactly on its top-right corner.

## Lesson 1.4: Variables and Expressions

Variables and arithmetic let shapes be placed **relative** to each other. Change `x`, `y`, or `size` and the whole snowman moves and resizes together.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas("skyblue");

        double x = 300;
        double y = 450;
        double size = 80;

        EasyDraw.Circle bottom = new EasyDraw.Circle(x, y, size);
        EasyDraw.Circle middle = new EasyDraw.Circle(x, y - size * 1.6, size * 0.75);
        EasyDraw.Circle head = new EasyDraw.Circle(x, y - size * 2.8, size * 0.5);

        bottom.setColor("white");
        middle.setColor("white");
        head.setColor("white");

        EasyDraw.end();
    }
}
```

**Discussion:** What happens with `int size = 80;` and `size / 3`? Compare it with `double size = 80;`. (Integer division!)

## Lesson 1.5: Colors and Strings

Colors can be a `String` (a name or a hex value) or three `int` values for red, green, and blue.

```java
shape.setColor("tomato");
shape.setColor("#FF6347");
shape.setColor(255, 99, 71);
```

Use the **Color Picker** button on the Easy Draw page to find RGB and hex values.

Text objects hold a `String`, and `+` builds new strings:

```java
String name = "Ada";
int age = 15;
EasyDraw.Text label = new EasyDraw.Text(300, 50, name + " is " + age + " years old");
label.setSize(28);
```

## Lesson 1.6: The Math Class

`Math.random()` returns a `double` from 0.0 up to (not including) 1.0. Multiply and cast it to get a random whole number.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas("black");

        int x = (int) (Math.random() * 600);
        int y = (int) (Math.random() * 600);
        int red = (int) (Math.random() * 256);

        EasyDraw.Circle star = new EasyDraw.Circle(x, y, 20);
        star.setColor(red, 255, 0);

        double distance = Math.sqrt(Math.pow(x - 300, 2) + Math.pow(y - 300, 2));
        EasyDraw.Text info = new EasyDraw.Text(300, 580, "Distance from center: " + (int) distance);
        info.setColor("white");

        EasyDraw.end();
    }
}
```

**Practice:** Run the program several times. Then draw a line from the center of the canvas to the star.

## Unit Project: Object Portrait

Students draw a portrait (of themselves, a character, an animal, or a robot) built only from Easy Draw objects.

**Requirements:**

* At least 12 objects using at least 5 different classes (`Rectangle`, `Circle`, `Oval`, `RegPolygon`, `Polygon`, `Line`, `Arc`, `Text`).
* Every shape is placed using `x`, `y`, and `size` variables, so changing those three values moves and resizes the whole portrait.
* At least 3 different setters and at least 2 getters are used.
* At least one color is RGB and one is hex.
* Uses `Math.random()` for at least one detail (like a random shirt color).
* A `Text` object shows a title built with string concatenation.

| Category          | 4 - Exceeds                                      | 3 - Meets                       | 2 - Approaching               | 1 - Beginning     |
| ----------------- | ------------------------------------------------ | ------------------------------- | ----------------------------- | ----------------- |
| Objects           | 15+ objects, 6+ classes                          | 12+ objects, 5+ classes         | Fewer objects or classes      | Very few objects  |
| Methods           | Setters and getters used together in expressions | 3+ setters and 2+ getters       | Only setters                  | No methods called |
| Relative position | Whole portrait scales correctly with `size`      | Portrait moves with `x` and `y` | Some shapes use fixed numbers | All fixed numbers |
| Code quality      | Clear names, comments, and organization          | Comments explain each part      | Few comments                  | Hard to read      |
| Design            | Original, detailed, and polished                 | Complete and recognizable       | Unfinished                    | Hard to recognize |


# Unit 2: If Statements and Drawings

In this unit students make drawings that **make decisions**. Boolean expressions and `if` statements decide what to draw, and event handlers make the decisions happen when the user clicks or presses a key.

{% hint style="info" %}
**Teacher notes**

* **Time:** 10 class periods: 5 lessons (1 class each) and 5 classes for the unit project
* **AP Computer Science A:** Boolean Expressions and if Statements (relational and logical operators, `if`/`else if`/`else`, comparing objects and `String`s with `.equals()`).
* **Before this unit:** students have finished [Unit 1: Using Easy Draw Objects](https://easy-draw.joemazzone.net/java-curriculum/unit-1-using-easy-draw-objects).
* Event handlers are written as lambdas. Students only need the pattern `event -> { ... }`; the full idea of lambdas is not needed yet.
  {% endhint %}

## Learning Objectives

Students will be able to:

1. Write boolean expressions with relational operators (`<`, `>`, `<=`, `>=`, `==`, `!=`) and logical operators (`&&`, `||`, `!`).
2. Use `if`, `if`/`else`, and `if`/`else if`/`else` to decide what to draw.
3. Compare `String` values with `.equals()` instead of `==`.
4. Write event handlers that use conditionals to respond to clicks and key presses.
5. Use `static` variables to remember information between events.

## Lesson 2.1: Drawing with Decisions

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        int hour = (int) (Math.random() * 24);

        if (hour >= 6 && hour < 18) {
            EasyDraw.setCanvasColor("skyblue");
            EasyDraw.Circle sun = new EasyDraw.Circle(500, 100, 60);
            sun.setColor("yellow");
        } else {
            EasyDraw.setCanvasColor("midnightblue");
            EasyDraw.Circle moon = new EasyDraw.Circle(500, 100, 50);
            moon.setColor("lightyellow");
        }

        EasyDraw.Text clock = new EasyDraw.Text(300, 550, "Hour: " + hour);
        clock.setSize(32);

        EasyDraw.end();
    }
}
```

**Practice:**

1. Add an `else if` so the sky is `"orange"` at sunset (hours 18 and 19).
2. Draw stars only at night.

## Lesson 2.2: Click Events

An **event handler** is code that runs when something happens, like a click. The code goes inside `event -> { ... }`.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        EasyDraw.Circle light = new EasyDraw.Circle(300, 300, 100);
        light.setColor("gray");

        light.eventSetup("<Button-1>", event -> {
            if (light.getColor().equals("gray")) {
                light.setColor("yellow");
            } else {
                light.setColor("gray");
            }
        });

        EasyDraw.end();
    }
}
```

**Discussion:** Why do we use `light.getColor().equals("gray")` and not `light.getColor() == "gray"`? (`==` checks whether two references point to the same object. `.equals()` checks whether two strings have the same characters.)

## Lesson 2.3: Remembering with Static Variables

A lambda cannot change a local variable from `main`. A `static` variable of the class can be changed, so it can remember information between clicks.

```java
public class Main {
    static int state = 0;

    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        EasyDraw.Rectangle box = new EasyDraw.Rectangle(250, 100, 100, 300);
        box.setColor("black");
        EasyDraw.Circle light = new EasyDraw.Circle(300, 250, 40);
        light.setColor("red");

        box.eventSetup("<Button-1>", event -> {
            state = state + 1;
            if (state > 2) {
                state = 0;
            }

            if (state == 0) {
                light.setColor("red");
                light.setCenter(300, 150);
            } else if (state == 1) {
                light.setColor("green");
                light.setCenter(300, 350);
            } else {
                light.setColor("yellow");
                light.setCenter(300, 250);
            }
        });

        EasyDraw.end();
    }
}
```

**Practice:** Add a `Text` object that shows `"STOP"`, `"GO"`, or `"SLOW"`.

## Lesson 2.4: Where Was the Click?

The `event` has the mouse position in `event.x` and `event.y`. Conditionals can check which part of the canvas was clicked.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        EasyDraw.Line divider = new EasyDraw.Line(300, 0, 300, 600);
        EasyDraw.Text message = new EasyDraw.Text(300, 300, "Click anywhere");
        message.setSize(28);

        EasyDraw.canvasEventSetup("<Button-1>", event -> {
            if (event.x < 300 && event.y < 300) {
                message.setText("Top left");
            } else if (event.x >= 300 && event.y < 300) {
                message.setText("Top right");
            } else if (event.x < 300) {
                message.setText("Bottom left");
            } else {
                message.setText("Bottom right");
            }
        });

        EasyDraw.end();
    }
}
```

**Practice:** Add a horizontal line so the four parts are easy to see. Then change the background color to match the part that was clicked.

## Lesson 2.5: Keyboard Events and Boundaries

Keys move a player. Conditionals keep the player on the canvas.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        EasyDraw.Circle player = new EasyDraw.Circle(300, 300, 25);
        player.setColor("blue");

        EasyDraw.canvasEventSetup("<Key>", event -> {
            double x = player.getCenterX();
            double y = player.getCenterY();

            if (event.keysym.equals("Left") && x > 25) {
                x = x - 20;
            } else if (event.keysym.equals("Right") && x < 575) {
                x = x + 20;
            } else if (event.keysym.equals("Up") && y > 25) {
                y = y - 20;
            } else if (event.keysym.equals("Down") && y < 575) {
                y = y + 20;
            }

            player.setCenter(x, y);
        });

        EasyDraw.end();
    }
}
```

{% hint style="info" %}
Key presses only reach Easy Draw when the Easy Draw page is the active browser tab. Click the page first.
{% endhint %}

**Practice:**

1. Turn the player red when it is in the right half of the canvas and blue in the left half.
2. Draw a goal square. When the player is inside it, show `"You win!"`. (Hint: use `&&` to check both x and y.)

## Unit Project: Choose Your Path

Students build an interactive drawing that changes based on what the user does. Ideas:

* **Mood Ring** - clicking different parts of a face changes its expression and color.
* **Quiz Show** - a question with clickable answer boxes that say "Correct!" or "Try again."
* **Maze Escape** - arrow keys move a player who cannot leave the path and wins at the exit.
* **Weather Station** - keys pick the weather and the scene changes to match.

**Requirements:**

* At least one `if`/`else if`/`else` chain.
* At least one compound boolean expression with `&&` or `||`.
* At least one `String` comparison with `.equals()`.
* At least two event handlers, with at least one using `event.x`/`event.y` or `event.keysym`.
* At least one `static` variable that remembers information between events.

| Category     | 4 - Exceeds                                        | 3 - Meets                                      | 2 - Approaching              | 1 - Beginning      |
| ------------ | -------------------------------------------------- | ---------------------------------------------- | ---------------------------- | ------------------ |
| Conditionals | Nested and chained conditionals used purposefully  | `if`/`else if`/`else` and compound expressions | Only simple `if` statements  | No conditionals    |
| Events       | 3+ handlers that work smoothly together            | 2+ handlers using event information            | 1 handler                    | Events do not work |
| State        | Several static variables track the program's state | A static variable remembers information        | State is attempted but buggy | No state           |
| Code quality | Clear names, comments, and organization            | Comments explain each handler                  | Few comments                 | Hard to read       |
| Design       | Creative, polished, with clear instructions        | Works and is easy to use                       | Partly works                 | Does not work      |


# Unit 3: Iteration and Drawings

In this unit students use **loops** to draw patterns, grids, and animations. Loops turn a few lines of code into hundreds of shapes, and the results show right away whether the loop is correct.

{% hint style="info" %}
**Teacher notes**

* **Time:** 11 class periods: 6 lessons (1 class each) and 5 classes for the unit project
* **AP Computer Science A:** Iteration (`while` loops, `for` loops, nested loops, developing algorithms, tracing loops) and an introduction to arrays.
* **Before this unit:** students have finished [Unit 2: If Statements and Drawings](https://easy-draw.joemazzone.net/java-curriculum/unit-2-if-statements-and-drawings).
* **Tracing tip:** have students predict where the first three shapes will be *before* running a loop. The drawing checks their trace.
  {% endhint %}

## Learning Objectives

Students will be able to:

1. Write `for` loops and `while` loops that draw repeated shapes.
2. Use the loop variable in expressions to change position, size, and color.
3. Write nested loops to draw rows and grids.
4. Combine loops and conditionals to draw patterns.
5. Trace a loop and predict how many times it runs and what it draws.
6. Store shapes in an array and loop over the array to change them.

## Lesson 3.1: for Loops

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        for (int i = 0; i < 10; i++) {
            EasyDraw.Circle dot = new EasyDraw.Circle(30 + i * 60, 300, 25);
            dot.setColor("blue");
        }

        EasyDraw.end();
    }
}
```

Trace it as a table: when `i` is 0, x is 30. When `i` is 1, x is 90. When does the loop stop?

The loop variable can change size and color too. Big circles are drawn first so the smaller ones end up on top.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        for (int i = 0; i < 10; i++) {
            EasyDraw.Circle ring = new EasyDraw.Circle(300, 300, 250 - i * 25);
            ring.setColor(i * 25, 0, 255 - i * 25);
        }

        EasyDraw.end();
    }
}
```

**Practice:**

1. Draw a staircase of 8 squares.
2. Draw 36 lines from the center of the canvas, each rotated 10 degrees more than the last. (Hint: draw the same line each time and call `rotate(i * 10)`.)
3. What changes if the loop is `for (int i = 9; i >= 0; i--)`? Predict, then run it.

## Lesson 3.2: while Loops

A `while` loop repeats as long as its condition is `true`. It is useful when we do not know ahead of time how many times to repeat.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        double size = 280;
        int count = 0;
        while (size > 5) {
            EasyDraw.Rectangle square = new EasyDraw.Rectangle(300 - size, 300 - size, size * 2, size * 2);
            if (count % 2 == 0) {
                square.setColor("black");
            } else {
                square.setColor("white");
            }
            size = size * 0.8;
            count++;
        }

        EasyDraw.Text label = new EasyDraw.Text(300, 585, count + " squares");
        label.setColor("red");

        EasyDraw.end();
    }
}
```

**Discussion:** How many squares will be drawn? What happens if we change `0.8` to `1.2`? (An infinite loop! Show students how to stop the program with Ctrl+C.)

## Lesson 3.3: Nested Loops

A loop inside a loop draws rows and columns.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        for (int row = 0; row < 8; row++) {
            for (int col = 0; col < 8; col++) {
                EasyDraw.Rectangle tile = new EasyDraw.Rectangle(col * 75, row * 75, 75, 75);
                if ((row + col) % 2 == 0) {
                    tile.setColor("black");
                } else {
                    tile.setColor("red");
                }
            }
        }

        EasyDraw.end();
    }
}
```

**Discussion:** How many times does the inner loop's body run in total?

**Practice:**

1. Draw a triangle of circles: 1 in the first row, 2 in the second, and so on up to 8. (Hint: the inner loop's condition uses `row`.)
2. Draw a grid of 100 squares that fade from white in the top-left to black in the bottom-right.

## Lesson 3.4: Algorithms with Loops

Loops can count, find the biggest, or add things up while they draw.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        int tallest = 0;
        int tallestIndex = 0;

        for (int i = 0; i < 12; i++) {
            int height = (int) (Math.random() * 400) + 50;
            EasyDraw.Rectangle building = new EasyDraw.Rectangle(i * 50, 600 - height, 48, height);
            building.setColor("dimgray");

            if (height > tallest) {
                tallest = height;
                tallestIndex = i;
            }
        }

        EasyDraw.Circle marker = new EasyDraw.Circle(tallestIndex * 50 + 24, 600 - tallest - 20, 10);
        marker.setColor("red");

        EasyDraw.end();
    }
}
```

**Practice:**

1. Show the average building height in a `Text` object.
2. Color every building taller than 300 pixels `"steelblue"`.

## Lesson 3.5: Arrays of Shapes

An array can store many shapes so a loop can change all of them later.

```java
public class Main {
    static EasyDraw.Circle[] balls = new EasyDraw.Circle[10];

    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        for (int i = 0; i < balls.length; i++) {
            balls[i] = new EasyDraw.Circle(30 + i * 60, 300, 25);
        }

        EasyDraw.canvasEventSetup("<Button-1>", event -> {
            for (EasyDraw.Circle ball : balls) {
                ball.setColor((int) (Math.random() * 256), (int) (Math.random() * 256), (int) (Math.random() * 256));
            }
        });

        EasyDraw.end();
    }
}
```

## Lesson 3.6: Animation

A loop with `Thread.sleep()` moves a shape a little at a time. `main` needs `throws InterruptedException` to use `Thread.sleep()`.

```java
public class Main {
    public static void main(String[] args) throws InterruptedException {
        EasyDraw.loadCanvas();

        EasyDraw.Circle ball = new EasyDraw.Circle(50, 300, 30);
        ball.setColor("red");
        double speed = 10;

        for (int step = 0; step < 200; step++) {
            double x = ball.getCenterX() + speed;
            if (x > 570 || x < 30) {
                speed = -speed;
            }
            ball.setCenter(x, 300);
            Thread.sleep(20);
        }

        EasyDraw.end();
    }
}
```

**Practice:** Make the ball bounce off all four walls by giving it an x speed and a y speed.

## Unit Project: Pattern Generator

Students write a program that draws an original pattern, scene, or animation using loops. Ideas: a quilt, a city at night with lit windows, a field of flowers, a spiral, an animated screensaver.

**Requirements:**

* At least one `for` loop, one `while` loop, and one nested loop.
* At least one conditional inside a loop.
* At least one algorithm that counts, totals, or finds a minimum or maximum while drawing.
* Uses `Math.random()` so each run is different.
* At least 100 shapes from no more than 60 lines of code inside `main`.
* A written trace table for one of the loops (first 4 times through).

| Category     | 4 - Exceeds                                         | 3 - Meets                                 | 2 - Approaching                   | 1 - Beginning |
| ------------ | --------------------------------------------------- | ----------------------------------------- | --------------------------------- | ------------- |
| Loops        | All loop types used in a complex, purposeful design | `for`, `while`, and nested loops all used | Only one or two kinds of loops    | No loops      |
| Algorithms   | Several algorithms affect the drawing               | One counting/total/min/max algorithm      | Algorithm attempted but incorrect | No algorithm  |
| Trace        | Complete and correct, with a predicted drawing      | Complete and correct                      | Partly correct                    | Missing       |
| Code quality | No "magic numbers," clear names and comments        | Clear names and comments                  | Few comments                      | Hard to read  |
| Design       | Original, polished, and different each run          | Complete and different each run           | Same every run                    | Incomplete    |


# Unit 4: Methods and Classes to Abstract Drawings

In this unit students write their own **methods** and **classes**. A `drawTree()` method hides the details of drawing a tree. A `Tree` class goes further: each tree becomes an object with its own instance variables and methods, just like the Easy Draw shapes students have been using all year.

{% hint style="info" %}
**Teacher notes**

* **Time:** 9 class periods: 4 lessons (1 class each) and 5 classes for the unit project
* **AP Computer Science A:** Writing Classes (instance variables, constructors, methods, accessors and mutators, `this`, `static`, encapsulation, and scope).
* **Before this unit:** students have finished [Unit 3: Iteration and Drawings](https://easy-draw.joemazzone.net/java-curriculum/unit-3-iteration-and-drawings).
* **Files:** projects now have three files in one folder: `EasyDraw.java`, `Main.java`, and the student's class, like `Tree.java`. Compile with `javac *.java`.
  {% endhint %}

## Learning Objectives

Students will be able to:

1. Write `static` methods with parameters to draw reusable pictures.
2. Write methods that return a value.
3. Write a class with `private` instance variables, a constructor, accessor methods, and mutator methods.
4. Use `this` to refer to the current object's instance variables.
5. Create many objects from their own class and store them in an array.
6. Explain how classes **abstract** (hide) details so a program is easier to read and change.

## Lesson 4.1: Static Methods That Draw

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas("lightblue");

        drawTree(100, 450, 120);
        drawTree(300, 400, 200);
        drawTree(500, 470, 80);

        EasyDraw.end();
    }

    /** Draws a tree with the bottom of its leaves at (x, y). */
    public static void drawTree(double x, double y, double size) {
        EasyDraw.Rectangle trunk = new EasyDraw.Rectangle(x - size / 8, y, size / 4, size / 2);
        trunk.setColor("saddlebrown");

        EasyDraw.Circle leaves = new EasyDraw.Circle(x, y - size / 4, size / 2);
        leaves.setColor("forestgreen");
    }
}
```

Vocabulary: **method header**, **parameters**, **arguments**, **method call**.

**Practice:**

1. Use a loop in `main` to call `drawTree()` 6 times across the canvas.
2. Add a `String color` parameter so each tree's leaves can be a different color.

## Lesson 4.2: Methods That Return Values

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        EasyDraw.Circle a = new EasyDraw.Circle(200, 300, 60);
        EasyDraw.Circle b = new EasyDraw.Circle(330, 300, 80);

        if (touching(a, b)) {
            a.setColor("red");
            b.setColor("red");
        }

        EasyDraw.end();
    }

    /** Returns true when two circles overlap. */
    public static boolean touching(EasyDraw.Circle c1, EasyDraw.Circle c2) {
        double dx = c1.getCenterX() - c2.getCenterX();
        double dy = c1.getCenterY() - c2.getCenterY();
        double distance = Math.sqrt(dx * dx + dy * dy);
        return distance < c1.getRadius() + c2.getRadius();
    }
}
```

**Practice:** Move circle `b` to (400, 300). Predict the color, then run it.

## Lesson 4.3: Writing a Class

`drawTree()` draws a tree, but afterward we cannot move it or change it. A `Tree` **class** keeps references to its shapes in **instance variables**, so every `Tree` object can be changed later.

`Tree.java`:

```java
public class Tree {
    private double x;
    private double y;
    private double size;
    private EasyDraw.Rectangle trunk;
    private EasyDraw.Circle leaves;

    /** Creates a tree with the bottom of its leaves at (x, y). */
    public Tree(double x, double y, double size) {
        this.x = x;
        this.y = y;
        this.size = size;

        trunk = new EasyDraw.Rectangle(x - size / 8, y, size / 4, size / 2);
        trunk.setColor("saddlebrown");

        leaves = new EasyDraw.Circle(x, y - size / 4, size / 2);
        leaves.setColor("forestgreen");
    }

    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }

    /** Moves the whole tree by dx and dy. */
    public void move(double dx, double dy) {
        x = x + dx;
        y = y + dy;
        trunk.setXY(x - size / 8, y);
        leaves.setCenter(x, y - size / 4);
    }

    public void setLeafColor(String color) {
        leaves.setColor(color);
    }
}
```

`Main.java`:

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas("lightblue");

        Tree oak = new Tree(150, 400, 150);
        Tree maple = new Tree(400, 400, 200);

        maple.setLeafColor("orangered");
        oak.move(-50, 50);

        EasyDraw.end();
    }
}
```

Walk through the parts of the class:

* **Instance variables** (`x`, `y`, `size`, `trunk`, `leaves`) - every `Tree` object has its own copy. They are `private`, so only `Tree`'s own methods can change them. This is **encapsulation**.
* **Constructor** - runs when we write `new Tree(...)`. `this.x = x;` copies the parameter `x` into the instance variable `x`.
* **Accessor methods** (`getX()`, `getY()`) return information.
* **Mutator methods** (`move()`, `setLeafColor()`) change the object.

**Discussion:** `Main` does not know a tree is made of a rectangle and a circle. If we changed the leaves to a triangle, would `Main` need to change? This is **abstraction**.

**Practice:**

1. Add a `grow(double amount)` method that makes the tree bigger. (Hint: change `size`, then update both shapes with their setters.)
2. Add a `toString()` method that returns something like `"Tree at (150.0, 400.0)"`.

## Lesson 4.4: Objects That Respond to Events

A class can set up its own event handlers in its constructor. Each object then responds on its own.

`Balloon.java`:

```java
public class Balloon {
    private static int popped = 0;

    private EasyDraw.Circle body;
    private EasyDraw.Line string;

    public Balloon(double x, double y, String color) {
        string = new EasyDraw.Line(x, y + 40, x, y + 140);
        string.setThickness(2);
        body = new EasyDraw.Circle(x, y, 40);
        body.setColor(color);

        body.eventSetup("<Button-1>", event -> pop());
    }

    public void pop() {
        body.erase();
        string.erase();
        popped++;
        System.out.println("Popped " + popped + " balloons!");
    }

    public static int getPopped() {
        return popped;
    }
}
```

`Main.java`:

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        String[] colors = {"red", "orange", "gold", "green", "blue", "purple"};
        Balloon[] balloons = new Balloon[colors.length];

        for (int i = 0; i < balloons.length; i++) {
            balloons[i] = new Balloon(75 + i * 90, 250, colors[i]);
        }

        EasyDraw.end();
    }
}
```

**Discussion:** `popped` is `static`, but `body` is not. What is the difference? (There is one `popped` shared by every balloon, but each balloon has its own `body`.)

## Unit Project: My Own Class

Students design a class for something that can be drawn and changed, then write a program that uses many objects of that class. Ideas: `Car`, `Fish`, `House`, `Robot`, `Monster`, `Flower`, `Spaceship`.

**Requirements:**

* A class in its own file with at least 3 `private` instance variables, including at least 2 Easy Draw shapes.
* A constructor with parameters that uses `this`.
* At least 2 accessor methods and at least 2 mutator methods (one should move the whole drawing).
* A `toString()` method.
* At least one `static` variable or method in the class.
* `Main` creates at least 5 objects, stored in an array, and uses a loop to call a method on each one.
* At least one event (click or key) changes the objects.
* A short written explanation of how the class **abstracts** the drawing.

| Category     | 4 - Exceeds                                     | 3 - Meets                                        | 2 - Approaching                   | 1 - Beginning          |
| ------------ | ----------------------------------------------- | ------------------------------------------------ | --------------------------------- | ---------------------- |
| Class design | Well-encapsulated class with meaningful methods | All required variables, constructor, and methods | Missing some required parts       | Class does not compile |
| Objects      | Many objects interact in interesting ways       | 5+ objects in an array, changed with a loop      | Objects not stored in an array    | One object             |
| Events       | Objects respond to several kinds of events      | At least one event changes the objects           | Event attempted but does not work | No events              |
| Code quality | Clear names, Javadoc comments on every method   | Comments explain each method                     | Few comments                      | Hard to read           |
| Explanation  | Clearly explains abstraction and encapsulation  | Explains how the class hides details             | Explanation is unclear            | Missing                |


