codepens/euclidean-algorithm-visualizer/dist/script.js

102 lines
2.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

let numMax = 50;
let margin = 5;
let G;
function setup() {
createCanvas(800, 800);
imageMode(CENTER);
G = createGraphics(width * 0.8, height * 0.8);
}
function draw(){
background(255);
let numA = int(map(mouseX, 0, width, 2, numMax));
let numB = int(map(mouseY, 0, height, 2, numMax));
let ratio = numB / numA;
textAlign(LEFT);
showText(100, 60, 40, "numA = " + numA, 0, this);
showText(100, 100, 40, "numB = " + numB, 0, this);
showText(400, 60, 40, "ratio = " + nfc(ratio, 2), 0, this);
Euclidean(ratio, G);
image(G, width / 2, height / 2 + height / 20);
}
function Euclidean(ratio, g) {
let xPos = 0;
let yPos = 0;
let count = 0;
let size = g.width;
g.rectMode(CENTER);
g.noStroke();
g.clear();
while (size > 0.1) {
count++;
//カウントが奇数だった場合、x軸方向に次の四角形を描く
if (count % 2 == 1) {
let xSize = size * ratio;
let ySize = size;
while (xPos + xSize < g.width + 0.1) {
g.push();
g.translate(xPos + xSize / 2, yPos + ySize / 2);
g.fill(100);
g.textAlign(CENTER, CENTER);
myRect(0, 0, xSize - margin, ySize - margin, g);
showText(0, 0, min(xSize, ySize) / 2, count, 255, g);
g.pop();
//座標更新X軸方向に描いた四角形の横の大きさ分だけ
xPos += xSize;
}
//描いた四角形の大きさ分だけ次に描く四角形の大きさを小さくする
size = g.width - xPos;
//カウントが偶数だった場合、y軸方向に次の四角形を描く
} else {
let xSize = size;
let ySize = size / ratio;
while (yPos + ySize < g.width + 0.1) {
g.push();
g.translate(xPos + xSize / 2, yPos + ySize / 2);
g.fill(0);
g.textAlign(CENTER, CENTER);
myRect(0, 0, xSize - margin, ySize - margin, g);
showText(0, 0, min(xSize, ySize) / 2, count, 255, g);
g.pop();
//座標更新Y軸方向に描いた四角形の縦の大きさ分だけ
yPos += ySize;
}
//描いた四角形の大きさ分だけ次に描く四角形の大きさを小さくする
size = g.width - yPos;
}
}
}
function showText(cx, cy, size, value, col, g){
g.push();
g.translate(cx, cy);
g.fill(col);
g.textSize(size);
g.text(value, 0, 0);
g.pop();
}
function myRect(cx, cy, sx, sy, g) {
g.push();
g.translate(cx, cy);
g.noStroke();
g.rect(0, 0, sx, sy);
g.pop();
}