main.js

URL: https://mirkwood.cs.edinboro.edu/~bennett/class/cmsc3780/spring2026/notes/javascript/code/newton/main.js
 
import {FunctionName} from './fun1.js'
import {FindRoot, ResetRoots} from './newton.js'

// image constants
// the canvas
const heading = document.getElementById("Main Heading");
heading.innerHTML += " " + FunctionName();

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

const width = canvas.width;
const height = canvas.height;

const imageData = ctx.createImageData(width, height);
const data = imageData.data; 

// buttons and input
let XMIN = -1.5
let YMIN = -1.5
let RANGE = 3;

const xBox = document.getElementById("xmin");
const yBox = document.getElementById("ymin");
const rangeBox = document.getElementById("width");
const executeButton = document.getElementById("doit");

xBox.value = XMIN
yBox.value = YMIN
rangeBox.value = RANGE

// debugging?
const outputArea = document.getElementById("output");

// later these will come from a UI

// later these will be computed when UI changes
let dx, dy 

// These should be calculated, but we need more info
const COLORS = [[0,0,0], [255,0,0], [0,255,0], [0,0,255]];

function NewtonFractal() {
    for (let y = 0; y < height; y++) {
        for (let x = 0; x < width; x++) {
            const i = (y * width + x) * 4;

            let realX = XMIN + x * dx;
            let realY = YMIN + y * dy;

            let answer = FindRoot(realX,realY)

            let root = answer[0];
            if (root > COLORS.length) {
               console.log("Error in root, ", root, " but max is " , COLORS.length);
               root = 0;
            }

            let iterations = answer[1];
            if (iterations == 0) {
                console.log("Iterations are 0"); 
                iterations = 1;

            }

            for(let rgb = 0; rgb < 3; ++rgb) {
                data[i + rgb] = COLORS[root][rgb]/iterations; 
            }
            data[i + 3] = 255; 
        }
    }
}

function ChangePicture() {

    ResetRoots();

    XMIN = parseFloat(xBox.value);
    YMIN = parseFloat(yBox.value);
    RANGE = parseFloat(rangeBox.value);
    dx = RANGE/width
    dy = RANGE/height
    NewtonFractal();
    ctx.putImageData(imageData, 0, 0);
}

executeButton.addEventListener("click",ChangePicture);

ChangePicture();