This is a simple pixel drawer. You can draw lines, circles using JS.
- Clone or download repo
- Execute this line in terminal: node ./startNode.js to start Node server
- 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.
Let's assume that we have x0 = 20px, y0 = 80px, x1 = 80px and y1 = 40px coordinates. Consider the next image:
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);
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;
}
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.
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;
If error > dx than we increment our Y by 1;