JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<canvas id='canvas' width='40' height='20'></canvas>
</body>
CSS
canvas {
image-rendering: pixelated;
width: 400px;
height: 200px;
margin: 1em;
border: 1px solid #aaa;
}
JavaScript
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const red = [255, 0, 0, 255];
const green = [0, 255, 0, 255];
const blue = [0, 0, 255, 255];
const black = [0, 0, 0, 255];
function drawPoint(x, y, color) {
const pixel = ctx.createImageData(1,1);
pixel.data.set(color);
ctx.putImageData(pixel, x, 20 - y); // flip y axis to match cartesian coords
}
function drawHyperbola1() {
for (let x = 10; x < 30; ++x) {
drawPoint(x, Math.floor(100 / x + 0.5), red);
}
}
function drawHyperbola2() {
let x = 10;
let y = Math.floor(100 / 10 + 0.5);
for (; x < 30; ++x) {
drawPoint(x, y, green);
const err1 = (y - 100 / (x + 1));
const err2 = (y - 1 - 100 / (x + 1));
const err = err1 * err1 - err2 * err2;
if (err < 0) {
y += 0;
} else {
y -= 1;
}
}
}
function drawHyperbola3() {
let x = 10;
let y = Math.floor(100 / 10 + 0.5);
for (; x < 30; ++x) {
drawPoint(x, y, blue);
const err = 2 * y * x + 2 * y - x - 201;
if (err < 0) {
y += 0;
} else {
y -= 1;
}
}
}
function drawHyperbola4() {
let x = 10;
let y = Math.floor(100 / 10 + 0.5);
let err = 2 * y * x + 2 * y - x - 201;
for (; x < 30; ++x) {
drawPoint(x, y, black);
if (err < 0) {
err += 2 * y - 1;
y += 0;
} else {
err += 2 * y - 2 * x - 5;
y -= 1;
}
}
}
drawHyperbola1();
drawHyperbola2();
drawHyperbola3();
drawHyperbola4();