drawing.js

URL: https://mirkwood.cs.edinboro.edu/~bennett/class/cmsc3780/spring2026/notes/javascript/code/seven/drawing.js
 

import {FindRoot} from "./newton.js"

function DoDots(imageData) {
    let width  = imageData.width
    let height = imageData.height
    let data = imageData.data

    for(let dots = 0; dots < 100; ++dots) {
        let x = Math.round(Math.random() * width )
        let y = Math.round(Math.random() * height )

        let offset = (y * width + x) * 4
        data[offset + 0] = Math.round(Math.random() * 255)
        data[offset + 1] = Math.round(Math.random() * 255)
        data[offset + 2] = Math.round(Math.random() * 255)
        data[offset + 3] = 255
    }
}

let XMin = -1.5
let YMin = -1.5
let RANGE = 3

const COLORS = [[0,0,0], [255,0,0], [0,255,0], [0,0,255]]

function NewtonFractal(imageData) {
    let width  = imageData.width
    let height = imageData.height
    let data = imageData.data

    let dx= RANGE/width
    let dy= RANGE/height
    let realX = XMin
    let realY = YMin

    for (let y = 0; y < height; y++) {
        realX = XMin
        for (let x = 0; x < width; x++) {
            const offset = (y * width + x) * 4
      
            let answer = FindRoot(realX,realY)

            let iterations = answer.iterations/2;
            if (iterations == 0) {
                iterations = 1
            }

            if (answer.root > 0 && answer.root < COLORS.length) {
                for(let rgb = 0; rgb < 3; ++rgb) {
                     data[offset + rgb] = COLORS[answer.root][rgb]/iterations
                }
                data[offset + 3] = 255
            }

            realX += dx
        }
        realY += dy
    }
}

export function DrawImage(inset, canvas) {
     const width= canvas.width
     const height = canvas.height
     const ctx = canvas.getContext("2d")

     const imageData = ctx.createImageData(width, height)
     NewtonFractal(imageData);
     ctx.putImageData(imageData,0,0)
}