Este código funciona perfectamente. Pero si elimino el comentario de la declaración de cambio, falla por completo. La declaración de cambio parece ser correcta. Cualquier ayuda será apreciada.
function draw(n) { let canvas = document.querySelector('#my-canvas'); let context = canvas.getContext('2d'); context.fillStyle = 'black' let contourInterval = 1500 let contourWidth = 500 let fsize = 1000 let x0 = fsize / 2 let y0 = fsize / 2 for (j = 0, y = -y0; j < fsize; j++, y++) { for (i = 0, x = -x0; i < fsize; i++, x++) { /* switch(n) { case 0: let fun = (x*x + y*y) break; case 1: let fun = (x*x - y*y) break; case 2: let fun = 1.0/(x*x + y*y) break; default: let fun = (x*x + y*y) } */ let fun = (x * x + y * y) if (Math.abs(fun % contourInterval) < contourWidth) { context.fillRect(x + x0 / 2, y + y0 / 2, 1, 1) } } } } draw(1) <canvas id="my-canvas" width="500" height="500"></canvas>El problema es que está declarando la variable fun dentro de la declaración de switch y luego está tratando de usarla afuera más tarde.
Intenta actualizar tu código a lo siguiente:
function draw(n) { let canvas = document.querySelector('#my-canvas'); let context = canvas.getContext('2d'); context.fillStyle = 'black' let contourInterval = 1500 let contourWidth = 500 let fsize = 1000 let x0 = fsize / 2 let y0 = fsize / 2 for (j = 0, y = -y0; j < fsize; j++, y++) { for (i = 0, x = -x0; i < fsize; i++, x++) { let fun = 0 // declare this here outside the scope of the switch statement switch(n) { case 0: // remember to get rid of the `let` keywords in your `case` statments fun = (x*x + y*y) break; case 1: fun = (x*x - y*y) break; case 2: fun = 1.0/(x*x + y*y) break; default: fun = (x*x + y*y) } // now `fun` can be used here without scope problems if (Math.abs(fun % contourInterval) < contourWidth) { context.fillRect(x + x0 / 2, y + y0 / 2, 1, 1) } } } } draw(1) <canvas id="my-canvas" width="500" height="500"></canvas>De esta manera, declara la variable en el ámbito externo y usa la declaración de cambio para establecerla. Ahora se puede utilizar en el ámbito exterior.
Declara diversión primero
function draw(n) { let canvas = document.querySelector('#my-canvas'); let context = canvas.getContext('2d'); context.fillStyle = 'black' let contourInterval = 1500 let contourWidth = 500 let fsize = 1000 let x0 = fsize / 2 let y0 = fsize / 2 for (j = 0, y = -y0; j < fsize; j++, y++) { for (i = 0, x = -x0; i < fsize; i++, x++) { let fun = 0 switch(n) { case 0: fun = (x*x + y*y) break; case 1: fun = (x*x - y*y) break; case 2: fun = 1.0/(x*x + y*y) break; default: fun = (x*x + y*y) } if (Math.abs(fun % contourInterval) < contourWidth) { context.fillRect(x + x0 / 2, y + y0 / 2, 1, 1) } } } } draw(1) <canvas id="my-canvas" width="500" height="500"></canvas>