Giter Site home page Giter Site logo

krassnig / codedraw Goto Github PK

View Code? Open in Web Editor NEW
17.0 4.0 7.0 2.76 MB

CodeDraw is a beginner-friendly drawing library which can be used to create pictures, animations and even interactive applications.

Home Page: https://krassnig.github.io/CodeDrawJavaDoc/

License: MIT License

Java 100.00%
codedraw code java canvas animation drawing educational graphics drawing-library drawing-on-canvas

codedraw's Introduction

CodeDraw

CodeDraw is a beginner-friendly drawing library which can be used to create pictures, animations and even interactive applications. It is designed for people who are just starting to learn programming, enabling them to create graphical applications.

Read the Introduction to CodeDraw for a beginners guide to CodeDraw. It also gives an overview of the features available in CodeDraw.

The JavaDoc for CodeDraw can be found here.

For a C# version of CodeDraw, visit the CodeDrawProject repository.

How To Install

Intellij

Go to releases and download the newest CodeDraw.jar.

Open Intellij with the project where you would like to add CodeDraw. Click on File > Project Structure.... Under Project Settings, select Libraries. At the top left, click on the small plus icon and select the Java option. Go to the downloaded CodeDraw.jar, and select it and then press OK. Now you can import CodeDraw with import codedraw.*; at the top of your Java files.

Eclipse, Maven & Gradle

To install CodeDraw with Eclipse, Maven or Gradle, please refer to the INSTALL.md.

Static Images

Here's is an example of how you can create a static image with the use of CodeDraw.

import codedraw.*;

public class Main {
    public static void main(String[] args) {
        // Creates a new CodeDraw window with a size of 400x400 pixel.
        CodeDraw cd = new CodeDraw(400, 400);

        // Sets the drawing color to red.
        cd.setColor(Palette.RED);
        // Draws the outline of a rectangle.
        cd.drawRectangle(100, 100, 200, 100);
        // Draws a filled square.
        cd.fillSquare(180, 150, 80);

        // Changes the color to light blue.
        cd.setColor(Palette.LIGHT_BLUE);
        cd.fillCircle(300, 200, 50);

        // Finally, the method "show" must be called
        // to display the drawn shapes in the CodeDraw window.
        cd.show();
    }
}

❗ Don't forget to call .show()

static_image.png

Animations

Animations are created by drawing multiple frames and then pausing in between those frames. In CodeDraw, this is achieved by creating a loop in which each iteration draws one frame and then waits a certain amount of time, 1 second or 1000 milliseconds in this case, using the method .show(1000).

import codedraw.*;

public class Main {
    public static void main(String[] args) {
        CodeDraw cd = new CodeDraw(400, 400);

        for (double sec = -Math.PI / 2; !cd.isClosed(); sec += Math.PI / 30) {
            // Clears the entire canvas.
            cd.clear();
            // Draws the second hand of the clock.
            cd.drawLine(200, 200, Math.cos(sec) * 100 + 200, Math.sin(sec) * 100 + 200);

            // Draws the twelve dots.
            for (double j = 0; j < Math.PI * 2; j += Math.PI / 6) {
                cd.fillCircle(Math.cos(j) * 100 + 200, Math.sin(j) * 100 + 200, 4);
            }

            // Displays the drawn objects and waits 1 second.
            cd.show(1000);
        }
    }
}
animation.mp4

Interactive Programs

Interactive programs can be created by reading events from the EventScanner and switching based on the type of event. In older Java versions, the EventScanner can also be used in the same way as the java.util.Scanner with has... and next... methods. A more detailed explanation can be found in the Handling Events section in the Introduction to CodeDraw.

You can also use the CodeDraw Event Code Generator to automatically generate your event code for you.

import codedraw.*;

public class Main {
    public static void main(String[] args) {
        CodeDraw cd = new CodeDraw();

        cd.drawText(200, 200, "Move your mouse over here.");
        cd.show();

        cd.setColor(Palette.RED);

        // Creates an endless loop (until you close the window).
        while (!cd.isClosed()) {
            // Creates a loop that consumes all the currently available events.
            for (var e : cd.getEventScanner()) {
                switch (e) {
                    // If the event is a mouse move event, a red square will be drawn at its location.
                    case MouseMoveEvent a ->
                        cd.fillSquare(a.getX() - 5, a.getY() - 5, 10);
                    default -> { }
                }
            }

            // Display the red squares that have been drawn up to this point.
            cd.show(16);
        }
    }
}
user_interaction.mp4

The Animation Interface

All these examples can also be created using the Animation interface. An instance of the Animation interface can be passed to CodeDraw which subsequently invokes the methods you implement. The following example enables you control a circle with the WASD-keys. The onKeyDown method is triggered each time a key is pressed down and modifies the position of the circle. The draw method is called 60 times per second and draws the circle at the x-y-coordinate.

import codedraw.*;

public class MyAnimation implements Animation {
    public static void main(String[] args) {
        CodeDraw.run(new MyAnimation());
    }

    private int x = 50;
    private int y = 50;

    @Override
    public void onKeyDown(KeyDownEvent event) {
        if (event.getKey() == Key.W) {
            y -= 20;
        }
        else if (event.getKey() == Key.A) {
            x -= 20;
        }
        else if (event.getKey() == Key.S) {
            y += 20;
        }
        else if (event.getKey() == Key.D) {
            x += 20;
        }
    }

    @Override
    public void draw(Image canvas) {
        canvas.clear();
        canvas.fillCircle(x, y, 10);
    }
}
inversion_of_control.mp4

Contributing

Feel free to ask questions, suggest features or make bug reports in the Issue Section. 🙂

codedraw's People

Contributors

krassnig avatar nikkasyan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

codedraw's Issues

Installation issues?

I was trying the maven variant after downloading apache-mvn.

It shows this error:

[FATAL] Non-parseable POM /Depot/jj/pom.xml: Expected root element 'project' but found 'repositories' (position: START_TAG seen <repositories>... @1:14)  @ line 1, column 14

The content of that pom.xml is:

<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>
<dependency>
    <groupId>com.github.Krassnig</groupId>
    <artifactId>CodeDraw</artifactId>
    <version>3.0.0</version>
</dependency>

Perhaps it needs some more information? I only copy/pasted from the main README of the project here.

I downloaded CodeDraw.jar by the way and it is the current working directory (same as I put the pom.xml).

Actually I am trying to find a way to make a local .jar file work, so I am a bit random-poking right now. I may solve this in the coming days via random googling :D - just wanted to mention it here before moving on to try more things. The EP1 .pdf refers to the project here, which is how I found it by the way.

[Suggestion] Font handling in CodeDraw: unavailable Fonts, and how to "work around" this issue

Without any further ado, let me first copy/paste the error I ran into today:

Exception in thread "main" java.lang.IllegalArgumentException: The font Arial is not available on your device.
    at codedraw.TextFormat.setFontName(TextFormat.java:79)
    at VierGewinnt.returnTheDefaultFont(VierGewinnt.java:734)
    at VierGewinnt.enter_game_loop_for_the_GUI(VierGewinnt.java:860)
    at VierGewinnt.run(VierGewinnt.java:979)
    at VierGewinnt.<init>(VierGewinnt.java:174)
    at VierGewinnt.main(VierGewinnt.java:987)

So, the font Arial is not on my linux system, or perhaps it can not be found.

If I omit specifying the Arial font, the very same program works fine. IF I specify
such a font that is not existing on my system, the program will instead terminate,
with the above error message.

(If you are curious, I ran into the above for the last assignment of EPROG1 where
we have to implement Vier Gewinnt.)

So it is not an issue for me; I can simply omit that line, or for EPROG1 presentation
I can put it back in - no problem. But I think this could also be improved a little.

For instance, one obvious solution would be to use the default fallback / generic
font. I assume CodeDraw already has a default font - after all if I do NOT specify
the Arial font, the same code base works fine. So one approach could be to
simply fall back towards that generic font. So the above would be displayed but
not terminate the program, instead, the fallback font is used. (One can reason
that it is my responsibility to handle such a use case via catch/throw, which I
can understand - but this would require adding a few more lines of code, so my
approach is to simply avoid Arial instead - less time investment.)

An alternative may be to add a way for users to specify a fallback font to use
in this event. That way the old behaviour is retained, but we could override
it via something like:

font.setDefaultFontName();

Or something like that. (Where font was: TextFormat font = new TextFormat(); )

There may be a few more ways to go about this, but I only wanted to a) report
this small issue, and b) give a very few suggestions how this could be improved.

If you also have time, perhaps https://github.com/Krassnig/CodeDraw/blob/master/INTRODUCTION.md
could mention a recommendation what to do when a font is not installed on a
given operating system. Although perhaps most folks use windows, no clue.

Anyway, that was it, thanks for polishing CodeDraw!

High DPI graphical rendering

On High DPI devices CodeDraw/AWT upscales the drawn image through bicubic interpolation. The result doesn't look very good usually.

Add Event::getTimeCreated()

This is feature request: the handling of an event might take some time such that events in between are scheduled but should be ignored (e.g. a game might update the visible area but the computation takes too long and we would like to drop clicks that happened before the update completed). An easy way to determine if an event is too old is by assigning a timestamp when the event is scheduled that can be checked by the user. It might be helpful to have the invariant that subsequent calls to EventScanner::nextEvent() return non-decreasing timestamps. Then a simple while loop could drop outdated events.

drawTriangle() for integer values?

Hey there Niklas and whoever else may read this,

I am currently working on the problem set in "Aufgabenblatt 2, Example 5". This is the free-form example
where other students had solutions such as this:

https://i.imgur.com/h0AH6qX.png

So, for one of the shapes / subshapes that I want to draw I am contemplating using drawTriangle().

When I was using it, though, I noticed I had to use double values (6 of them, e. g.
for the 3 vertices or end points or however one calls them).

API is:

public void drawTriangle(double x1,  double y1,  double x2,  double y2,  double x3,  double y3)

x1 - The distance in pixel from the left side of the canvas to the first corner of the triangle.
y1 - The distance in pixel from the top side of the canvas to the first corner of the triangle.
x2 - The distance in pixel from the left side of the canvas to the second corner of the triangle.
y2 - The distance in pixel from the top side of the canvas to the second corner of the triangle.
x3 - The distance in pixel from the left side of the canvas to the third corner of the triangle.
y3 - The distance in pixel from the top side of the canvas to the third corner of the triangle.

My canvas, though, right now only needs integer values. Or at the least I was thinking I was
using integer values for x-coordinate and y-coordinate of the various subshapes.

It is not a big deal either way; I can convert the integer values into double values. But I was
also thinking that there should not be a reason to not allow integer values here? Or perhaps
there is one and I am unaware of that - that could be the case too.

Either way, the TL;DR variant for this suggestion:

Would it be possible to add the "same" method signature as-is, but also allow integer values
for x1, y1 etc...?

The primary rationale here is just for a bit of extra convenience. It's not necessary since we
can convert our integer to double values easily, but if CodeDraw directly could support this
then we can save a tiny bit of code in our implementation.

As always thank you for reading either way.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.