Drawing Newton's Fractal
Notes
- We are almost there
- We need to map the complex plane to the canvas
- And get the input
- The canvas is (0,0) to (width, height)
- The plane we wish to view is (XMin, YMin) to (XMin + RANGE, YMin + Range)
- This means that (Xmin, YMin) needs to map to (0,0)
- And that (XMin + RANGE, YMin + Range) needs to map to (width, height)
- If we let
- dx = RANGE/width
- dy = RANGE/height
- Then we will
- start at XMin
- step across RANGE times adding dx each time
-
realX = XMin dx = RANGE/width for(let x = 0; x < width; ++x) { // do computations realX += dx } - So realX will take on width values
- realX, realX +dx, realX+dx+dx (realX+2dx), realX + 3dx, ..., realX + (width-1)×dx
- hummmm, maybe we should put in a ≤ in that loop
- Well, nope, since the array is width wide, and 0 to width-1 are the indexes, this is C/javascript not FORTRAN
- Which is the number of pixels we need in the canvas.
- So the final loop is
let realX = XMin let realY = YMin for (let y = 0; y < height; y++) { realX = XMin for (let x = 0; x < width; x++) { // code deleted realX += dx } realY += dy }
- Inside the loop
- At each point (realX, realY)
- Find the root, for the value realX+realYi
- This will return a "root number" and a color.
- I have a predefined array of colors
const COLORS = [[0,0,0], [255,0,0], [0,255,0], [0,0,255]]- This is bad as it assumes only three roots.
- We will learn how to build colors later to overcome this problem.
- But for now, if you change the function, add more colors to the array.
- I want this an array of arrays to make coloring a pixel easy.
-
const offset = (y * width + x) * 4 let answer = FindRoot(realX,realY) ... for(let rgb = 0; rgb < 3; ++rgb) { data[offset + rgb] = COLORS[root][rgb]/iterations } data[offset + 3] = 255 - The real code has some sanity checks.
- I added a check to see that the root was in the range of colors, and if not, mapped it to root 0.
- It might be better to just not set the color if the root is not in the right range.
- Remember, we might have something that diverged.
- I scaled iterations by 2
- Remember our iterations can go to 256*2
- This is bad, I should move the constant to the drawing.js file
- Or provide a function to share this.
- We should finish by adding boxes to allow us to control the view
- Some ideas
- specify (minX, minY) and range
- specify (minX, minY) and (maxX, maxY)
- Specify max iterations, scale factor, ...
- Specify colors for each root, moderate difficulty
- Specify the polynomial, hard
- We have hit a fork in the road, do you want to continue this project?
- Color discussion?
- Clicking on canvas to set (minX, minY) or (maxX, maxY)?
- Anything else...