/pixelDrawer-JS

This is a simple pixel drawer. You can draw lines, circles using JS.

Primary LanguageJavaScript

Русский вариант

Table of Contents

Pixel Drawer

This is a simple pixel drawer. You can draw lines, circles using JS.

Js

How to reproduce?

  1. Clone or download repo
  2. Execute this line in terminal: node ./startNode.js to start Node server
  3. Put it in the browser line: http://localhost:3000/examples/lineDrawer/index.html

NB! after /examples/ you can write lineDrawer or circleDrawer. All examples are placed in examples folder.

How it works?

Line Drawer

Example of drawn line

Let's assume that we have x0 = 20px, y0 = 80px, x1 = 80px and y1 = 40px coordinates. Consider the next image: How line drawer works-1


Steep

The first thing we need to understand whether our line is steep or not. Steep means that (x1 - x0) < (y1 - y0). In other words: width of line is less than height. Our coordinates will not be steep, because (80 - 20) > (80 - 40);

How line drawer works-2

If the line is steep we transpose our coordinates to make it NOT steep, so we can draw it horizontally(from left to right) again.

if (Math.abs(x0 - x1) < Math.abs(y0 - y1)) {
  [x0, y0] = [y0, x0];
  [x1, y1] = [y1, x1];
  steep = true;
}

How line drawer works-3


From left to right

These lines of code will make our coordinates from left to right.

    if (x0 > x1) {
        [x0, x1] = [x1, x0];
        [y0, y1] = [y1, y0];
    }

NB! Whe should always draw our line from left to right and width should always be bigger than height.


Making an error

How line drawer works-4

Now consider this code:

    const dx = x1 - x0;
    const dy = y1 - y0;
    const derror = Math.abs(dy) * 2;
    const yadd = y1 > y0 ? 1 : -1;
    const dx2 = dx * 2;
    let error = 0;

How line drawer works-4

If error > dx than we increment our Y by 1;

How line drawer works-4

Different example: How line drawer works-5

Circle Drawer

Example of drawn circle