\n\n
Los cuartos y quintos parámetros, dw
y dh
, son opcionales. Establecen el ancho y alto para dibujar la imagen de destino. Por defecto, image()
dibuja la imagen de origen completa en su tamaño original.
Los sextos y séptimos parámetros, sx
y sy
, también son opcionales. Estas coordenadas definen la esquina superior izquierda de una subsección para dibujar desde la imagen de origen.
Los octavos y novenos parámetros, sw
y sh
, también son opcionales. Definen el ancho y alto de una subsección para dibujar desde la imagen de origen. Por defecto, image()
dibuja la subsección completa que comienza en (sx, sy)
y se extiende hasta los bordes de la imagen de origen.
El noveno parámetro, fit
, también es opcional. Permite que se dibuje una subsección de la imagen de origen sin afectar su relación de aspecto. Si se pasa CONTAIN
, la subsección completa aparecerá dentro del rectángulo de destino. Si se pasa COVER
, la subsección cubrirá completamente el rectángulo de destino. Esto puede tener el efecto de hacer en la subsección.
Los décimos y undécimos parámetros, xAlign
y yAlign
, también son opcionales. Determinan cómo alinear la subsección ajustada. xAlign
puede establecerse en LEFT
, RIGHT
o CENTER
. yAlign
puede establecerse en TOP
, BOTTOM
o CENTER
. Por defecto, tanto xAlign
como yAlign
se establecen en CENTER
.
imagen a mostrar.
"],"type":[0,"p5.Image|p5.Element|p5.Texture|p5.Framebuffer|p5.FramebufferTexture"]}],[0,{"name":[0,"x"],"description":[0,"\ncoordenada x de la esquina superior izquierda de la imagen.
"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"coordenada y de la esquina superior izquierda de la imagen.
"],"type":[0,"Number"]}],[0,{"name":[0,"width"],"description":[0,"ancho para dibujar la imagen.
"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"height"],"description":[0,"\nalto para dibujar la imagen.
"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"img"],"description":[0,""],"type":[0,"p5.Image|p5.Element|p5.Texture|p5.Framebuffer|p5.FramebufferTexture"]}],[0,{"name":[0,"dx"],"description":[0,"\nla coordenada x del rectángulo de destino\n\nen el cual se dibuja la imagen fuente
"],"type":[0,"Number"]}],[0,{"name":[0,"dy"],"description":[0,"\nla coordenada y del rectángulo de destino\n\nen el cual se dibuja la imagen fuente
"],"type":[0,"Number"]}],[0,{"name":[0,"dWidth"],"description":[0,"\nel ancho del rectángulo de destino
"],"type":[0,"Number"]}],[0,{"name":[0,"dHeight"],"description":[0,"\nla altura del rectángulo de destino
"],"type":[0,"Number"]}],[0,{"name":[0,"sx"],"description":[0,"\np>la coordenada x de la subsección de la imagen fuente\n\npara dibujar en el rectángulo de destino"],"type":[0,"Number"]}],[0,{"name":[0,"sy"],"description":[0,"\nla coordenada y de la subsección de la imagen fuente\n\npara dibujar en el rectángulo de destino
"],"type":[0,"Number"]}],[0,{"name":[0,"sWidth"],"description":[0,"\nel ancho de la subsección de la\n\nimagen fuente para dibujar en el rectángulo de destino
"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"sHeight"],"description":[0,"\nla altura de la subsección de la\n\nimagen fuente para dibujar en el rectángulo de destino
"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"fit"],"description":[0,"\nya sea CONTAIN o COVER
"],"type":[0,"Constant"],"optional":[0,true]}],[0,{"name":[0,"xAlign"],"description":[0,"\n\"ya sea LEFT, RIGHT o CENTER; el valor predeterminado es CENTER
\""],"type":[0,"Constant"],"optional":[0,true]}],[0,{"name":[0,"yAlign"],"description":[0,"\n\"ya sea TOP, BOTTOM o CENTER; el valor predeterminado es CENTER
\""],"type":[0,"Constant"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Draw the image.\n image(img, 0, 0);\n\n describe('An image of the underside of a white umbrella with a gridded ceiling above.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Draw the image.\n image(img, 10, 10);\n\n describe('An image of the underside of a white umbrella with a gridded ceiling above. The image has dark gray borders on its left and top.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Draw the image 50x50.\n image(img, 0, 0, 50, 50);\n\n describe('An image of the underside of a white umbrella with a gridded ceiling above. The image is drawn in the top left corner of a dark gray square.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Draw the center of the image.\n image(img, 25, 25, 50, 50, 25, 25, 50, 50);\n\n describe('An image of a gridded ceiling drawn in the center of a dark gray square.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/moonwalk.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Draw the image and scale it to fit within the canvas.\n image(img, 0, 0, width, height, 0, 0, img.width, img.height, CONTAIN);\n\n describe('An image of an astronaut on the moon. The top and bottom borders of the image are dark gray.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n // Image is 50 x 50 pixels.\n img = loadImage('/assets/laDefense50.png');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Draw the image and scale it to cover the canvas.\n image(img, 0, 0, width, height, 0, 0, img.width, img.height, COVER);\n\n describe('A pixelated image of the underside of a white umbrella with a gridded ceiling above.');\n}\n
\nCambia la ubicación desde la cual se dibujan las imágenes cuando se llama a image().
\n\nPor defecto, los dos primeros parámetros de image() son las coordenadas x e y de la esquina superior izquierda de la imagen. Los siguientes parámetros son su ancho y alto. Esto es lo mismo que llamar a imageMode(CORNER)
.
imageMode(CORNERS)
también utiliza los dos primeros parámetros de image() como las coordenadas x e y de la esquina superior izquierda de la imagen. Los tercer y cuarto parámetros son las coordenadas de su esquina inferior derecha.
imageMode(CENTER)
utiliza los dos primeros parámetros de image() como las coordenadas x e y del centro de la imagen. Los siguientes parámetros son su ancho y alto.
ya sea CORNER, CORNERS o CENTER.
"],"type":[0,"Constant"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use CORNER mode.\n imageMode(CORNER);\n\n // Display the image.\n image(img, 10, 10, 50, 50);\n\n describe('A square image of a brick wall is drawn at the top left of a gray square.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use CORNERS mode.\n imageMode(CORNERS);\n\n // Display the image.\n image(img, 10, 10, 90, 40);\n\n describe('An image of a brick wall is drawn on a gray square. The image is squeezed into a small rectangular area.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use CENTER mode.\n imageMode(CENTER);\n\n // Display the image.\n image(img, 50, 50, 80, 80);\n\n describe('A square image of a brick wall is drawn on a gray square.');\n}\n
\nCarga una imagen para crear un objeto p5.Image.
\n\n\"loadImage()
interpreta el primer parámetro de tres formas diferentes. Si se proporciona la ruta a un archivo de imagen, loadImage()
lo cargará. Las rutas a archivos locales deben ser relativas, como '/assets/thundercat.jpg'
. Las URL como 'https\":\"//ejemplo.com/thundercat.jpg'
pueden ser bloqueadas debido a la seguridad del navegador. También se puede pasar datos de imagen en bruto como una imagen codificada en base64 en la forma 'data:image/png;base64,secuenciaderandomcharacters'
.
El segundo parámetro es opcional. Si se pasa una función, se llamará una vez que se haya cargado la imagen. La función callback puede usar opcionalmente el nuevo objeto p5.Image.
\n\nEl tercer parámetro también es opcional. Si se pasa una función, se llamará si la imagen no se carga correctamente. La función callback puede usar opcionalmente el evento de error.
\n\nLas imágenes pueden tardar en cargarse. Llamar a loadImage()
en preload() asegura que las imágenes se carguen antes de ser utilizadas en setup() o draw().
ruta de la imagen a cargar o imagen codificada en base64.
"],"type":[0,"String"]}],[0,{"name":[0,"successCallback"],"description":[0,"\nfunción llamada con p5.Image una vez que se cargue.
"],"type":[0,"function(p5.Image)"],"optional":[0,true]}],[0,{"name":[0,"failureCallback"],"description":[0,"\nfunción llamada con el evento de error si la imagen no se carga correctamente.
"],"type":[0,"Function(Event)"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"el objeto p5.Image."],"type":[0,"p5.Image"]}],"example":[1,[[0,"\n\nlet img;\n\n// Load the image and create a p5.Image object.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Draw the image.\n image(img, 0, 0);\n\n describe('Image of the underside of a white umbrella and a gridded ceiling.');\n}\n
\n\nfunction setup() {\n // Call handleImage() once the image loads.\n loadImage('/assets/laDefense.jpg', handleImage);\n\n describe('Image of the underside of a white umbrella and a gridded ceiling.');\n}\n\n// Display the image.\nfunction handleImage(img) {\n image(img, 0, 0);\n}\n
\n\nfunction setup() {\n // Call handleImage() once the image loads or\n // call handleError() if an error occurs.\n loadImage('/assets/laDefense.jpg', handleImage, handleError);\n}\n\n// Display the image.\nfunction handleImage(img) {\n image(img, 0, 0);\n\n describe('Image of the underside of a white umbrella and a gridded ceiling.');\n}\n\n// Log the error.\nfunction handleError(event) {\n console.error('Oops!', event);\n}\n
\nElimina el tinte actual establecido por tint().
\n\nnoTint()
restaura las imágenes a sus colores originales.
\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Left.\n // Tint with a CSS color string.\n tint('red');\n image(img, 0, 0);\n\n // Right.\n // Remove the tint.\n noTint();\n image(img, 50, 0);\n\n describe('Two images of an umbrella and a ceiling side-by-side. The image on the left has a red tint.');\n}\n
\nGenera un gif a partir de un boceto y lo guarda en un archivo.
\n\nsaveGif()
puede ser llamado en setup() o en cualquier momento mientras se ejecuta un boceto.
El primer parámetro, fileName
, establece el nombre del archivo del gif.
El segundo parámetro, duration
, establece la duración del GIF en segundos.
El tercer parámetro, options
, es opcional. Si se pasa un objeto, saveGif()
utilizará sus propiedades para personalizar el GIF. saveGif()
reconoce las propiedades delay
, units
, silent
, notificationDuration
y notificationID
.
nombre del archivo del gif.
"],"type":[0,"String"]}],[0,{"name":[0,"duration"],"description":[0,"\nduración en segundos para capturar desde el boceto.
"],"type":[0,"Number"]}],[0,{"name":[0,"options"],"description":[0,"\nun objeto que puede contener cinco propiedades adicionales:\n\n\"delay
, un número que especifica cuánto tiempo esperar antes de grabar;\"\n\n\"units
, una cadena que puede ser 'seconds' o 'frames'. Por defecto es 'seconds';\"\n\n\"silent
, un booleano que define la presencia de notificaciones de progreso. Por defecto es false
;\"\n\n\"notificationDuration
, un número que define cuánto tiempo en segundos durará la notificación final. Por defecto es 0
, lo que significa que la notificación nunca se eliminará;\"\n\n\"notificationID
, una cadena que especifica el ID del elemento DOM de la notificación. Por defecto es 'progressBar’
.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A circle drawn in the middle of a gray square. The circle changes color from black to white, then repeats.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the circle.\n let c = frameCount % 255;\n fill(c);\n\n // Display the circle.\n circle(50, 50, 25);\n}\n\n// Save a 5-second gif when the user presses the 's' key.\nfunction keyPressed() {\n if (key === 's') {\n saveGif('mySketch', 5);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A circle drawn in the middle of a gray square. The circle changes color from black to white, then repeats.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the circle.\n let c = frameCount % 255;\n fill(c);\n\n // Display the circle.\n circle(50, 50, 25);\n}\n\n// Save a 5-second gif when the user presses the 's' key.\n// Wait 1 second after the key press before recording.\nfunction keyPressed() {\n if (key === 's') {\n saveGif('mySketch', 5, { delay: 1 });\n }\n}\n
\nTinta imágenes usando un color.
\n\nLa versión de tint()
con un parámetro se interpreta de cuatro maneras diferentes. Si el parámetro es un número, se interpreta como un valor de escala de grises. Si el parámetro es una cadena, se interpreta como una cadena de color CSS. También se puede usar una matriz de [R, G, B, A]
valores o un objeto p5.Color para establecer el color de la tinta.
La versión de tint()
con dos parámetros utiliza el primero como un valor de escala de grises y el segundo como un valor alfa. Por ejemplo, llamar a tint(255, 128)
hará que una imagen sea 50% transparente.
La versión de tint()
con tres parámetros los interpreta como valores RGB o HSB, dependiendo del actual colorMode(). El cuarto parámetro opcional establece el valor alfa. Por ejemplo, tint(255, 0, 0, 100)
dará a las imágenes una tinta roja y las hará transparentes.
valor rojo o de matiz.
"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"\nvalor verde o de saturación.
"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"\nvalor azul o de brillo.
"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"\ncadena de color CSS.
"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gray"],"description":[0,"\nValor de escala de grises.
"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"values"],"description":[0,"\nun arreglo que contiene los componentes rojo, verde, azul y alfa del color.
"],"type":[0,"Number[]"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"\nel color de tinte
"],"type":[0,"p5.Color"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Left image.\n image(img, 0, 0);\n\n // Right image.\n // Tint with a CSS color string.\n tint('red');\n image(img, 50, 0);\n\n describe('Two images of an umbrella and a ceiling side-by-side. The image on the right has a red tint.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Left image.\n image(img, 0, 0);\n\n // Right image.\n // Tint with RGB values.\n tint(255, 0, 0);\n image(img, 50, 0);\n\n describe('Two images of an umbrella and a ceiling side-by-side. The image on the right has a red tint.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Left.\n image(img, 0, 0);\n\n // Right.\n // Tint with RGBA values.\n tint(255, 0, 0, 100);\n image(img, 50, 0);\n\n describe('Two images of an umbrella and a ceiling side-by-side. The image on the right has a transparent red tint.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Left.\n image(img, 0, 0);\n\n // Right.\n // Tint with grayscale and alpha values.\n tint(255, 180);\n image(img, 50, 0);\n\n describe('Two images of an umbrella and a ceiling side-by-side. The image on the right is transparent.');\n}\n
\nCrea un objeto ancho en píxeles.
"],"type":[0,"Integer"]}],[0,{"name":[0,"height"],"description":[0,"\nalto en píxeles.
"],"type":[0,"Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"nuevo objeto p5.Image."],"type":[0,"p5.Image"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels into memory.\n img.loadPixels();\n\n // Set all the image's pixels to black.\n for (let x = 0; x < img.width; x += 1) {\n for (let y = 0; y < img.height; y += 1) {\n img.set(x, y, 0);\n }\n }\n\n // Update the image's pixel values.\n img.updatePixels();\n\n // Draw the image.\n image(img, 17, 17);\n\n describe('A black square drawn in the middle of a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the image's pixels into memory.\n img.loadPixels();\n\n // Create a color gradient.\n for (let x = 0; x < img.width; x += 1) {\n for (let y = 0; y < img.height; y += 1) {\n // Calculate the transparency.\n let a = map(x, 0, img.width, 0, 255);\n\n // Create a p5.Color object.\n let c = color(0, a);\n\n // Set the pixel's color.\n img.set(x, y, c);\n }\n }\n\n // Update the image's pixels.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A square with a horizontal color gradient that transitions from gray to black.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Image object.\n let img = createImage(66, 66);\n\n // Load the pixels into memory.\n img.loadPixels();\n // Get the current pixel density.\n let d = pixelDensity();\n\n // Calculate the pixel that is halfway through the image's pixel array.\n let halfImage = 4 * (d * img.width) * (d * img.height / 2);\n\n // Set half of the image's pixels to black.\n for (let i = 0; i < halfImage; i += 4) {\n // Red.\n img.pixels[i] = 0;\n // Green.\n img.pixels[i + 1] = 0;\n // Blue.\n img.pixels[i + 2] = 0;\n // Alpha.\n img.pixels[i + 3] = 255;\n }\n\n // Update the image's pixels.\n img.updatePixels();\n\n // Display the image.\n image(img, 17, 17);\n\n describe('A black square drawn in the middle of a gray square.');\n}\n
\nGuarda el lienzo actual como una imagen.
\n\nPor defecto, saveCanvas()
guarda el lienzo como una imagen PNG llamada untitled.png
.
El primer parámetro, filename
, es opcional. Es una cadena que establece el nombre del archivo. Si se incluye una extensión de archivo, como en saveCanvas('drawing.png')
, entonces la imagen se guardará utilizando ese formato.
El segundo parámetro, extension
, también es opcional. Establece el formato de los archivos. Se pueden usar 'png'
o 'jpg'
. Por ejemplo, saveCanvas('drawing', 'jpg')
guarda el lienzo en un archivo llamado drawing.jpg
.
Nota: El navegador guardará el archivo inmediatamente o pedirá al usuario que lo haga a través de una ventana de diálogo.
"],"line":[0,153],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"selectedCanvas"],"description":[0,"\nreferencia a un elemento canvas específico de HTML5.
"],"type":[0,"p5.Framebuffer|p5.Element|HTMLCanvasElement"]}],[0,{"name":[0,"filename"],"description":[0,"\n\"nombre del archivo. Por defecto, es 'untitled'.
\""],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"extension"],"description":[0,"\n\"extensión del archivo, ya sea 'jpg' o 'png'. Por defecto, es 'png'.
\""],"type":[0,"String"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"filename"],"description":[0,""],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"extension"],"description":[0,""],"type":[0,"String"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n background(255);\n\n // Save the canvas to 'untitled.png'.\n saveCanvas();\n\n describe('A white square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(255);\n\n // Save the canvas to 'myCanvas.jpg'.\n saveCanvas('myCanvas.jpg');\n\n describe('A white square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(255);\n\n // Save the canvas to 'myCanvas.jpg'.\n saveCanvas('myCanvas', 'jpg');\n\n describe('A white square.');\n}\n
\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n background(255);\n\n // Save the canvas to 'untitled.png'.\n saveCanvas(cnv);\n\n describe('A white square.');\n}\n
\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n background(255);\n\n // Save the canvas to 'myCanvas.jpg'.\n saveCanvas(cnv, 'myCanvas.jpg');\n\n describe('A white square.');\n}\n
\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n background(255);\n\n // Save the canvas to 'myCanvas.jpg'.\n saveCanvas(cnv, 'myCanvas', 'jpg');\n\n describe('A white square.');\n}\n
\nCaptura una secuencia de fotogramas del lienzo que pueden ser guardados como imágenes.
\n\nsaveFrames()
crea un array de objetos de fotograma. Cada fotograma se almacena como un objeto con su tipo de archivo, nombre de archivo y datos de imagen como una cadena. Por ejemplo, el primer fotograma guardado podría tener las siguientes propiedades:
{ ext: \"'png', filenmame: 'frame0', imageData: 'data:image/octet-stream;base64, abc123' }
.
El primer parámetro, filename
, establece el prefijo para los nombres de archivo. Por ejemplo, configurar el prefijo como 'frame'
generaría los archivos de imagen frame0.png
, frame1.png
, y así sucesivamente.
El segundo parámetro, extension
, establece el tipo de archivo ya sea 'png'
o 'jpg'
.
El tercer parámetro, duration
, establece la duración a grabar en segundos. La duración máxima es de 15 segundos.
El cuarto parámetro, framerate
, establece el número de fotogramas a grabar por segundo. El valor máximo de velocidad de fotogramas es 22. Se aplican límites a duration
y framerate
para evitar el uso excesivo de memoria. La grabación de lienzos grandes puede hacer que los bocetos se bloqueen fácilmente o incluso los navegadores web.
El quinto parámetro, callback
, es opcional. Si se pasa una función, los archivos de imagen no se guardarán por defecto. La función callback puede ser utilizada para procesar un array que contiene los datos de cada fotograma capturado. El array de datos de imagen contiene una secuencia de objetos con tres propiedades para cada fotograma: imageData
, filename
, y extension
.
Nota: Los fotogramas se descargan como archivos de imagen individuales por defecto.
"],"line":[0,558],"params":[1,[[0,{"name":[0,"filename"],"description":[0,"prefijo del nombre del archivo.
"],"type":[0,"String"]}],[0,{"name":[0,"extension"],"description":[0,"extensión del archivo, ya sea 'jpg' o 'png'.
"],"type":[0,"String"]}],[0,{"name":[0,"duration"],"description":[0,"duración en segundos para grabar. Este parámetro estará limitado a ser menor o igual a 15.
"],"type":[0,"Number"]}],[0,{"name":[0,"framerate"],"description":[0,"número de fotogramas para guardar por segundo. Este parámetro estará limitado a ser menor o igual a 22.
"],"type":[0,"Number"]}],[0,{"name":[0,"callback"],"description":[0,"función callback que se ejecutará para manejar los datos de la imagen. Esta función debe aceptar un array como argumento. El array contendrá el número especificado de fotogramas de objetos. Cada objeto tiene tres propiedades: imageData
, filename
, y extension
.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A square repeatedly changes color from blue to pink.');\n}\n\nfunction draw() {\n let r = frameCount % 255;\n let g = 50;\n let b = 100;\n background(r, g, b);\n}\n\n// Save the frames when the user presses the 's' key.\nfunction keyPressed() {\n if (key === 's') {\n saveFrames('frame', 'png', 1, 5);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A square repeatedly changes color from blue to pink.');\n}\n\nfunction draw() {\n let r = frameCount % 255;\n let g = 50;\n let b = 100;\n background(r, g, b);\n}\n\n// Print 5 frames when the user presses the mouse.\nfunction mousePressed() {\n saveFrames('frame', 'png', 1, 5, printFrames);\n}\n\n// Prints an array of objects containing raw image data, filenames, and extensions.\nfunction printFrames(frames) {\n for (let frame of frames) {\n print(frame);\n }\n}\n
\nCopia una región de píxeles de una imagen a otra.
\n\nEl primer parámetro, srcImage
, es el objeto p5.Image para mezclar.
Los siguientes cuatro parámetros, sx
, sy
, sw
y sh
, determinan la región de la cual mezclar la imagen de origen. (sx, sy)
es la esquina superior izquierda de la región. sw
y sh
son el ancho y la altura de la región.
Los siguientes cuatro parámetros, dx
, dy
, dw
y dh
, determinan la región del lienzo en la cual mezclar. (dx, dy)
es la esquina superior izquierda de la región. dw
y dh
son el ancho y la altura de la región.
El décimo parámetro, blendMode
, establece el efecto utilizado para mezclar los colores de las imágenes. Las opciones son BLEND
, DARKEST
, LIGHTEST
, DIFFERENCE
, MULTIPLY
, EXCLUSION
, SCREEN
, REPLACE
, OVERLAY
, HARD_LIGHT
, SOFT_LIGHT
, DODGE
, BURN
, ADD
o NORMAL
.
imagen de origen.
"],"type":[0,"p5.Image"]}],[0,{"name":[0,"sx"],"description":[0,"\ncoordenada x de la esquina superior izquierda de la imagen de origen.
"],"type":[0,"Integer"]}],[0,{"name":[0,"sy"],"description":[0,"\ny-coordenada de la esquina superior izquierda de la imagen de origen.
"],"type":[0,"Integer"]}],[0,{"name":[0,"sw"],"description":[0,"\nancho de la imagen de origen.
"],"type":[0,"Integer"]}],[0,{"name":[0,"sh"],"description":[0,"\nalto de la imagen de origen.
"],"type":[0,"Integer"]}],[0,{"name":[0,"dx"],"description":[0,"\ncoordenada x de la esquina superior izquierda del destino.
"],"type":[0,"Integer"]}],[0,{"name":[0,"dy"],"description":[0,"\ncoordenada y de la esquina superior izquierda del destino.
"],"type":[0,"Integer"]}],[0,{"name":[0,"dw"],"description":[0,"\nancho de la imagen de destino.
"],"type":[0,"Integer"]}],[0,{"name":[0,"dh"],"description":[0,"\nalto de la imagen de destino.
"],"type":[0,"Integer"]}],[0,{"name":[0,"blendMode"],"description":[0,"\nel modo de mezcla. Puede ser BLEND, DARKEST, LIGHTEST, DIFFERENCE,\nMULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\nSOFT_LIGHT, DODGE, BURN, ADD o NORMAL.
"],"type":[0,"Constant"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"sx"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"sy"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"sw"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"sh"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dx"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dy"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dw"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dh"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"blendMode"],"description":[0,""],"type":[0,"Constant"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img0;\nlet img1;\n\n// Load the images.\nfunction preload() {\n img0 = loadImage('/assets/rockies.jpg');\n img1 = loadImage('/assets/bricks_third.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use the mountains as the background.\n background(img0);\n\n // Display the bricks.\n image(img1, 0, 0);\n\n // Display the bricks faded into the landscape.\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n\n describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears faded on the right of the image.');\n}\n
\n\nlet img0;\nlet img1;\n\n// Load the images.\nfunction preload() {\n img0 = loadImage('/assets/rockies.jpg');\n img1 = loadImage('/assets/bricks_third.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use the mountains as the background.\n background(img0);\n\n // Display the bricks.\n image(img1, 0, 0);\n\n // Display the bricks partially transparent.\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n\n describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears transparent on the right of the image.');\n}\n
\n\nlet img0;\nlet img1;\n\n// Load the images.\nfunction preload() {\n img0 = loadImage('/assets/rockies.jpg');\n img1 = loadImage('/assets/bricks_third.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use the mountains as the background.\n background(img0);\n\n // Display the bricks.\n image(img1, 0, 0);\n\n // Display the bricks washed out into the landscape.\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n\n describe('A wall of bricks in front of a mountain landscape. The same wall of bricks appears washed out on the right of the image.');\n}\n
\nCopia píxeles de una imagen fuente a una región del lienzo.
\n\nEl primer parámetro, srcImage
, es el objeto p5.Image a mezclar. La imagen fuente puede ser el lienzo en sí mismo o un objeto p5.Image. copy()
escalara los píxeles de la región fuente si no es del mismo tamaño que la región de destino.
Los siguientes cuatro parámetros, sx
, sy
, sw
y sh
, determinan la región a copiar desde la imagen fuente. (sx, sy)
es la esquina superior izquierda de la región. sw
y sh
son el ancho y la altura de la región.
Los siguientes cuatro parámetros, dx
, dy
, dw
y dh
, determinan la región del lienzo a copiar. (dx, dy)
es la esquina superior izquierda de la región. dw
y dh
son el ancho y la altura de la región.
imagen fuente.
"],"type":[0,"p5.Image|p5.Element"]}],[0,{"name":[0,"sx"],"description":[0,"\ncoordenada x de la esquina superior izquierda de la imagen fuente.
"],"type":[0,"Integer"]}],[0,{"name":[0,"sy"],"description":[0,"\ncoordenada y de la esquina superior izquierda de la imagen fuente.
"],"type":[0,"Integer"]}],[0,{"name":[0,"sw"],"description":[0,"\nancho de la imagen fuente.
"],"type":[0,"Integer"]}],[0,{"name":[0,"sh"],"description":[0,"\nalto de la imagen fuente.
"],"type":[0,"Integer"]}],[0,{"name":[0,"dx"],"description":[0,"\ncoordenada x de la esquina superior izquierda del destino.
"],"type":[0,"Integer"]}],[0,{"name":[0,"dy"],"description":[0,"\ncoordenada y de la esquina superior izquierda del destino.
"],"type":[0,"Integer"]}],[0,{"name":[0,"dw"],"description":[0,"\nancho de la imagen de destino.
"],"type":[0,"Integer"]}],[0,{"name":[0,"dh"],"description":[0,"\nalto de la imagen de destino.
"],"type":[0,"Integer"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"sx"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"sy"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"sw"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"sh"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dx"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dy"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dw"],"description":[0,""],"type":[0,"Integer"]}],[0,{"name":[0,"dh"],"description":[0,""],"type":[0,"Integer"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use the mountains as the background.\n background(img);\n\n // Copy a region of pixels to another spot.\n copy(img, 7, 22, 10, 10, 35, 25, 50, 50);\n\n // Outline the copied region.\n stroke(255);\n noFill();\n square(7, 22, 10);\n\n describe('An image of a mountain landscape. A square region is outlined in white. A larger square contains a pixelated view of the outlined region.');\n}\n
\nAplica un filtro de imagen al lienzo.
\n\nLas opciones predefinidas son:
\n\nINVERTIR
\nInvierte los colores de la imagen. No se utiliza ningún parámetro.
GRAY
\nConvierte la imagen a escala de grises. No se utiliza ningún parámetro.
THRESHOLD
\nConvierte la imagen a blanco y negro. Los píxeles con un valor de escala de grises\nsuperior a un umbral dado se convierten en blanco. El resto se convierte en negro.\nEl umbral debe estar entre 0.0 (negro) y 1.0 (blanco). Si no se especifica ningún\nvalor, se usa 0.5.
OPACO
\nEstablece el canal alfa como completamente opaco. No se utiliza ningún parámetro.
POSTERIZE
\nLimita el número de colores en la imagen. Cada canal de color se limita al número\nde colores especificado. Los valores entre 2 y 255 son válidos, pero los\nresultados son más evidentes con valores más bajos. El valor predeterminado es 4.
BLUR
\nDifumina la imagen. El nivel de difuminación se especifica mediante un radio de\ndifuminación. Valores más altos aumentan el difuminado. El valor predeterminado es 4.\nSe utiliza un desenfoque gaussiano en el modo P2D
. Se utiliza un desenfoque\nde caja en el modo WEBGL
.
ERODE
\nReduce las áreas claras. No se utiliza ningún parámetro.
DILATE
\nAumenta las áreas claras. No se utiliza ningún parámetro.
filter()
utiliza WebGL en segundo plano de forma predeterminada porque es más rápido.\nEsto se puede desactivar en el modo P2D
agregando un argumento false
,\ncomo en filter(BLUR, false)
. Esto puede ser útil para mantener el cómputo\nfuera de la GPU o para solucionar problemas de falta de soporte de WebGL.
En el modo WebgL, filter()
también puede usar shaders personalizados. Consulta\ncreateFilterShader() para obtener más\ninformación.
uno de THRESHOLD, GRAY, OPAQUE, INVERT, POSTERIZE, BLUR, ERODE, DILATE o BLUR.
"],"type":[0,"Constant"]}],[0,{"name":[0,"filterParam"],"description":[0,"\nparámetro único para cada filtro.
"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"useWebGL"],"description":[0,"\n\"bandera para controlar si se utilizan filtros WebGL rápidos (GPU) o filtros de imagen originales (CPU); por defecto es true
.
shader que ha sido cargado, con el fragment shader usando un uniform tex0
.
\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the INVERT filter.\n filter(INVERT);\n\n describe('A blue brick wall.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the GRAY filter.\n filter(GRAY);\n\n describe('A brick wall drawn in grayscale.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the THRESHOLD filter.\n filter(THRESHOLD);\n\n describe('A brick wall drawn in black and white.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the OPAQUE filter.\n filter(OPAQUE);\n\n describe('A red brick wall.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the POSTERIZE filter.\n filter(POSTERIZE, 3);\n\n describe('An image of a red brick wall drawn with limited color palette.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the BLUR filter.\n filter(BLUR, 3);\n\n describe('A blurry image of a red brick wall.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the DILATE filter.\n filter(DILATE);\n\n describe('A red brick wall with bright lines between each brick.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the ERODE filter.\n filter(ERODE);\n\n describe('A red brick wall with faint lines between each brick.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Apply the BLUR filter.\n // Don't use WebGL.\n filter(BLUR, 3, false);\n\n describe('A blurry image of a red brick wall.');\n}\n
\nObtiene un píxel o una región de píxeles del lienzo.
\n\nget()
es fácil de usar pero no es tan rápido como pixels. Usa pixels para leer muchos valores de píxeles.
La versión de get()
sin parámetros devuelve todo el lienzo.
La versión de get()
con dos parámetros se interpreta como coordenadas. Devuelve un array con los valores [R, G, B, A]
del píxel en el punto dado.
La versión de get()
con cuatro parámetros se interpreta como coordenadas y dimensiones. Devuelve una subsección del lienzo como un objeto p5.Image. Los dos primeros parámetros son las coordenadas de la esquina superior izquierda de la subsección. Los dos últimos parámetros son el ancho y el alto de la subsección.
Usa p5.Image.get() para trabajar directamente con objetos p5.Image.
"],"line":[0,820],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,"\ncoordenada x del píxel.
"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"\ncoordenada y del píxel.
"],"type":[0,"Number"]}],[0,{"name":[0,"w"],"description":[0,"\nancho de la subsección que se devolverá.
"],"type":[0,"Number"]}],[0,{"name":[0,"h"],"description":[0,"\nalto de la subsección que se devolverá.
"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[]]}],[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"Number"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"subsección con un objeto p5.Image"],"type":[0,"p5.Image"]}],"example":[1,[[0,"\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Get the entire canvas.\n let c = get();\n\n // Display half the canvas.\n image(c, 50, 0);\n\n describe('Two identical mountain landscapes shown side-by-side.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Get the color of a pixel.\n let c = get(50, 90);\n\n // Style the square with the pixel's color.\n fill(c);\n noStroke();\n\n // Display the square.\n square(25, 25, 50);\n\n describe('A mountain landscape with an olive green square in its center.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0);\n\n // Get a region of the image.\n let c = get(0, 0, 50, 50);\n\n // Display the region.\n image(c, 50, 50);\n\n describe('A mountain landscape drawn on top of another mountain landscape.');\n}\n
\nCarga el valor actual de cada píxel en el lienzo en el arreglo de\npíxeles.
\nloadPixels()
debe ser llamado antes de leer o escribir en\npíxeles.
\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0, 100, 100);\n\n // Get the pixel density.\n let d = pixelDensity();\n\n // Calculate the halfway index in the pixels array.\n let halfImage = 4 * (d * width) * (d * height / 2);\n\n // Load the pixels array.\n loadPixels();\n\n // Copy the top half of the canvas to the bottom.\n for (let i = 0; i < halfImage; i += 1) {\n pixels[i + halfImage] = pixels[i];\n }\n\n // Update the canvas.\n updatePixels();\n\n describe('Two identical images of mountain landscapes, one on top of the other.');\n}\n
\nUn array que contiene el color de cada píxel en el lienzo.
\n\nLos colores se almacenan como números que representan los valores de rojo, verde, azul y alfa (RGBA). pixels
es un array unidimensional por razones de rendimiento.
Cada píxel ocupa cuatro elementos en el array pixels
, uno para cada valor de RGBA. Por ejemplo, el píxel en las coordenadas (0, 0) almacena sus valores RGBA en pixels[0]
, pixels[1]
, pixels[2]
y pixels[3]
, respectivamente. El siguiente píxel en las coordenadas (1, 0) almacena sus valores RGBA en pixels[4]
, pixels[5]
, pixels[6]
y pixels[7]
. Y así sucesivamente. El array pixels
para un lienzo de 100×100 tiene 100 × 100 × 4 = 40.000 elementos.
Algunas pantallas utilizan varios píxeles más pequeños para establecer el color en un solo punto. La función pixelDensity() devuelve la densidad de píxeles del lienzo. Las pantallas de alta densidad a menudo tienen una pixelDensity() de 2. En una pantalla así, el array pixels
para un lienzo de 100×100 tiene 200 × 200 × 4 = 160.000 elementos.
Acceder a los valores de RGBA para un punto en el lienzo requiere un poco de matemáticas como se muestra a continuación. La función loadPixels() debe ser llamada antes de acceder al array pixels
. La función updatePixels() debe ser llamada después de realizar cualquier cambio.
\nfunction setup() {\n createCanvas(100, 100);\n\n // Load the pixels array.\n loadPixels();\n\n // Set the dot's coordinates.\n let x = 50;\n let y = 50;\n\n // Get the pixel density.\n let d = pixelDensity();\n\n // Set the pixel(s) at the center of the canvas black.\n for (let i = 0; i < d; i += 1) {\n for (let j = 0; j < d; j += 1) {\n let index = 4 * ((y * d + j) * width * d + (x * d + i));\n // Red.\n pixels[index] = 0;\n // Green.\n pixels[index + 1] = 0;\n // Blue.\n pixels[index + 2] = 0;\n // Alpha.\n pixels[index + 3] = 255;\n }\n }\n\n // Update the canvas.\n updatePixels();\n\n describe('A black dot in the middle of a gray rectangle.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Load the pixels array.\n loadPixels();\n\n // Get the pixel density.\n let d = pixelDensity();\n\n // Calculate the halfway index in the pixels array.\n let halfImage = 4 * (d * width) * (d * height / 2);\n\n // Make the top half of the canvas red.\n for (let i = 0; i < halfImage; i += 4) {\n // Red.\n pixels[i] = 255;\n // Green.\n pixels[i + 1] = 0;\n // Blue.\n pixels[i + 2] = 0;\n // Alpha.\n pixels[i + 3] = 255;\n }\n\n // Update the canvas.\n updatePixels();\n\n describe('A red rectangle drawn above a gray rectangle.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Color object.\n let pink = color(255, 102, 204);\n\n // Load the pixels array.\n loadPixels();\n\n // Get the pixel density.\n let d = pixelDensity();\n\n // Calculate the halfway index in the pixels array.\n let halfImage = 4 * (d * width) * (d * height / 2);\n\n // Make the top half of the canvas red.\n for (let i = 0; i < halfImage; i += 4) {\n pixels[i] = red(pink);\n pixels[i + 1] = green(pink);\n pixels[i + 2] = blue(pink);\n pixels[i + 3] = alpha(pink);\n }\n\n // Update the canvas.\n updatePixels();\n\n describe('A pink rectangle drawn above a gray rectangle.');\n}\n
\nEstablece el color de un píxel o dibuja una imagen en el lienzo.
\nset()
es fácil de usar pero no es tan rápido como\npixels. Usa pixels\npara establecer muchos valores de píxeles.
set()
interpreta los dos primeros parámetros como coordenadas x, y. \nInterpreta el último parámetro como un valor de escala de grises, un arreglo de píxeles [R, G, B, A]
, un objeto p5.Color, o un\nobjeto p5.Image. Si se pasa una imagen, los dos primeros\nparámetros establecen las coordenadas para la esquina superior izquierda de la imagen,\nindependientemente del imageMode() actual.
Se debe llamar a updatePixels() después de usar\nset()
para que los cambios aparezcan.
Coordenada x del píxel.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"Coordenada y del píxel.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"c"],"description":[0,"valor de escala de grises | arreglo de píxeles |\n p5.Color | p5.Image para copiar.
\n"],"type":[0,"Number|Number[]|Object"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Set four pixels to black.\n set(30, 20, 0);\n set(85, 20, 0);\n set(85, 75, 0);\n set(30, 75, 0);\n\n // Update the canvas.\n updatePixels();\n\n describe('Four black dots arranged in a square drawn on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let black = color(0);\n\n // Set four pixels to black.\n set(30, 20, black);\n set(85, 20, black);\n set(85, 75, black);\n set(30, 75, black);\n\n // Update the canvas.\n updatePixels();\n\n describe('Four black dots arranged in a square drawn on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(255);\n\n // Draw a horizontal color gradient.\n for (let x = 0; x < 100; x += 1) {\n for (let y = 0; y < 100; y += 1) {\n // Calculate the grayscale value.\n let c = map(x, 0, 100, 0, 255);\n\n // Set the pixel using the grayscale value.\n set(x, y, c);\n }\n }\n\n // Update the canvas.\n updatePixels();\n\n describe('A horiztonal color gradient from black to white.');\n}\n
\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use the image to set all pixels.\n set(0, 0, img);\n\n // Update the canvas.\n updatePixels();\n\n describe('An image of a mountain landscape.');\n}\n
\nActualiza el lienzo con los valores RGBA en el arreglo de píxeles.
\nupdatePixels()
solo necesita ser llamado después de cambiar valores en el arreglo de píxeles. Tales cambios pueden hacerse directamente después de llamar a loadPixels() o llamando a set().
Coordenada x de la esquina superior izquierda de la región a actualizar.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"y"],"description":[0,"Coordenada y de la esquina superior izquierda de la región a actualizar.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"w"],"description":[0,"Ancho de la región a actualizar.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"h"],"description":[0,"Alto de la región a actualizar.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\n// Load the image.\nfunction preload() {\n img = loadImage('/assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Display the image.\n image(img, 0, 0, 100, 100);\n\n // Get the pixel density.\n let d = pixelDensity();\n\n // Calculate the halfway index in the pixels array.\n let halfImage = 4 * (d * width) * (d * height / 2);\n\n // Load the pixels array.\n loadPixels();\n\n // Copy the top half of the canvas to the bottom.\n for (let i = 0; i < halfImage; i += 1) {\n pixels[i + halfImage] = pixels[i];\n }\n\n // Update the canvas.\n updatePixels();\n\n describe('Two identical images of mountain landscapes, one on top of the other.');\n}\n
\nAplica una matriz de transformación al sistema de coordenadas.
\nTransformaciones como\ntranslate(),\nrotate(), y\nscale()\nutilizan multiplicación de matriz-vector detrás de escena. Una tabla de números,\nllamada matriz, codifica cada transformación. Los valores en la matriz\nluego multiplican cada punto en el lienzo, que está representado por un vector.
\napplyMatrix()
permite aplicar muchas transformaciones a la vez. Consulta\nWikipedia\ny MDN\npara obtener más detalles sobre transformaciones.
Hay dos formas de llamar a applyMatrix()
en dos y tres dimensiones.
En el modo 2D, los parámetros a
, b
, c
, d
, e
, y f
, corresponden a\nelementos en la siguiente matriz de transformación:
\n\n\n
Los números se pueden pasar individualmente, como en\napplyMatrix(2, 0, 0, 0, 2, 0)
. También se pueden pasar en un arreglo, como en\napplyMatrix([2, 0, 0, 0, 2, 0])
.
En el modo 3D, los parámetros a
, b
, c
, d
, e
, f
, g
, h
, i
,\nj
, k
, l
, m
, n
, o
, y p
corresponden a elementos en la\nsiguiente matriz de transformación:
Los números se pueden pasar individualmente, como en\napplyMatrix(2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1)
. También se pueden\npasar en un arreglo, como en\napplyMatrix([2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1])
.
Por defecto, las transformaciones se acumulan. Las funciones\npush() y pop()\nse pueden usar para aislar transformaciones dentro de grupos de dibujo distintos.
\nNota: Las transformaciones se restablecen al principio del bucle de dibujo. Llamar\napplyMatrix()
dentro de la función draw() no\ncausará que las formas se transformen continuamente.
un array que contiene los elementos de la matriz de transformación. Su longitud debe ser 6 (2D) o 16 (3D).
\n"],"type":[0,"Array"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"a"],"description":[0,"un elemento de la matriz de transformación.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"b"],"description":[0,"un elemento de la matriz de transformación.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"c"],"description":[0,"un elemento de la matriz de transformación.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"d"],"description":[0,"un elemento de la matriz de transformación.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"e"],"description":[0,"un elemento de la matriz de transformación.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"f"],"description":[0,"un elemento de la matriz de transformación.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"a"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"b"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"c"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"d"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"e"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"f"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"g"],"description":[0,"un elemento de la matriz de transformación.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"h"],"description":[0,"un elemento de la matriz de transformación.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"i"],"description":[0,"un elemento de la matriz de transformación.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"j"],"description":[0,"un elemento de la matriz de transformación.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"k"],"description":[0,"un elemento de la matriz de transformación.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"l"],"description":[0,"un elemento de la matriz de transformación.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"m"],"description":[0,"un elemento de la matriz de transformación.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"n"],"description":[0,"un elemento de la matriz de transformación.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"o"],"description":[0,"un elemento de la matriz de transformación.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"p"],"description":[0,"un elemento de la matriz de transformación.
\n"],"type":[0,"Number"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n applyMatrix(1, 0, 0, 1, 50, 50);\n\n // Draw the circle at coordinates (0, 0).\n circle(0, 0, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n let m = [1, 0, 0, 1, 50, 50];\n applyMatrix(m);\n\n // Draw the circle at coordinates (0, 0).\n circle(0, 0, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A white rectangle on a gray background. The rectangle's long axis runs from top-left to bottom-right.\");\n}\n\nfunction draw() {\n background(200);\n\n // Rotate the coordinate system 1/8 turn.\n let angle = QUARTER_PI;\n let ca = cos(angle);\n let sa = sin(angle);\n applyMatrix(ca, sa, -sa, ca, 0, 0);\n\n // Draw a rectangle at coordinates (50, 0).\n rect(50, 0, 40, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'Two white squares on a gray background. The larger square appears at the top-center. The smaller square appears at the top-left.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw a square at (30, 20).\n square(30, 20, 40);\n\n // Scale the coordinate system by a factor of 0.5.\n applyMatrix(0.5, 0, 0, 0.5, 0, 0);\n\n // Draw a square at (30, 20).\n // It appears at (15, 10) after scaling.\n square(30, 20, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white quadrilateral on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the shear factor.\n let angle = QUARTER_PI;\n let shearFactor = 1 / tan(HALF_PI - angle);\n\n // Shear the coordinate system along the x-axis.\n applyMatrix(1, 0, shearFactor, 1, 0, 0);\n\n // Draw the square.\n square(0, 0, 50);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube rotates slowly against a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system a little more each frame.\n let angle = frameCount * 0.01;\n let ca = cos(angle);\n let sa = sin(angle);\n applyMatrix(ca, 0, sa, 0, 0, 1, 0, 0, -sa, 0, ca, 0, 0, 0, 0, 1);\n\n // Draw a box.\n box();\n}\n
\nBorra todas las transformaciones aplicadas al sistema de coordenadas.
\n"],"line":[0,246],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'Two circles drawn on a gray background. A blue circle is at the top-left and a red circle is at the bottom-right.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw a red circle at the coordinates (25, 25).\n fill('blue');\n circle(25, 25, 20);\n\n // Clear all transformations.\n // The origin is now at the top-left corner.\n resetMatrix();\n\n // Draw a blue circle at the coordinates (25, 25).\n fill('red');\n circle(25, 25, 20);\n}\n
\nRota el sistema de coordenadas.
\nDe forma predeterminada, el eje x positivo apunta hacia la derecha y el eje y positivo\napunta hacia abajo. La función rotate()
cambia esta orientación\nrotando el sistema de coordenadas alrededor del origen. Todo lo dibujado después\nde llamar a rotate()
aparecerá rotado.
El primer parámetro, angle
, es la cantidad a rotar. Por ejemplo, llamar a\nrotate(1)
rota el sistema de coordenadas en sentido horario 1 radián que es\ncasi 57˚. rotate()
interpreta los valores de ángulo usando el\nangleMode() actual.
El segundo parámetro, axis
, es opcional. Se utiliza para orientar rotaciones en 3D\nen modo WebGL. Si se pasa un p5.Vector, como en\nrotate(QUARTER_PI, miVector)
, entonces el sistema de coordenadas se rotará\nQUARTER_PI
radianes alrededor de myVector
. Si se pasa un arreglo de componentes \nde vector, como en rotate(QUARTER_PI, [1, 0, 0])
, entonces el sistema de coordenadas\nse rotará QUARTER_PI
radianes alrededor de un vector con los componentes\n[1, 0, 0]
.
De forma predeterminada, las transformaciones se acumulan. Por ejemplo, llamar a rotate(1)
\ndos veces tiene el mismo efecto que llamar a rotate(2)
una vez. Las\nfunciones push() y pop()\nse pueden usar para aislar transformaciones dentro de grupos de dibujo distintos.
Nota: Las transformaciones se restablecen al principio del bucle de dibujo. Llamar\na rotate(1)
dentro de la función draw() no hará que\nlas formas giren.
el ángulo de rotación, especificado en radianes\n o grados, dependiendo del ángulo angleMode
\n"],"type":[0,"Number"]}],[0,{"name":[0,"axis"],"description":[0,"(en 3D) el eje alrededor del cual rotar
\n"],"type":[0,"p5.Vector|Number[]"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n \"A white rectangle on a gray background. The rectangle's long axis runs from top-left to bottom-right.\"\n );\n}\n\nfunction draw() {\n background(200);\n\n // Rotate the coordinate system 1/8 turn.\n rotate(QUARTER_PI);\n\n // Draw a rectangle at coordinates (50, 0).\n rect(50, 0, 40, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n \"A white rectangle on a gray background. The rectangle's long axis runs from top-left to bottom-right.\"\n );\n}\n\nfunction draw() {\n background(200);\n\n // Rotate the coordinate system 1/16 turn.\n rotate(QUARTER_PI / 2);\n\n // Rotate the coordinate system another 1/16 turn.\n rotate(QUARTER_PI / 2);\n\n // Draw a rectangle at coordinates (50, 0).\n rect(50, 0, 40, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use degrees.\n angleMode(DEGREES);\n\n describe(\n \"A white rectangle on a gray background. The rectangle's long axis runs from top-left to bottom-right.\"\n );\n}\n\nfunction draw() {\n background(200);\n\n // Rotate the coordinate system 1/8 turn.\n rotate(45);\n\n // Draw a rectangle at coordinates (50, 0).\n rect(50, 0, 40, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A white rectangle on a gray background. The rectangle rotates slowly about the top-left corner. It disappears and reappears periodically.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Rotate the coordinate system a little more each frame.\n let angle = frameCount * 0.01;\n rotate(angle);\n\n // Draw a rectangle at coordinates (50, 0).\n rect(50, 0, 40, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\"A cube on a gray background. The cube's front face points to the top-right.\");\n}\n\nfunction draw() {\n background(200);\n\n // Rotate the coordinate system 1/8 turn about\n // the axis [1, 1, 0].\n let axis = createVector(1, 1, 0);\n rotate(QUARTER_PI, axis);\n\n // Draw a box.\n box();\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\"A cube on a gray background. The cube's front face points to the top-right.\");\n}\n\nfunction draw() {\n background(200);\n\n // Rotate the coordinate system 1/8 turn about\n // the axis [1, 1, 0].\n let axis = [1, 1, 0];\n rotate(QUARTER_PI, axis);\n\n // Draw a box.\n box();\n}\n
\nRota el sistema de coordenadas alrededor del eje x en modo WebGL.
\nEl parámetro, angle
, es la cantidad a rotar. Por ejemplo, llamar a\nrotateX(1)
rota el sistema de coordenadas alrededor del eje x por 1 radián.\nrotateX()
interpreta los valores de ángulo usando el\nangleMode().
De forma predeterminada, las transformaciones se acumulan. Por ejemplo, llamar a rotateX(1)
\ndos veces tiene el mismo efecto que llamar a rotateX(2)
una vez. Las\nfunciones push() y pop()\nse pueden usar para aislar transformaciones dentro de grupos de dibujo distintos.
Nota: Las transformaciones se restablecen al principio del bucle de dibujo. Llamar\na rotateX(1)
dentro de la función draw() no hará que\nlas formas giren.
ángulo de rotación en el angleMode() actual.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system 1/8 turn.\n rotateX(QUARTER_PI);\n\n // Draw a box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system 1/16 turn.\n rotateX(QUARTER_PI / 2);\n\n // Rotate the coordinate system 1/16 turn.\n rotateX(QUARTER_PI / 2);\n\n // Draw a box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Use degrees.\n angleMode(DEGREES);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system 1/8 turn.\n rotateX(45);\n\n // Draw a box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube rotates slowly against a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system a little more each frame.\n let angle = frameCount * 0.01;\n rotateX(angle);\n\n // Draw a box.\n box();\n}\n
\nRota el sistema de coordenadas alrededor del eje y- en modo WebGL.
\nEl parámetro, angle
, es la cantidad a rotar. Por ejemplo, llamar a\nrotateY(1)
rota el sistema de coordenadas alrededor del eje y- por 1 radián.\nrotateY()
interpreta los valores de ángulo utilizando el\nangleMode() actual.
Por defecto, las transformaciones se acumulan. Por ejemplo, llamar rotateY(1)
\ndos veces tiene el mismo efecto que llamar rotateY(2)
una vez. Las\nfunciones push() y pop()\npueden ser utilizadas para aislar transformaciones dentro de grupos de dibujo distintos.
Nota: Las transformaciones se reinician al inicio del ciclo de dibujo. Llamar\nrotateY(1)
dentro de la función draw() no hará que\nlas formas giren.
ángulo de rotación en el angleMode() actual.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system 1/8 turn.\n rotateY(QUARTER_PI);\n\n // Draw a box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system 1/16 turn.\n rotateY(QUARTER_PI / 2);\n\n // Rotate the coordinate system 1/16 turn.\n rotateY(QUARTER_PI / 2);\n\n // Draw a box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Use degrees.\n angleMode(DEGREES);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system 1/8 turn.\n rotateY(45);\n\n // Draw a box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube rotates slowly against a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system a little more each frame.\n let angle = frameCount * 0.01;\n rotateY(angle);\n\n // Draw a box.\n box();\n}\n
\nRota el sistema de coordenadas alrededor del eje z- en modo WebGL.
\nEl parámetro, angle
, es la cantidad a rotar. Por ejemplo, llamar a\nrotateZ(1)
rota el sistema de coordenadas alrededor del eje z- por 1 radián.\nrotateZ()
interpreta los valores de ángulo utilizando el\nangleMode() actual.
Por defecto, las transformaciones se acumulan. Por ejemplo, llamar rotateZ(1)
\ndos veces tiene el mismo efecto que llamar rotateZ(2)
una vez. Las\nfunciones push() y pop()\npueden ser utilizadas para aislar transformaciones dentro de grupos de dibujo distintos.
Nota: Las transformaciones se reinician al inicio del ciclo de dibujo. Llamar\nrotateZ(1)
dentro de la función draw() no hará que\nlas formas giren.
ángulo de rotación en el angleMode() actual.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system 1/8 turn.\n rotateZ(QUARTER_PI);\n\n // Draw a box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system 1/16 turn.\n rotateZ(QUARTER_PI / 2);\n\n // Rotate the coordinate system 1/16 turn.\n rotateZ(QUARTER_PI / 2);\n\n // Draw a box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Use degrees.\n angleMode(DEGREES);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system 1/8 turn.\n rotateZ(45);\n\n // Draw a box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube rotates slowly against a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Rotate the coordinate system a little more each frame.\n let angle = frameCount * 0.01;\n rotateZ(angle);\n\n // Draw a box.\n box();\n}\n
\nEscala el sistema de coordenadas.
\nDe forma predeterminada, las formas se dibujan en su escala original. Un rectángulo que tiene 50\npíxeles de ancho parece ocupar la mitad del ancho de un lienzo de 100 píxeles de ancho.\nLa función scale()
puede reducir o ampliar el sistema de coordenadas para que\nlas formas aparezcan a diferentes tamaños. Hay dos formas de llamar a scale()
con\nparámetros que establecen el factor de escala(s).
La primera forma de llamar a scale()
utiliza números para establecer la cantidad de escalado.\nEl primer parámetro, s
, establece la cantidad para escalar cada eje. Por ejemplo,\nllamar a scale(2)
estira los ejes x-, y-, y z- por un factor de 2. Los\nsiguientes dos parámetros, y
y z
, son opcionales. Establecen la cantidad para\nescalar el eje y- y eje z-. Por ejemplo, llamar a scale(2, 0.5, 1)
estira\nel eje x por un factor de 2, encoge el eje y- por un factor de 0.5 y\ndeja sin cambios el eje z-.
La segunda forma de llamar a scale()
utiliza un objeto p5.Vector\npara establecer los factores de escala. Por ejemplo, llamar a scale(myVector)
\nutiliza los componentes x-, y-, y z- de myVector
para establecer la cantidad de\nescalado a lo largo de los ejes x-, y- y z-. Hacerlo es lo mismo que llamar\na scale(myVector.x, myVector.y, myVector.z)
.
De forma predeterminada, las transformaciones se acumulan. Por ejemplo, llamar a scale(1)
\ndos veces tiene el mismo efecto que llamar a scale(2)
una vez. Los\npush() y pop() funciones\nse pueden utilizar para aislar transformaciones dentro de grupos de dibujo distintos.
Nota: Las transformaciones se restablecen al principio del bucle de dibujo. Llamar\na scale(2)
dentro de la función draw() no hará que\nlas formas crezcan continuamente.
cantidad para escalar a lo largo del eje x- positivo.
\n"],"type":[0,"Number|p5.Vector|Number[]"]}],[0,{"name":[0,"y"],"description":[0,"cantidad para escalar a lo largo del eje y- positivo. Por defecto, s
.
cantidad para escalar a lo largo del eje z positivo. Por defecto, y
.
vector cuyos componentes deben usarse para escalar.
\n"],"type":[0,"p5.Vector|Number[]"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'Two white squares on a gray background. The larger square appears at the top-center. The smaller square appears at the top-left.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw a square at (30, 20).\n square(30, 20, 40);\n\n // Scale the coordinate system by a factor of 0.5.\n scale(0.5);\n\n // Draw a square at (30, 20).\n // It appears at (15, 10) after scaling.\n square(30, 20, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A rectangle and a square drawn in white on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw a square at (30, 20).\n square(30, 20, 40);\n\n // Scale the coordinate system by factors of\n // 0.5 along the x-axis and\n // 1.3 along the y-axis.\n scale(0.5, 1.3);\n\n // Draw a square at (30, 20).\n // It appears as a rectangle at (15, 26) after scaling.\n square(30, 20, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A rectangle and a square drawn in white on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw a square at (30, 20).\n square(30, 20, 40);\n\n // Create a p5.Vector object.\n let v = createVector(0.5, 1.3);\n\n // Scale the coordinate system by factors of\n // 0.5 along the x-axis and\n // 1.3 along the y-axis.\n scale(v);\n\n // Draw a square at (30, 20).\n // It appears as a rectangle at (15, 26) after scaling.\n square(30, 20, 40);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'A red box and a blue box drawn on a gray background. The red box appears embedded in the blue box.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Style the spheres.\n noStroke();\n\n // Draw the red sphere.\n fill('red');\n box();\n\n // Scale the coordinate system by factors of\n // 0.5 along the x-axis and\n // 1.3 along the y-axis and\n // 2 along the z-axis.\n scale(0.5, 1.3, 2);\n\n // Draw the blue sphere.\n fill('blue');\n box();\n}\n
\nInclina el eje x- para que las formas parezcan sesgadas.
\nDe forma predeterminada, los ejes x- e y- son perpendiculares. La función shearX()
transforma \nel sistema de coordenadas de modo que las coordenadas x- se traducen mientras\nlas coordenadas y- permanecen fijas.
El primer parámetro, angle
, es la cantidad de inclinación. Por ejemplo, llamar a\nshearX(1)
transforma todas las coordenadas x- usando la fórmula\nx = x + y * tan(angle)
. shearX()
interpreta los valores de ángulo utilizando el\nangleMode() actual.
De forma predeterminada, las transformaciones se acumulan. Por ejemplo, llamar a\nshearX(1)
dos veces tiene el mismo efecto que llamar a shearX(2)
una vez. Las\npush() y\npop() funciones se pueden utilizar para aislar\ntransformaciones dentro de grupos de dibujo distintos.
Nota: Las transformaciones se restablecen al principio del bucle de dibujo. Llamar\na shearX(1)
dentro de la función draw() no hará\nque las formas se inclinen continuamente.
ángulo de inclinación en el angleMode() actual.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white quadrilateral on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Shear the coordinate system along the x-axis.\n shearX(QUARTER_PI);\n\n // Draw the square.\n square(0, 0, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use degrees.\n angleMode(DEGREES);\n\n describe('A white quadrilateral on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Shear the coordinate system along the x-axis.\n shearX(45);\n\n // Draw the square.\n square(0, 0, 50);\n}\n
\nInclina el eje y- para que las formas aparezcan sesgadas.
\nDe forma predeterminada, los ejes x- e y- son perpendiculares. La función shearY()
transforma \nel sistema de coordenadas de modo que las coordenadas y- se traducen mientras\nlas coordenadas x- permanecen fijas.
El primer parámetro, angle
, es la cantidad de inclinación. Por ejemplo, llamar a\nshearY(1)
transforma todas las coordenadas y- usando la fórmula\ny = y + x * tan(angle)
. shearY()
interpreta los valores de ángulo utilizando el\nangleMode() actual.
De forma predeterminada, las transformaciones se acumulan. Por ejemplo, llamar a\nshearY(1)
dos veces tiene el mismo efecto que llamar a shearY(2)
una vez. Las\npush() y\npop() funciones se pueden utilizar para aislar\ntransformaciones dentro de grupos de dibujo distintos.
Nota: Las transformaciones se restablecen al principio del bucle de dibujo. Llamar\na shearY(1)
dentro de la función draw() no hará\nque las formas se inclinen continuamente.
ángulo de inclinación en el angleMode() actual.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white quadrilateral on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Shear the coordinate system along the x-axis.\n shearY(QUARTER_PI);\n\n // Draw the square.\n square(0, 0, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use degrees.\n angleMode(DEGREES);\n\n describe('A white quadrilateral on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Shear the coordinate system along the x-axis.\n shearY(45);\n\n // Draw the square.\n square(0, 0, 50);\n}\n
\nDesplaza el sistema de coordenadas.
\nDe forma predeterminada, el origen (0, 0)
está en la esquina superior izquierda del lienzo en modo 2D \ny en el centro en el modo WebGL. La función translate()
desplaza el origen\na una posición diferente. Todo lo dibujado después de llamar a translate()
\nparecerá estar desplazado. Hay dos formas de llamar a translate()
con\nparámetros que establecen la posición del origen.
La primera forma de llamar a translate()
utiliza números para establecer la cantidad de\ndesplazamiento. Los dos primeros parámetros, x
y y
, establecen la cantidad de\ndesplazamiento a lo largo de los ejes x- e y- positivos. Por ejemplo, llamar a\ntranslate(20, 30)
desplaza el origen 20 píxeles a lo largo del eje x- y 30\npíxeles a lo largo del eje y-. El tercer parámetro, z
, es opcional. Establece la \ncantidad de desplazamiento a lo largo del eje z- positivo. Por ejemplo, llamar a\ntranslate(20, 30, 40)
desplaza el origen 20 píxeles a lo largo del eje x-,\n30 píxeles a lo largo del eje y- y 40 píxeles a lo largo del eje z-.
La segunda forma de llamar a translate()
utiliza un objeto \np5.Vector para establecer la cantidad de\ndesplazamiento. Por ejemplo, llamar a translate(myVector)
utiliza el x-, y- \ny z- componentes de myVector
para establecer la cantidad de desplazamiento a lo largo del x-,\ny- y z-ejes. Hacer esto es lo mismo que llamar a\ntranslate(myVector.x, myVector.y, myVector.z)
.
De forma predeterminada, las transformaciones se acumulan. Por ejemplo, llamar a\ntranslate(10, 0)
dos veces tiene el mismo efecto que llamar a\ntranslate(20, 0)
una vez. Las funciones push() y\npop() se pueden utilizar para aislar\ntransformaciones dentro de grupos de dibujo distintos.
Nota: Las transformaciones se restablecen al principio del bucle de dibujo. Llamar\na translate(10, 0)
dentro de la función draw() no hará\nque las formas se muevan continuamente.
cantidad a desplazar a lo largo del eje x- positivo.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"cantidad a desplazar a lo largo del eje y- positivo.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,"cantidad a desplazar a lo largo del eje z- positivo.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"vector"],"description":[0,"vector por el que desplazar.
\n"],"type":[0,"p5.Vector"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw a circle at coordinates (0, 0).\n circle(0, 0, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'Two circles drawn on a gray background. The blue circle on the right overlaps the red circle at the center.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw the red circle.\n fill('red');\n circle(0, 0, 40);\n\n // Translate the origin to the right.\n translate(25, 0);\n\n // Draw the blue circle.\n fill('blue');\n circle(0, 0, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle moves slowly from left to right on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the x-coordinate.\n let x = frameCount * 0.2;\n\n // Translate the origin.\n translate(x, 50);\n\n // Draw a circle at coordinates (0, 0).\n circle(0, 0, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Create a p5.Vector object.\n let v = createVector(50, 50);\n\n // Translate the origin by the vector.\n translate(v);\n\n // Draw a circle at coordinates (0, 0).\n circle(0, 0, 40);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'Two spheres sitting side-by-side on gray background. The sphere at the center is red. The sphere on the right is blue.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Turn on the lights.\n lights();\n\n // Style the spheres.\n noStroke();\n\n // Draw the red sphere.\n fill('red');\n sphere(10);\n\n // Translate the origin to the right.\n translate(30, 0, 0);\n\n // Draw the blue sphere.\n fill('blue');\n sphere(10);\n}\n
\ncursor()
cambia la apariencia de el cursor y cuenta con tres parámetros.
El primer parámetro, type
, define el tipo de cursor que se mostrará. Entre las opciones predefinidas se encuentran ARROW
, CROSS
, HAND
, MOVE
, TEXT
, y WAIT
.
cursor()
también reconoce propiedades de cursor que son estándar de CSS. Estas pueden ser usadas si se pasan como cadena de caracteres: 'help'
, 'wait'
, 'crosshair'
,'not-allowed'
, 'zoom-in'
, and 'grab'
. Si se proporciona la ruta a una imagen, por ejemplo: cursor('/assets/target.png'); entonces esa imagen se usará como cursor. Las imágenes deben estar en formato .cur, .gif, .jpg, .jpeg o .png y deben tener como máximo 32 por 32 píxeles de tamaño.
El segundo parámetro, x
, y el tercer parámetro, y
son opcionales y pueden ser utilizados para especificar la posición inicial del cursor. Por defecto, ambos tienen un valor de 0, lo que hace que el cursor comience en la esquina superior izquierda si se utiliza una imagen como cursor. Si se desea cambiar esta posición inicial, el valor proporcionado para x
y y
debe ser menor que el ancho y alto de la imagen, respectivamente.
Opciones predefinidas: ya sea ARROW, CROSS, HAND, MOVE, TEXT, o WAIT. Propiedades de cursor estándar de CSS: ’crosshair’, ‘not-allowed’, ‘grab’, etc. Ruta a una imagen.
\n"],"line":[0,209],"params":[1,[[0,{"name":[0,"type"],"description":[0,"Opciones predefinidas: ya sea ARROW, CROSS, HAND, MOVE, TEXT, o WAIT.\n Propiedades de cursor estándar de CSS: ’crosshair’, ‘not-allowed’, ‘grab’, etc.\n Ruta a una imagen.
\n"],"type":[0,"String|Constant"]}],[0,{"name":[0,"x"],"description":[0,"punto activo horizontal del cursor.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"y"],"description":[0,"punto activo vertical del cursor.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A gray square. The cursor appears as crosshairs.');\n}\n\nfunction draw() {\n background(200);\n\n // Set the cursor to crosshairs: +\n cursor(CROSS);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A gray square divided into quadrants. The cursor image changes when the mouse moves to each quadrant.');\n}\n\nfunction draw() {\n background(200);\n\n // Divide the canvas into quadrants.\n line(50, 0, 50, 100);\n line(0, 50, 100, 50);\n\n // Change cursor based on mouse position.\n if (mouseX < 50 && mouseY < 50) {\n cursor(CROSS);\n } else if (mouseX > 50 && mouseY < 50) {\n cursor('progress');\n } else if (mouseX > 50 && mouseY > 50) {\n cursor('https://avatars0.githubusercontent.com/u/1617169?s=16');\n } else {\n cursor('grab');\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('An image of three purple curves follows the mouse. The image shifts when the mouse is pressed.');\n}\n\nfunction draw() {\n background(200);\n\n // Change the cursor's active spot\n // when the mouse is pressed.\n if (mouseIsPressed === true) {\n cursor('https://avatars0.githubusercontent.com/u/1617169?s=16', 8, 8);\n } else {\n cursor('https://avatars0.githubusercontent.com/u/1617169?s=16');\n }\n}\n
\nLa variable deltaTime
rastrea el número de milisegundos que tomó dibujar el último fotograma.
deltaTime
contiene entonces la cantidad de tiempo que tomó draw() para ejecutarse durante el fotograma anterior.
Esta variable es útil para crear animaciones sensibles al tiempo o cálculos físicos que deben mantenerse constantes independientemente de los cuadros por segundo.
\n"],"line":[0,124],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nlet x = 0;\nlet speed = 0.05;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Set the frameRate to 30.\n frameRate(30);\n\n describe('A white circle moves from left to right on a gray background. It reappears on the left side when it reaches the right side.');\n}\n\nfunction draw() {\n background(200);\n\n // Use deltaTime to calculate\n // a change in position.\n let deltaX = speed * deltaTime;\n\n // Update the x variable.\n x += deltaX;\n\n // Reset x to 0 if it's\n // greater than 100.\n if (x > 100) {\n x = 0;\n }\n\n // Use x to set the circle's\n // position.\n circle(x, 50, 20);\n}\n
\ndescribe()
genera una descripción del lienzo, la cual es accesible para lectores de pantalla y otras tecnologías de asistencia. describe()
cuenta con dos parámetros.
El primer parámetro, text
, cumple la función de describir lo que se puede observar en el lienzo.
El segundo parámetro, display
es opcional y determina de qué manera se va a mostrar la descripción.
Si LABEL
se pasa como argumento, por ejemplo: describe('Descripción del lienzo.', LABEL)
, la descripción será visible en un elemento ‘div’ al lado del lienzo. Por otro lado, si FALLBACK
se pasa como argumento, por ejemplo: describe(' Descripción del lienzo.', FALLBACK)
, la descripción será visible solo para los lectores de pantalla. Este es el modo predeterminado.
Lee ‘ Escribiendo descripciones accesibles para lienzos’ para aprender más sobre cómo hacer que tus ‘sketches’ sean accesibles.
\n"],"line":[0,18],"params":[1,[[0,{"name":[0,"text"],"description":[0,"descripción del lienzo.
\n"],"type":[0,"String"]}],[0,{"name":[0,"display"],"description":[0,"ya sea LABEL o FALLBACK.
\n"],"type":[0,"Constant"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n background('pink');\n\n // Draw a heart.\n fill('red');\n noStroke();\n circle(67, 67, 20);\n circle(83, 67, 20);\n triangle(91, 73, 75, 95, 59, 73);\n\n // Add a general description of the canvas.\n describe('A pink square with a red heart in the bottom-right corner.');\n}\n
\n\nfunction setup() {\n background('pink');\n\n // Draw a heart.\n fill('red');\n noStroke();\n circle(67, 67, 20);\n circle(83, 67, 20);\n triangle(91, 73, 75, 95, 59, 73);\n\n // Add a general description of the canvas\n // and display it for debugging.\n describe('A pink square with a red heart in the bottom-right corner.', LABEL);\n}\n
\n\nfunction draw() {\n background(200);\n\n // The expression\n // frameCount % 100\n // causes x to increase from 0\n // to 99, then restart from 0.\n let x = frameCount % 100;\n\n // Draw the circle.\n fill(0, 255, 0);\n circle(x, 50, 40);\n\n // Add a general description of the canvas.\n describe(`A green circle at (${x}, 50) moves from left to right on a gray square.`);\n}\n
\n\nfunction draw() {\n background(200);\n\n // The expression\n // frameCount % 100\n // causes x to increase from 0\n // to 99, then restart from 0.\n let x = frameCount % 100;\n\n // Draw the circle.\n fill(0, 255, 0);\n circle(x, 50, 40);\n\n // Add a general description of the canvas\n // and display it for debugging.\n describe(`A green circle at (${x}, 50) moves from left to right on a gray square.`, LABEL);\n}\n
\ndescribeElement()
genera una descripción de los elementos presentes en el lienzo, la cual es accesible para lectores de pantalla y otras tecnologías de asistencia.
Los elementos son formas o grupos de formas que juntas crean significado. Por ejemplo, unos círculos superpuestos podrían formar un elemento “ojo”.
describeElement()
cuenta con tres parámetros.
El primer parámetro, name
, es el nombre del elemento.
El segundo parámetro, text
, es la descripción del elemento.
El tercer parámetro, display
, es opcional y determina de qué manera se va a mostrar la descripción. Si LABEL
se pasa como argumento, por ejemplo: describe('Descripción del lienzo.', LABEL)
, la descripción será visible en un elemento ‘div’ al lado del lienzo. Sin embargo, el uso de LABEL
crea mensajes duplicados que son ineficientes para los usuarios de lectores de pantalla, por lo que recomendamos utilizar únicamente LABEL
durante la fase de desarrollo. Por otro lado, si FALLBACK
se pasa como argumento, por ejemplo: describe('Descripción del lienzo.', FALLBACK)
, la descripción será visible solo para los lectores de pantalla. Este es el modo predeterminado.
Lee ‘ Escribiendo descripciones accesibles para lienzos’ para aprender más sobre cómo hacer que tus ‘sketches’ sean accesibles.
\n"],"line":[0,162],"params":[1,[[0,{"name":[0,"name"],"description":[0,"nombre del elemento.
\n"],"type":[0,"String"]}],[0,{"name":[0,"text"],"description":[0,"descripción del elemento..
\n"],"type":[0,"String"]}],[0,{"name":[0,"display"],"description":[0,"ya sea LABEL o FALLBACK.
\n"],"type":[0,"Constant"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n background('pink');\n\n // Describe the first element\n // and draw it.\n describeElement('Circle', 'A yellow circle in the top-left corner.');\n noStroke();\n fill('yellow');\n circle(25, 25, 40);\n\n // Describe the second element\n // and draw it.\n describeElement('Heart', 'A red heart in the bottom-right corner.');\n fill('red');\n circle(66.6, 66.6, 20);\n circle(83.2, 66.6, 20);\n triangle(91.2, 72.6, 75, 95, 58.6, 72.6);\n\n // Add a general description of the canvas.\n describe('A red heart and yellow circle over a pink background.');\n}\n
\n\nfunction setup() {\n background('pink');\n\n // Describe the first element\n // and draw it. Display the\n // description for debugging.\n describeElement('Circle', 'A yellow circle in the top-left corner.', LABEL);\n noStroke();\n fill('yellow');\n circle(25, 25, 40);\n\n // Describe the second element\n // and draw it. Display the\n // description for debugging.\n describeElement('Heart', 'A red heart in the bottom-right corner.', LABEL);\n fill('red');\n circle(66.6, 66.6, 20);\n circle(83.2, 66.6, 20);\n triangle(91.2, 72.6, 75, 95, 58.6, 72.6);\n\n // Add a general description of the canvas.\n describe('A red heart and yellow circle over a pink background.');\n}\n
\ndisplayDensity()
devuelve la densidad de píxeles actual de la pantalla.
En el ejemplo, se puede ver como pixelDensity(1)
se ha usado para que la densidad de píxeles del boceto (sketch) no coincida con la densidad de píxeles de la pantalla del usuario (revisa pixelDensity() para entender mejor que es la densidad de píxeles).
Cuando se da clic en el boceto, se puede ver un cambio en la resolución de la imagen. Esto indica que displayDensity()
reconoce la densidad de pixeles de la pantalla del usuario.
\nfunction setup() {\n // Set the pixel density to 1.\n pixelDensity(1);\n\n // Create a canvas and draw\n // a circle.\n createCanvas(100, 100);\n background(200);\n circle(50, 50, 70);\n\n describe('A fuzzy white circle drawn on a gray background. The circle becomes sharper when the mouse is pressed.');\n}\n\nfunction mousePressed() {\n // Get the current display density.\n let d = displayDensity();\n\n // Use the display density to set\n // the sketch's pixel density.\n pixelDensity(d);\n\n // Paint the background and\n // draw a circle.\n background(200);\n circle(50, 50, 70);\n}\n
\nLa variable displayHeight
almacena la altura de la pantalla. Es particularmente útil para ejecutar programas en modo de pantalla completa.
Su valor depende del valor actual de pixelDensity().
Nota: la altura de la pantalla actual se puede calcular de la siguiente manera: displayHeight * pixelDensity()
.
\nfunction setup() {\n // Set the canvas' width and height\n // using the display's dimensions.\n createCanvas(displayWidth, displayHeight);\n\n background(200);\n\n describe('A gray canvas that is the same size as the display.');\n}\n
\nLa variable displayWidth
almacena el ancho de la pantalla. Es particularmente útil para ejecutar programas en modo de pantalla completa.
Su valor depende del valor actual de pixelDensity().
Nota: el ancho de la pantalla actual se puede calcular de la siguiente manera: displayWidth * pixelDensity()
.
\nfunction setup() {\n // Set the canvas' width and height\n // using the display's dimensions.\n createCanvas(displayWidth, displayHeight);\n\n background(200);\n\n describe('A gray canvas that is the same size as the display.');\n}\n
\nLa variable booleana focused
indica si la ventana de un programa de p5.js está activa, lo que permite que el boceto (sketch) reciba información, como interacciones con el teclado o el ratón.
Cuando la ventana está activa, es decir, cuando el usuario está interactuando con ella, la variable focused
es verdadera (true); de lo contrario, es falsa (false).
\n// Open this example in two separate browser\n// windows placed side-by-side to demonstrate.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A square changes color from green to red when the browser window is out of focus.');\n}\n\nfunction draw() {\n // Change the background color\n // when the browser window\n // goes in/out of focus.\n if (focused === true) {\n background(0, 255, 0);\n } else {\n background(255, 0, 0);\n }\n}\n
\nLa variable frameCount
rastrea el número de fotogramas (frames) que se han mostrado desde que el programa comenzó a ejecutarse.
Dentro de la función setup(), el valor de frameCount
comienza en 0. Luego, cada vez que el código dentro de la función draw() se ejecuta por completo, frameCount
incrementa en 1.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Display the value of\n // frameCount.\n textSize(30);\n textAlign(CENTER, CENTER);\n text(frameCount, 50, 50);\n\n describe('The number 0 written in black in the middle of a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Set the frameRate to 30.\n frameRate(30);\n\n textSize(30);\n textAlign(CENTER, CENTER);\n\n describe('A number written in black in the middle of a gray square. Its value increases rapidly.');\n}\n\nfunction draw() {\n background(200);\n\n // Display the value of\n // frameCount.\n text(frameCount, 50, 50);\n}\n
\nEstablece el número de cuadros a dibujar por segundo.
Si se pasa un argumento numérico a la función frameRate()
, por ejemplo: frameRate(30)
, esta intentará dibujar 30 cuadros por segundo, o 30 FPS (Frames Per Second en inglés). Se dice ‘intentará’ porque el número de cuadros que se pueden dibujar por segundo (velocidad) depende de las necesidades de procesamiento del boceto (sketch). La mayoría de computadores tiene una velocidad de cuadros predeterminada de 60FPS. Velocidades de cuadro de 24 FPS en adelante son suficientemente rápidas para animaciones fluidas.
Llamar a frameRate()
sin argumentos devuelve la velocidad de cuadros actual, aunque este valor puede ser una aproximación.
número de cuadros a dibujar por segundo.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle on a gray background. The circle moves from left to right in a loop. It slows down when the mouse is pressed.');\n}\n\nfunction draw() {\n background(200);\n\n // Set the x variable based\n // on the current frameCount.\n let x = frameCount % 100;\n\n // If the mouse is pressed,\n // decrease the frame rate.\n if (mouseIsPressed === true) {\n frameRate(10);\n } else {\n frameRate(60);\n }\n\n // Use x to set the circle's\n // position.\n circle(x, 50, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A number written in black on a gray background. The number decreases when the mouse is pressed.');\n}\n\nfunction draw() {\n background(200);\n\n // If the mouse is pressed, do lots\n // of math to slow down drawing.\n if (mouseIsPressed === true) {\n for (let i = 0; i < 1000000; i += 1) {\n random();\n }\n }\n\n // Get the current frame rate\n // and display it.\n let fps = frameRate();\n text(fps, 50, 50);\n}\n
\nfullscreen()
acepta un parámetro de carácter Booleano, es decir, ‘true’(verdadero) o ‘false’ (falso); y es capaz de activar el modo de pantalla completa o devolver el estado actual de la pantalla
Si se pasa true
como argumento, por ejemplo: fullscreen(true)
, el boceto (sketch) se mostrará en modo de pantalla completa.
Si se pasa false
como argumento, por ejemplo: fullscreen(false)
, el boceto (sketch) se mostrará en su tamaño original.
Cuando se llama fullscreen()
sin ningún argumento, devolverá true
si el boceto (sketch) esta en modo de pantalla completa, y false
si no lo está.
Nota: Debido a restricciones del navegador, fullscreen()
solo puede se llamado con una entrada del usuario, como presionar el ratón.
ya sea si el boceto debe estar en modo de pantalla completa, o no.
"],"type":[0,"Boolean"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"estado actual de pantalla (tamaño original, o modo de pantalla completa)."],"type":[0,"Boolean"]}],"example":[1,[[0,"\n\nfunction setup() {\n background(200);\n\n describe('A gray canvas that switches between default and full-screen display when clicked.');\n}\n\n// If the mouse is pressed,\n// toggle full-screen mode.\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n let fs = fullscreen();\n fullscreen(!fs);\n }\n}\n
\n getTargetFrameRate()
devuelve la velocidad de cuadros con la que se está dibujando el boceto (sketch).
Este valor puede ser la velocidad de cuadros predeterminada del sistema (60 FPS) o el último valor que se pasó a la función frameRate().
\n"],"line":[0,447],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"_targetFrameRate"],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('The number 20 written in black on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Set the frame rate to 20.\n frameRate(20);\n\n // Get the target frame rate and\n // display it.\n let fps = getTargetFrameRate();\n text(fps, 43, 54);\n}\n
\nDevuelve la URL o enlace del boceto (sketch) como una ‘cadena de caracteres’, también conocida en inglés como String
\nfunction setup() {\n background(200);\n\n // Get the sketch's URL\n // and display it.\n let url = getURL();\n textWrap(CHAR);\n text(url, 0, 40, 100);\n\n describe('The URL \"https://p5js.org/reference/p5/getURL\" written in black on a gray background.');\n}\n
\nDevuelve los parámetros de la URL como un objeto.
\nPor ejemplo, si llamamos a getURLParams()
en un boceto (sketch) alojado en la URL http:\"//p5js.org?year=2014&month=May&day=15
, obtendremos el siguiente objeto{ year: 2014, month: 'May', day: 15 }
\n// Imagine this sketch is hosted at the following URL:\n// https://p5js.org?year=2014&month=May&day=15\n\nfunction setup() {\n background(200);\n\n // Get the sketch's URL\n // parameters and display\n // them.\n let params = getURLParams();\n text(params.day, 10, 20);\n text(params.month, 10, 40);\n text(params.year, 10, 60);\n\n describe('The text \"15\", \"May\", and \"2014\" written in black on separate lines.');\n}\n
\nDevuelve la ruta de URL del boceto (sketch) como un arreglo de cadenas.
\nPor ejemplo, considera un boceto alojado en la URL https:\"//example.com/sketchbook
. Si llamamos a getURLPath()
obtendremos ['sketchbook']
.
En otro ejemplo, para un boceto alojado en la URL https:\"//example.com/sketchbook/monday
, al llamar a getURLPath()
, obtendremos ['sketchbook', 'monday']
.
\nfunction setup() {\n background(200);\n\n // Get the sketch's URL path\n // and display the first\n // part.\n let path = getURLPath();\n text(path[0], 25, 54);\n\n describe('The word \"reference\" written in black on a gray background.');\n}\n
\ngridOutput()
genera una descripción de las formas presentes en el lienzo, la cual es accesible para lectores de pantalla, y otras tecnologías de asistencia
gridOutput()
añade una descripción general del lienzo, una lista de formas, y una tabla de formas a la página web. La descripción general incluye el tamaño del lienzo, el color del lienzo y el número de formas en el lienzo. Por ejemplo: Your output is a, 100 by 100 pixels, gray canvas containing the following 2 shapes:
La descripción es seguida por una lista de formas. gridOutput
establece el contenido del lienzo a través de una cuadrícula (tabla de html) que se basa en la posición espacial de cada forma. Cada forma se ubica en la celda correspondiente (fila y columna) según su posición en el lienzo. El lector de pantalla leerá las celdas de la cuadrícula y describirá el color y la forma que se encuentra en cada posición. Esto es diferente de textOutput() , que usa una lista para describir el contenido del lienzo.
Finalmente, gridOutput
provee una lista de formas. Esta lista describe el color, la forma, la posición y el área de cada forma . Por ejemplo: red circle location = middle area = 3%
.
El parámetro display
es opcional. Este parámetro determina de qué manera se va a mostrar la descripción. Si LABEL
se pasa como argumento, por ejemplo: gridOutput(LABEL)
, la descripción será visible en un elemento ‘div’ al lado del lienzo. Sin embargo, el uso de LABEL
crea mensajes duplicados que son ineficientes para los usuarios de lectores de pantalla, por lo que recomendamos utilizar únicamente LABEL
durante la fase de desarrollo. Por otro lado, si FALLBACK
se pasa como argumento, por ejemplo: gridOutput(FALLBACK)
, la descripción será visible solo para los lectores de pantalla. Este es el modo predeterminado.
Lee ‘Escribiendo descripciones accesibles para lienzos’ para aprender más sobre cómo hacer que tus ‘sketches’ sean accesibles.
\n"],"line":[0,144],"params":[1,[[0,{"name":[0,"display"],"description":[0,"ya sea FALLBACK o LABEL.
\n"],"type":[0,"Constant"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n // Add the grid description.\n gridOutput();\n\n // Draw a couple of shapes.\n background(200);\n fill(255, 0, 0);\n circle(20, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle and a blue square on a gray background.');\n}\n
\n\nfunction setup() {\n // Add the grid description and\n // display it for debugging.\n gridOutput(LABEL);\n\n // Draw a couple of shapes.\n background(200);\n fill(255, 0, 0);\n circle(20, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle and a blue square on a gray background.');\n}\n
\n\nfunction draw() {\n // Add the grid description.\n gridOutput();\n\n // Draw a moving circle.\n background(200);\n let x = frameCount * 0.1;\n fill(255, 0, 0);\n circle(x, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle moves from left to right above a blue square.');\n}\n
\n\nfunction draw() {\n // Add the grid description and\n // display it for debugging.\n gridOutput(LABEL);\n\n // Draw a moving circle.\n background(200);\n let x = frameCount * 0.1;\n fill(255, 0, 0);\n circle(x, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle moves from left to right above a blue square.');\n}\n
\nLa variable height
almacena la altura del lienzo en píxeles.
Por defecto, height
tiene un valor de 100, el cual puede ser modificado mediante la llamada a createCanvas() o resizeCanvas(). Por ejemplo: createCanvas(100, 50) define el valor de height
como 50.
Al llamar noCanvas() se definirá el valor de height
como 0.
\nfunction setup() {\n background(200);\n\n // Display the canvas' height.\n text(height, 42, 54);\n\n describe('The number 100 written in black on a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 50);\n\n background(200);\n\n // Display the canvas' height.\n text(height, 42, 27);\n\n describe('The number 50 written in black on a gray rectangle.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Display the canvas' height.\n text(height, 42, 54);\n\n describe('The number 100 written in black on a gray square. When the mouse is pressed, the square becomes a rectangle and the number becomes 50.');\n}\n\n// If the mouse is pressed, reisze\n// the canvas and display its new\n// height.\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n resizeCanvas(100, 50);\n background(200);\n text(height, 42, 27);\n }\n}\n
\n noCursor()
oculta el cursor. En el ejemplo se puede observar cómo el cursor desaparece cuando este se desplaza sobre el lienzo. Este es reemplazado por un círculo con el propósito de visualizar el efecto de noCursor()
.
Si se elimina por completo la línea circle(mouseX, mouseY, 10)
en el ejemplo, podrás observar cómo el cursor desaparece al entrar al lienzo.
\nfunction setup() {\n // Hide the cursor.\n noCursor();\n}\n\nfunction draw() {\n background(200);\n\n circle(mouseX, mouseY, 10);\n\n describe('A white circle on a gray background. The circle follows the mouse as it moves. The cursor is hidden.');\n}\n
\npixelDensity()
define la densidad de los píxeles, o devuelve la densidad actual de píxeles.
Las pantallas de computadora son matrices de pequeñas luces llamadas píxeles. La densidad de píxeles (pixel density) de una pantalla describe cuántos píxeles se encuentran en un área determinada. Las pantallas con píxeles más pequeños tienen una densidad de píxeles más alta y crean imágenes más nítidas.
\npixelDensity()
establece la escala de píxeles para pantallas de alta densidad de píxeles. De forma predeterminada, la densidad de píxeles del boceto (sketch) se ajusta para que coincida con la densidad de píxeles de la pantalla del usuario. Llamar a pixelDensity(1)
desactiva esta función.
Llamar a pixelDensity()
sin argumentos devuelve la densidad de píxeles actual.
densidad de píxeles deseada.
"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n // Set the pixel density to 1.\n pixelDensity(1);\n\n // Create a canvas and draw\n // a circle.\n createCanvas(100, 100);\n background(200);\n circle(50, 50, 70);\n\n describe('A fuzzy white circle on a gray canvas.');\n}\n
\n\nfunction setup() {\n // Set the pixel density to 3.\n pixelDensity(3);\n\n // Create a canvas, paint the\n // background, and draw a\n // circle.\n createCanvas(100, 100);\n background(200);\n circle(50, 50, 70);\n\n describe('A sharp white circle on a gray canvas.');\n}\n
\n La función print()
muestra texto en la consola del navegador web.
Esta función es útil para imprimir valores durante la depuración de código. Cada llamada a print()
crea una nueva línea de texto.
Nota: \"para imprimir una línea vacía en la consola utiliza print('\\n')
. Si llamas print()
sin un argumento, esto abre el cuadro de diálogo del navegador que se utiliza para imprimir documentos.
contenido para imprimir en la consola.
"],"type":[0,"Any"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n // Prints \"hello, world\" to the console.\n print('hello, world');\n}\n
\n\nfunction setup() {\n let name = 'ada';\n // Prints \"hello, ada\" to the console.\n print(`hello, ${name}`);\n}\n
\ntextOutput()
genera una descripción de las formas presentes en el lienzo, la cual es accesible para lectores de pantalla y otras tecnologías de asistencia.
textOutput()
añade una descripción general del lienzo, una lista de formas, y una tabla de formas a la página web. La descripción general incluye el tamaño del lienzo, el color del lienzo y el número de formas en el lienzo. Por ejemplo: \"Your output is a, 100 by 100 pixels, gray canvas containing the following 2 shapes:
La descripción es seguida por una lista de formas. La lista describe el color, la forma, la posición y el área de cada forma presente en el lienzo. Por ejemplo: a red circle at middle covering 3% of the canvas
. Cada forma puede ser seleccionada para obtener más detalles.
Finalmente, textOutput()
provee una tabla de formas. Esta tabla describe el color, la forma, la posición y el área de cada forma . Por ejemplo: red circle location = middle area = 3%
. Esto es diferente de gridOutput(), que provee una tabla como cuadrícula (tabla de html).
El parámetro display
es opcional. Este parámetro determina de qué manera se va a mostrar la descripción. Si LABEL
se pasa como argumento, por ejemplo: \"textOutput(LABEL)
, la descripción será visible en un elemento ‘div’ al lado del lienzo. Sin embargo, el uso de LABEL
crea mensajes duplicados que son ineficientes para los usuarios de lectores de pantalla, por lo que recomendamos utilizar únicamente LABEL
durante la fase de desarrollo. Por otro lado, si FALLBACK
se pasa como argumento, por ejemplo: textOutput(FALLBACK)
, la descripción será visible solo para los lectores de pantalla. Este es el modo predeterminado.
Lee ‘ Escribiendo descripciones accesibles para lienzos’ para aprender más sobre cómo hacer que tus ‘sketches’ sean accesibles.
"],"line":[0,10],"params":[1,[[0,{"name":[0,"display"],"description":[0,"\nya sea FALLBACK o LABEL.
"],"type":[0,"Constant"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n // Add the text description.\n textOutput();\n\n // Draw a couple of shapes.\n background(200);\n fill(255, 0, 0);\n circle(20, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle and a blue square on a gray background.');\n}\n
\n\nfunction setup() {\n // Add the text description and\n // display it for debugging.\n textOutput(LABEL);\n\n // Draw a couple of shapes.\n background(200);\n fill(255, 0, 0);\n circle(20, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle and a blue square on a gray background.');\n}\n
\n\nfunction draw() {\n // Add the text description.\n textOutput();\n\n // Draw a moving circle.\n background(200);\n let x = frameCount * 0.1;\n fill(255, 0, 0);\n circle(x, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle moves from left to right above a blue square.');\n}\n
\n\nfunction draw() {\n // Add the text description and\n // display it for debugging.\n textOutput(LABEL);\n\n // Draw a moving circle.\n background(200);\n let x = frameCount * 0.1;\n fill(255, 0, 0);\n circle(x, 20, 20);\n fill(0, 0, 255);\n square(50, 50, 50);\n\n // Add a general description of the canvas.\n describe('A red circle moves from left to right above a blue square.');\n}\n
\nLa variable webglVersion
devuelve la versión de WebGL que está en uso.
El valor que webglVersion
devuelve es igual a una las siguientes cadenas de caracteres constantes:
WEBGL2
cuyo valor es 'webgl2'
,WEBGL
cuyo valor es 'webgl'
, oP2D
cuyo valor es 'p2d'
. Este es el valor predeterminado\"\npara bocetos (sketches) 2D.Consulta setAttributes() para conocer formas de configurar la\nversión de WebGL.
"],"line":[0,508],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n background(200);\n\n // Display the current WebGL version.\n text(webglVersion, 42, 54);\n\n describe('The text \"p2d\" written in black on a gray background.');\n}\n
\n\nlet font;\n\nfunction preload() {\n // Load a font to use.\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n // Create a canvas using WEBGL mode.\n createCanvas(100, 50, WEBGL);\n background(200);\n\n // Display the current WebGL version.\n fill(0);\n textFont(font);\n text(webglVersion, -15, 5);\n\n describe('The text \"webgl2\" written in black on a gray background.');\n}\n
\n\nlet font;\n\nfunction preload() {\n // Load a font to use.\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n // Create a canvas using WEBGL mode.\n createCanvas(100, 50, WEBGL);\n\n // Set WebGL to version 1.\n setAttributes({ version: 1 });\n\n background(200);\n\n // Display the current WebGL version.\n fill(0);\n textFont(font);\n text(webglVersion, -14, 5);\n\n describe('The text \"webgl\" written in black on a gray background.');\n}\n
\nLa variable width
almacena el ancho del lienzo en píxeles.
Por defecto, width
tiene un valor de 100, el cual puede ser modificado mediante la llamada a createCanvas() o resizeCanvas(). Por ejemplo: createCanvas(50, 100) define el valor de width
como 50.
Al llamar noCanvas() se definirá el valor de width
como 0.
\nfunction setup() {\n background(200);\n\n // Display the canvas' width.\n text(width, 42, 54);\n\n describe('The number 100 written in black on a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(50, 100);\n\n background(200);\n\n // Display the canvas' width.\n text(width, 21, 54);\n\n describe('The number 50 written in black on a gray rectangle.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Display the canvas' width.\n text(width, 42, 54);\n\n describe('The number 100 written in black on a gray square. When the mouse is pressed, the square becomes a rectangle and the number becomes 50.');\n}\n\n// If the mouse is pressed, reisze\n// the canvas and display its new\n// width.\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n resizeCanvas(50, 100);\n background(200);\n text(width, 21, 54);\n }\n}\n
\nLa variable windowHeight
almacena la altura de la ventana del navegador.
Por otro lado, la ventana gráfica de diseño (conocida como layout viewport) es el espacio dentro del navegador que está disponible para dibujar.
"],"line":[0,680],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n // Set the canvas' width and height\n // using the browser's dimensions.\n createCanvas(windowWidth, windowHeight);\n\n background(200);\n\n describe('A gray canvas that takes up the entire browser window.');\n}\n
\nLa función windowResized()
es llamada cuando la ventana del navegador cambia de tamaño.
El código que se escriba dentro de windowResized()
se ejecutará automáticamente en respuesta a este cambio de tamaño. Es un lugar adecuado para invocar resizeCanvas() u realizar otros ajustes necesarios para que el contenido del lienzo se adapte al nuevo tamaño de la ventana.
El parámetro evento
es opcional. Si se incluye en la declaración de la función windowResized()
, puede ser útil para la depuración del código.
Evento de cambio de tamaño opcional.
"],"type":[0,"UIEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(windowWidth, windowHeight);\n\n describe('A gray canvas with a white circle at its center. The canvas takes up the entire browser window. It changes size to match the browser window.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw a circle at the center.\n circle(width / 2, height / 2, 50);\n}\n\n// Resize the canvas when the\n// browser's size changes.\nfunction windowResized() {\n resizeCanvas(windowWidth, windowHeight);\n}\n
\nLa variable windowWidth
almacena el ancho de la ventana del navegador.
Por otro lado, la ventana gráfica de diseño (conocida como layout viewport) es el espacio dentro del navegador que está disponible para dibujar.\"
"],"line":[0,652],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n // Set the canvas' width and height\n // using the browser's dimensions.\n createCanvas(windowWidth, windowHeight);\n\n background(200);\n\n describe('A gray canvas that takes up the entire browser window.');\n}\n
\ncamera()
establece la posición y orientación de la cámara actual en un dibujo 3D.
camera()
permite ver objetos desde diferentes ángulos. Tiene nueve parámetros, todos opcionales.
Los tres primeros parámetros, x
, y
y z
son las coordenadas de la posición de la cámara. Por ejemplo, llamar a camera(0, 0, 0)
coloca la cámara en el origen (0, 0, 0)
. De forma predeterminada, la cámara se encuentra en (0, 0, 800)
.
Los siguientes tres parámetros, centerX
, centerY
y centerZ
son las coordenadas del punto hacia donde se dirige la cámara. Por ejemplo, llamar a camera(0, 0, 0, 10, 20, 30)
coloca la cámara en el origen (0, 0, 0)
y la hace apuntar a (10, 20, 30)
. De forma predeterminada, la cámara se dirige al origen (0, 0, 0)
.
Los tres últimos parámetros, upX
, upY
y upZ
son los componentes del vector \"arriba\". El vector \"arriba\" orienta el eje y de la cámara. Por ejemplo, llamar a camera(0, 0, 0, 10, 20, 30, 0, -1, 0)
coloca la cámara en el origen (0, 0, 0)
, la hace apuntar a (10, 20, 30)
y establece el vector \"arriba\" en (0, -1, 0)
lo que es como si la cámara estuviera volada hacia arriba. De forma predeterminada, el vector \"arriba\" es (0, 1, 0)
.
Nota: camera()
solo puede ser usado en el modo WebGL.
Coordenada x de la cámara. Por defecto, 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"y"],"description":[0,"Coordenada y de la cámara. Por defecto, 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"z"],"description":[0,"Coordenada z de la cámara. Por defecto, 800.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"centerX"],"description":[0,"Coordenada x del punto al que se dirige la cámara. Por defecto, 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"centerY"],"description":[0,"Coordenada y del punto al que se dirige la cámara. Por defecto, 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"centerZ"],"description":[0,"Coordenada z del punto al que se dirige la cámara. Por defecto, 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"upX"],"description":[0,"Componente x del vector \"arriba\" de la cámara. Por defecto, 0.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"upY"],"description":[0,"Componente y del vector \"arriba\" de la cámara. Por defecto, 1.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"upZ"],"description":[0,"Componente z del vector \"arriba\" de la cámara. Por defecto, 0.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Move the camera to the top-right.\n camera(200, -400, 800);\n\n // Draw the box.\n box();\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube apperas to sway left and right on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the camera's x-coordinate.\n let x = 400 * cos(frameCount * 0.01);\n\n // Orbit the camera around the box.\n camera(x, -400, 800);\n\n // Draw the box.\n box();\n}\n
\n\n// Adjust the range sliders to change the camera's position.\n\nlet xSlider;\nlet ySlider;\nlet zSlider;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create slider objects to set the camera's coordinates.\n xSlider = createSlider(-400, 400, 400);\n xSlider.position(0, 100);\n xSlider.size(100);\n ySlider = createSlider(-400, 400, -200);\n ySlider.position(0, 120);\n ySlider.size(100);\n zSlider = createSlider(0, 1600, 800);\n zSlider.position(0, 140);\n zSlider.size(100);\n\n describe(\n 'A white cube drawn against a gray background. Three range sliders appear beneath the image. The camera position changes when the user moves the sliders.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Get the camera's coordinates from the sliders.\n let x = xSlider.value();\n let y = ySlider.value();\n let z = zSlider.value();\n\n // Move the camera.\n camera(x, y, z);\n\n // Draw the box.\n box();\n}\n
\nCrea un nuevo objeto p5.Camera y lo establece como la cámara actual (activa).
\nLa nueva cámara se inicializa con una posición por defecto (0, 0, 800)
y una proyección perspectiva por defecto. Sus propiedades pueden ser controladas mediante métodos de la clase p5.Camera, como myCamera.lookAt(0, 0, 0)
.
Nota: Cada dibujo 3D comienza con una cámara por defecto inicializada. Esta cámara puede ser controlada con las funciones camera(), perspective(), ortho() y frustum() si es la única cámara en la escena.
\nNota: createCamera()
solo puede ser usado en modo WebGL.
\n// Double-click to toggle between cameras.\n\nlet cam1;\nlet cam2;\nlet usingCam1 = true;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the first camera.\n // Keep its default settings.\n cam1 = createCamera();\n\n // Create the second camera.\n // Place it at the top-left.\n // Point it at the origin.\n cam2 = createCamera();\n cam2.setPosition(400, -400, 800);\n cam2.lookAt(0, 0, 0);\n\n // Set the current camera to cam1.\n setCamera(cam1);\n\n describe('A white cube on a gray background. The camera toggles between frontal and aerial views when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw the box.\n box();\n}\n\n// Toggle the current camera when the user double-clicks.\nfunction doubleClicked() {\n if (usingCam1 === true) {\n setCamera(cam2);\n usingCam1 = false;\n } else {\n setCamera(cam1);\n usingCam1 = true;\n }\n}\n
\nfrustum()
cambia la perspectiva por defecto de la cámara actual en un boceto 3D.
En una proyección de frustum, las formas que están más lejanas de la cámara aparecen más pequeñas que las formas que están cercanas a la cámara. Esta técnica, llamada foreshortening(escorzo), crea escenas 3D realistas.
\nfrustum()
cambia la perspectiva de la cámara cambiando su frustum de vista. El frustum es el volumen de espacio que es visible para la cámara. La forma del frustum es una pirámide con su parte superior cortada. La cámara está en la parte superior de la pirámide y mira hacia la base de la pirámide. Vista la región visible dentro del frustum.
Los primeros cuatro parámetros, left
, right
, bottom
y top
, establecen las coordenadas de los lados, parte inferior y superior del frustum. Por ejemplo, llamar a frustum(-100, 100, 200, -200)
crea un frustum que mide 200 píxeles de ancho y 400 píxeles de alto. Por defecto, estos parámetros están establecidos basados en el ancho y alto del boceto, como en\northo(-ancho / 20, ancho / 20, alto / 20, -alto / 20)
.
Los dos últimos parámetros, near
y far
, establecen la distancia del plano cercano y lejano del frustum respectivamente desde la cámara. Por ejemplo, llamar a ortho(-100, 100, 200, -200, 50, 1000)
crea un frustum que mide 200 píxeles de ancho y alto, empieza a 50 píxeles de la cámara y termina a 1000 píxeles de la cámara. Por defecto, near
está establecido en 0.1 * 800
, que es 1/10th la distancia por defecto entre la cámara y el origen. far
está establecido en 10 * 800
, que es 10 veces la distancia por defecto entre la cámara y el origen.
Nota: frustum()
solo puede ser usado en modo WebGL.
Coordenada x del plano izquierdo del frustum. Por defecto es -width / 20
.
Coordenada x del plano derecho del frustum. Por defecto es width / 20
.
Coordenada y del plano inferior del frustum. Por defecto es height / 20
.
Coordenada y del plano superior del frustum. Por defecto es -height / 20
.
Coordenada z del plano cercano del frustum. Por defecto es 0.1 * 800
.
Coordenada z del plano lejano del frustum. Por defecto es 10 * 800
.
\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A row of white cubes on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Apply the default frustum projection.\n frustum();\n\n // Translate the origin toward the camera.\n translate(-10, 10, 600);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n translate(0, 0, -40);\n box(10);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Adjust the frustum.\n // Center it.\n // Set its width and height to 20 pixels.\n // Place its near plane 300 pixels from the camera.\n // Place its far plane 350 pixels from the camera.\n frustum(-10, 10, -10, 10, 300, 350);\n\n // Translate the origin toward the camera.\n translate(-10, 10, 600);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n translate(0, 0, -40);\n box(10);\n }\n}\n
\nHabilita o deshabilita la perspectiva de las líneas en bocetos 3D.
\nEn el modo WebGL, las líneas pueden ser dibujadas con un grosor más delgado cuando están\nmás lejanas de la cámara. Esto da una apariencia más realista.
\nDe forma predeterminada, las líneas son dibujadas de formas diferentes dependiendo del tipo de\nperspectiva que se está utilizando:
\nperspective()
y frustum()
simulan una perspectiva realista. En\nestos modos, el grosor de las líneas se ve afectado por su distancia a la\ncámara. Esto da una apariencia más natural. perspective()
es\nel modo predeterminado para los bocetos 3D.ortho()
no simula una perspectiva realista. En este modo, el grosor de las líneas es consistente independientemente de su distancia a la\ncámara. Esto da una apariencia más predecible y consistente.linePerspective()
puede sobreescribir el modo por defecto de dibujado de líneas.
El parámetro enable
es opcional. Es un valor Boolean
que establece el\nmodo en que se dibujan las líneas. Si se pasa true
como en linePerspective(true)
,\nlas líneas aparecerán más delgadas cuando estén más lejanas de la cámara. Si\nse pasa false
como en linePerspective(false)
, las líneas tendrán\nun grosor de trazo constante independientemente de su distancia a la cámara. De forma predeterminada, linePerspective()
está habilitado.
Al llamar a linePerspective()
sin pasar un argumento devuelve true
si\nestá habilitado y false
si no lo está.
Nota: linePerspective()
solo puede ser utilizado en el modo WebGL.
Si se debe habilitar la perspectiva de líneas.
\n"],"type":[0,"Booleano"]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Double-click the canvas to toggle the line perspective.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'A white cube with black edges on a gray background. Its edges toggle between thick and thin when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin toward the camera.\n translate(-10, 10, 600);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n translate(0, 0, -40);\n box(10);\n }\n}\n\n// Toggle the line perspective when the user double-clicks.\nfunction doubleClicked() {\n let isEnabled = linePerspective();\n linePerspective(!isEnabled);\n}\n
\n\n// Double-click the canvas to toggle the line perspective.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'A row of cubes with black edges on a gray background. Their edges toggle between thick and thin when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Use an orthographic projection.\n ortho();\n\n // Translate the origin toward the camera.\n translate(-10, 10, 600);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n translate(0, 0, -40);\n box(10);\n }\n}\n\n// Toggle the line perspective when the user double-clicks.\nfunction doubleClicked() {\n let isEnabled = linePerspective();\n linePerspective(!isEnabled);\n}\n
\northo()
establece una proyección ortográfica para la cámara actual en un\nboceto 3D. En una proyección ortográfica, las formas con el mismo tamaño siempre\naparecen con el mismo tamaño, independientemente de si están cerca o lejanas\nrespecto a la cámara.
ortho()
cambia la perspectiva de la cámara al cambiar su frustum de vision\nde un pirámide truncada a un prisma rectangular. La cámara se coloca delante del\nfrustum y muestra todo lo que hay entre el plano cercano del frustum y su plano\nlejano. ortho()
tiene seis parámetros opcionales para definir el\nfrustum.
Los primeros cuatro parámetros, left
, right
, bottom
y top
, establecen las coordenadas de\nlos lados del frustum como son la parte superior e inferior. Por ejemplo, llamar a ortho(-100, 100, 200, -200)
crea un frustum que mide 200 pixeles de ancho y\n400 pixeles de alto. Por defecto, estos parámetros están establecidos\nbasados en el ancho y el alto del boceto, como en\northo(-width / 2, width / 2, -height / 2, height / 2)
.
Los últimos dos parámetros, near
y far
, establecen la distancia del plano cercano del frustum y del plano lejano respectivamente. Por\nejemplo, llamar a ortho(-100, 100, 200, 200, 50, 1000)
crea un frustum que mide 200 pixeles de ancho, 400 pixeles de alto, comienza 50 pixeles desde la cámara y termina 1,000 pixeles desde la cámara. Por defecto, near
y far
están establecidos en 0 y\nmax(width, height) + 800
, respectivamente.
Nota: ortho()
solo puede ser utilizado en modo WebGL.
Coordenada x del plano izquierdo del frustum. Por defecto es -width / 2
.
Coordenada x del plano derecho del frustum. Por defecto es width / 2
.
Coordenada y del plano inferior del frustum. Por defecto es height / 2
.
Coordenada y del plano superior del frustum. Por defecto es -height / 2
.
Coordenada z del plano cercano del frustum. Por defecto es 0.
"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"far"],"description":[0,"Coordenada z del plano lejano del frustum. Por defecto es max(width, height) + 800
.
\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A row of tiny, white cubes on a gray background. All the cubes appear the same size.');\n}\n\nfunction draw() {\n background(200);\n\n // Apply an orthographic projection.\n ortho();\n\n // Translate the origin toward the camera.\n translate(-10, 10, 600);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n translate(0, 0, -40);\n box(10);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white cube on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Apply an orthographic projection.\n // Center the frustum.\n // Set its width and height to 20.\n // Place its near plane 300 pixels from the camera.\n // Place its far plane 350 pixels from the camera.\n ortho(-10, 10, -10, 10, 300, 350);\n\n // Translate the origin toward the camera.\n translate(-10, 10, 600);\n\n // Rotate the coordinate system.\n rotateY(-0.1);\n rotateX(-0.1);\n\n // Draw the row of boxes.\n for (let i = 0; i < 6; i += 1) {\n translate(0, 0, -40);\n box(10);\n }\n}\n
\nUna clase para describir una cámara para ver un boceto 3D.
\nCada objeto p5.Camera
representa una cámara que ve una sección de espacio 3D. Almacena información sobre la posición, orientación y proyección de la cámara.
En el modo WebGL, la cámara predeterminada es un objeto p5.Camera
que puede ser controlada con las funciones camera(),\nperspective(),\northo() y\nfrustum(). Se pueden crear cámaras adicionales con createCamera() y activarlas con setCamera().
Nota: Las funciones de p5.Camera
operan en dos sistemas de coordenadas:
myCamera.setPosition()
coloca la cámara en el espacio 3D utilizando\ncoordenadas “mundo”.Establece una proyección perspectiva para la cámara actual en un sketch (boceto) 3D.
\nEn una proyección perspectiva, las formas que están más lejos de la cámara\naparecen más pequeñas que las que están cerca de la cámara. Esta técnica,\nllamada perspectiva, crea escenas 3D realistas. Se aplica por defecto en\nmodo WebGL.
\nperspective()
cambia la perspectiva de la cámara al cambiar su campo de visión. El campo de visión de la cámara es un volumen de espacio que\nestá visible desde la cámara. Su forma es una pirámide con su parte superior\ncortada. La cámara está donde debería estar la parte superior de la pirámide y\nmira hacia todo lo que hay entre la parte superior (plano cercano) y la\nparte inferior (plano lejano) del volumen.
El primer parámetro, fovy
, es el campo de visión vertical de la cámara. Es un ángulo que describe la altura o ancho de la visión que la\ncámara tiene. Por ejemplo, llamar a perspective(0.5)
establece el campo de visión vertical de la cámara a 0.5 radianes. Por defecto,\nfovy
se calcula basado en la altura del boceto y la distancia predeterminada de la cámara al origen, que es 800. La fórmula para el fovy
predeterminado es 2 * atan(altura / 2 / 800)
.
El segundo parámetro, aspect
, es la relación de aspecto de la cámara. Es un número que describe la relación entre el ancho del plano superior\ny su altura. Por ejemplo, llamar a perspective(0.5, 1.5)
establece el campo de visión de la cámara a 0.5 radianes y su relación de aspecto a 1.5, lo\nque haría que las formas aparezcan más estrechas en un lienzo cuadrado. Por\ndefecto, aspecto está establecido a ancho / altura
.
El tercer parámetro, near
, es la distancia desde la cámara al plano cercano. Por ejemplo, llamar a perspective(0.5, 1.5, 100)
establece el campo de visión de la cámara a 0.5 radianes, su relación de aspecto a 1.5, y coloca el plano cercano a 100 pixeles de la cámara. Cualquier forma\ndibujada a menos de 100 pixeles de la cámara no será visible. Por defecto,\nnear está establecido a 0.1 * 800
, lo que es un 1/10 de la distancia predeterminada entre la cámara y el origen.
El cuarto parámetro, far
, es la distancia desde la cámara al plano lejano. Por ejemplo, llamar a perspective(0.5, 1.5, 100, 10000)
establece el campo de visión de la cámara a 0.5 radianes, su relación de aspecto a 1.5, coloca el plano cercano a 100 pixeles de la cámara y el plano lejano a 10000 pixeles de la cámara. Cualquier forma dibujada más\nde 10000 pixeles de la cámara no será visible. Por defecto, far está establecido a 10 * 800
, lo que es 10 veces la distancia predeterminada entre la cámara y el origen.
Nota: perspective()
solo puede ser usado en el modo WebGL.
Campo de visión vertical del cono de visión de la cámara. Toma como\nvalor por defecto 2 * atan(height / 2 / 800)
.
Relación de aspecto del cono de visión de la cámara. Toma como valor\npor defecto width / height
.
Distancia desde la cámara al plano de recorte cercano. Toma como valor\npor defecto 0.1 * 800
.
Distancia desde la cámara al plano de recorte lejano. Toma como valor\npor defecto 10 * 800
.
\n// Double-click to squeeze the box.\n\nlet isSqueezed = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white rectangular prism on a gray background. The box appears to become thinner when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Place the camera at the top-right.\n camera(400, -400, 800);\n\n if (isSqueezed === true) {\n // Set fovy to 0.2.\n // Set aspect to 1.5.\n perspective(0.2, 1.5);\n }\n\n // Draw the box.\n box();\n}\n\n// Change the camera's perspective when the user double-clicks.\nfunction doubleClicked() {\n isSqueezed = true;\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white rectangular prism on a gray background. The prism moves away from the camera until it disappears.');\n}\n\nfunction draw() {\n background(200);\n\n // Place the camera at the top-right.\n camera(400, -400, 800);\n\n // Set fovy to 0.2.\n // Set aspect to 1.5.\n // Set near to 600.\n // Set far to 1200.\n perspective(0.2, 1.5, 600, 1200);\n\n // Move the origin away from the camera.\n let x = -frameCount;\n let y = frameCount;\n let z = -2 * frameCount;\n translate(x, y, z);\n\n // Draw the box.\n box();\n}\n
\nEstablece la cámara actual (activa) de un boceto 3D.
\nsetCamera()
permite cambiar entre múltiples cámaras creadas con\ncreateCamera().
Nota: setCamera()
solo puede ser usado en el modo WebGL.
La cámara que debe ser activada.
\n"],"type":[0,"p5.Camera"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Double-click to toggle between cameras.\n\nlet cam1;\nlet cam2;\nlet usingCam1 = true;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the first camera.\n // Keep its default settings.\n cam1 = createCamera();\n\n // Create the second camera.\n // Place it at the top-left.\n // Point it at the origin.\n cam2 = createCamera();\n cam2.setPosition(400, -400, 800);\n cam2.lookAt(0, 0, 0);\n\n // Set the current camera to cam1.\n setCamera(cam1);\n\n describe('A white cube on a gray background. The camera toggles between frontal and aerial views when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw the box.\n box();\n}\n\n// Toggle the current camera when the user double-clicks.\nfunction doubleClicked() {\n if (usingCam1 === true) {\n setCamera(cam2);\n usingCam1 = false;\n } else {\n setCamera(cam1);\n usingCam1 = true;\n }\n}\n
\nAgrega una cuadrícula y un ícono de ejes para aclarar la orientación en bocetos 3D.
\ndebugMode()
agrega una cuadrícula que muestra dónde está el \"suelo\" en un boceto. Por\ndefecto, la cuadrícula pasará por el origen (0, 0, 0)
del boceto\na lo largo del plano XZ. debugMode()
también agrega un ícono de ejes que\napunta a lo largo de los ejes x-, y- y z-positivos. Llamar a debugMode()
muestra la cuadrícula\ny el ícono de ejes con su tamaño y posición predeterminados.
Hay cuatro formas de llamar a debugMode()
con parámetros opcionales para\npersonalizar el entorno de depuración.
La primera forma de llamar a debugMode()
tiene un parámetro, mode
. Si se pasa la\nconstante del sistema GRID
, como en debugMode(GRID)
, entonces se mostrará la cuadrícula y se ocultará el ícono de ejes. Si se pasa la constante AXES
,\ncomo en debugMode(AXES)
, entonces se mostrará el ícono de ejes y se ocultará la cuadrícula.
La segunda forma de llamar a debugMode()
tiene seis parámetros. El primer\nparámetro, mode
, selecciona ya sea GRID
o AXES
para ser mostrado. Los\nsiguientes cinco parámetros, gridSize
, gridDivisions
, xOff
, yOff
y\nzOff
son opcionales. Son números que establecen la apariencia de la cuadrícula\n(gridSize
y gridDivisions
) y la ubicación del ícono de ejes\n(xOff
, yOff
y zOff
). Por ejemplo, llamar a\ndebugMode(20, 5, 10, 10, 10)
establece el gridSize
en 20 píxeles, el número\nde gridDivisions
en 5 y desplaza el ícono de ejes en 10 píxeles a lo largo de los\nejes x-, y- y z-.
La tercera forma de llamar a debugMode()
tiene cinco parámetros. El primer\nparámetro, mode
, selecciona ya sea GRID
o AXES
para ser mostrado. Los\nsiguientes cuatro parámetros, axesSize
, xOff
, yOff
y zOff
son opcionales.\nSon números que establecen la apariencia del tamaño del ícono de ejes\n(axesSize
) y su ubicación (xOff
, yOff
y zOff
).
La cuarta forma de llamar a debugMode()
tiene nueve parámetros opcionales. Los\nprimeros cinco parámetros, gridSize
, gridDivisions
, gridXOff
, gridYOff
,\ny gridZOff
son números que establecen la apariencia de la cuadrícula. Por\nejemplo, llamar a debugMode(100, 5, 0, 0, 0)
establece el gridSize
en 100,\nel número de gridDivisions
en 5 y establece todos los desplazamientos en 0 para que\nla cuadrícula esté centrada en el origen. Los siguientes cuatro parámetros, axesSize
,\nxOff
, yOff
y zOff
son números que establecen la apariencia del tamaño\ndel ícono de ejes (axesSize
) y su ubicación (axesXOff
, axesYOff
,\ny axesZOff
). Por ejemplo, llamar a\ndebugMode(100, 5, 0, 0, 0, 50, 10, 10, 10)
establece el gridSize
en 100,\nel número de gridDivisions
en 5 y establece todos los desplazamientos en 0 para que\nla cuadrícula esté centrada en el origen. Luego establece el axesSize
en 50 y\ndesplaza el ícono 10 píxeles a lo largo de cada eje.
ya sea GRID o AXES
\n"],"type":[0,"Constant"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"mode"],"description":[0,""],"type":[0,"Constant"]}],[0,{"name":[0,"gridSize"],"description":[0,"longitud de lado de la cuadrícula.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"gridDivisions"],"description":[0,"número de divisiones en la cuadrícula.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"xOff"],"description":[0,"desplazamiento desde el origen a lo largo del eje x.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"yOff"],"description":[0,"desplazamiento desde el origen a lo largo del eje y.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"zOff"],"description":[0,"desplazamiento desde el origen a lo largo del eje z.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"mode"],"description":[0,""],"type":[0,"Constant"]}],[0,{"name":[0,"axesSize"],"description":[0,"longitud de los marcadores del ícono de ejes.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"xOff"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"yOff"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"zOff"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gridSize"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"gridDivisions"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"gridXOff"],"description":[0,"desplazamiento de la cuadrícula desde el origen a lo largo del eje x.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"gridYOff"],"description":[0,"desplazamiento de la cuadrícula desde el origen a lo largo del eje y.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"gridZOff"],"description":[0,"desplazamiento de la cuadrícula desde el origen a lo largo del eje z.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"axesSize"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"axesXOff"],"description":[0,"desplazamiento del ícono de ejes desde el origen a lo largo del eje x.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"axesYOff"],"description":[0,"desplazamiento del ícono de ejes desde el origen a lo largo del eje y.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"axesZOff"],"description":[0,"desplazamiento del ícono de ejes desde el origen a lo largo del eje z.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Enable debug mode.\n debugMode();\n\n describe('A multicolor box on a gray background. A grid and axes icon are displayed near the box.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Style the box.\n normalMaterial();\n\n // Draw the box.\n box(20, 40);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Enable debug mode.\n // Only display the axes icon.\n debugMode(AXES);\n\n describe('A multicolor box on a gray background. A grid and axes icon are displayed near the box.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Style the box.\n normalMaterial();\n\n // Draw the box.\n box(20, 40);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Enable debug mode.\n // Only display the grid and customize it:\n // - size: 50\n // - divisions: 10\n // - offsets: 0, 20, 0\n debugMode(GRID, 50, 10, 0, 20, 0);\n\n describe('A multicolor box on a gray background. A grid is displayed below the box.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Style the box.\n normalMaterial();\n\n // Draw the box.\n box(20, 40);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Enable debug mode.\n // Display the grid and axes icon and customize them:\n // Grid\n // ----\n // - size: 50\n // - divisions: 10\n // - offsets: 0, 20, 0\n // Axes\n // ----\n // - size: 50\n // - offsets: 0, 0, 0\n debugMode(50, 10, 0, 20, 0, 50, 0, 0, 0);\n\n describe('A multicolor box on a gray background. A grid is displayed below the box. An axes icon is displayed at the center of the box.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Style the box.\n normalMaterial();\n\n // Draw the box.\n box(20, 40);\n}\n
\nDesactiva debugMode() en un boceto 3D.
\n"],"line":[0,725],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Enable debug mode.\n debugMode();\n\n describe('A multicolor box on a gray background. A grid and axes icon are displayed near the box. They disappear when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Style the box.\n normalMaterial();\n\n // Draw the box. box(20, 40);\n}\n\n// Disable debug mode when the user double-clicks.\nfunction doubleClicked() {\n noDebugMode();\n}\n
\nPermite al usuario orbitar alrededor de un boceto 3D utilizando un mouse, trackpad o pantalla táctil.
\nLos bocetos 3D se ven a través de una cámara imaginaria. Llamar a orbitControl()
dentro de la función draw() permite al usuario cambiar la posición de la cámara:
\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();
\n // Rest of sketch.\n}\n
\nHacer clic izquierdo y arrastrar o deslizar el dedo rotará la posición de la cámara alrededor del centro del boceto. Hacer clic derecho y arrastrar o deslizar con varios dedos moverá la posición de la cámara sin rotación. Usar la rueda del mouse (desplazamiento) o pellizcar hacia adentro/afuera moverá la cámara más lejos o más cerca del centro del boceto.
\nLos primeros tres parámetros, sensitivityX
, sensitivityY
y sensitivityZ
, son opcionales. Son números que establecen la sensibilidad del boceto al movimiento a lo largo de cada eje. Por ejemplo, llamar a orbitControl(1, 2, -1)
mantiene el movimiento a lo largo del eje x en su valor predeterminado, hace que el boceto sea dos veces más sensible al movimiento a lo largo del eje y y invierte el movimiento a lo largo del eje z. Por defecto, todos los valores de sensibilidad son 1.
El cuarto parámetro, options
, también es opcional. Es un objeto que cambia el comportamiento de la órbita. Por ejemplo, llamar a orbitControl(1, 1, 1, options)
mantiene los valores de sensibilidad predeterminados mientras cambia los comportamientos establecidos con options
. El objeto puede tener las siguientes propiedades:
\nlet options = {\n // Setting this to false makes mobile interactions smoother by\n // preventing accidental interactions with the page while orbiting.\n // By default, it's true.\n disableTouchActions: true,\n\n // Setting this to true makes the camera always rotate in the\n // direction the mouse/touch is moving.\n // By default, it's false.\n freeRotation: false\n};
\norbitControl(1, 1, 1, options);\n
\n"],"line":[0,11],"params":[1,[[0,{"name":[0,"sensitivityX"],"description":[0,"sensibilidad al movimiento a lo largo del eje x. Por defecto es 1.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"sensitivityY"],"description":[0,"sensibilidad al movimiento a lo largo del eje y. Por defecto es 1.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"sensitivityZ"],"description":[0,"sensibilidad al movimiento a lo largo del eje z. Por defecto es 1.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"options"],"description":[0,"objeto con dos propiedades opcionales, disableTouchActions
\n y freeRotation
. Ambas son de tipo Boolean
. disableTouchActions
\n por defecto es true
y freeRotation
por defecto es false
.
\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A multicolor box on a gray background. The camera angle changes when the user interacts using a mouse, trackpad, or touchscreen.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Style the box.\n normalMaterial();\n\n // Draw the box.\n box(30, 50);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A multicolor box on a gray background. The camera angle changes when the user interacts using a mouse, trackpad, or touchscreen.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n // Make the interactions 3X sensitive.\n orbitControl(3, 3, 3);\n\n // Style the box.\n normalMaterial();\n\n // Draw the box.\n box(30, 50);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A multicolor box on a gray background. The camera angle changes when the user interacts using a mouse, trackpad, or touchscreen.');\n}\n\nfunction draw() {\n background(200);\n\n // Create an options object.\n let options = {\n disableTouchActions: false,\n freeRotation: true\n };\n\n // Enable orbiting with the mouse.\n // Prevent accidental touch actions on touchscreen devices\n // and enable free rotation.\n orbitControl(1, 1, 1, options);\n\n // Style the box.\n normalMaterial();\n\n // Draw the box.\n box(30, 50);\n}\n
\nCrea una luz que brilla desde todas las direcciones.
\nLa luz ambiental no proviene de una dirección específica. En cambio, las formas 3D\nse iluminan de manera uniforme desde todos los lados. Las luces ambientales se utilizan casi siempre en\ncombinación con otros tipos de luces.
\nHay tres formas de llamar a ambientLight()
con parámetros opcionales para\nestablecer el color de la luz.
La primera forma de llamar a ambientLight()
tiene dos parámetros, gray
y\nalpha
. alpha
es opcional. Se pueden pasar valores de escala de grises y alfa entre 0 y 255\npara establecer el color de la luz ambiental, como en ambientLight(50)
o\nambientLight(50, 30)
.
La segunda forma de llamar a ambientLight()
tiene un parámetro, color. Se puede pasar un\nobjeto p5.Color, un arreglo de valores de color o una\ncadena de color CSS, como en ambientLight('magenta')
, para establecer el\ncolor de la luz ambiental.
La tercera forma de llamar a ambientLight()
tiene cuatro parámetros, v1
, v2
,\nv3
y alpha
. alpha
es opcional. Se pueden pasar valores RGBA, HSBA o HSLA\npara establecer los colores de la luz ambiental, como en ambientLight(255, 0, 0)
\no ambientLight(255, 0, 0, 30)
. Los valores de color se interpretarán utilizando\nel colorMode() actual.
valor rojo o de matiz en el actual\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"valor verde o de saturación en el actual\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"valor azul, brillo o luminosidad en el actual\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,"valor alfa (transparencia) en el actual\n colorMode().
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gray"],"description":[0,"valor de escala de grises entre 0 y 255.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"color como una cadena CSS.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"values"],"description":[0,"color como un arreglo de valores RGBA, HSBA o HSLA.
\n"],"type":[0,"Number[]"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"color como un objeto p5.Color.
\n"],"type":[0,"p5.Color"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click the canvas to turn on the light.\n\nlet isLit = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere drawn against a gray background. The sphere appears to change color when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Control the light.\n if (isLit === true) {\n // Use a grayscale value of 80.\n ambientLight(80);\n }\n\n // Draw the sphere.\n sphere(30);\n}\n\n// Turn on the ambient light when the user double-clicks.\nfunction doubleClicked() {\n isLit = true;\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A faded magenta sphere drawn against a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n // Use a p5.Color object.\n let c = color('orchid');\n ambientLight(c);\n\n // Draw the sphere.\n sphere();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A faded magenta sphere drawn against a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n // Use a CSS color string.\n ambientLight('#DA70D6');\n\n // Draw the sphere.\n sphere(30);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A faded magenta sphere drawn against a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n // Use RGB values\n ambientLight(218, 112, 214);\n\n // Draw the sphere.\n sphere(30);\n}\n
\nCrea una luz que brilla en una dirección.
\nLas luces direccionales no brillan desde un punto específico. Son como un sol\nque brilla desde algún lugar fuera de la pantalla. La dirección de la luz se establece\nutilizando tres valores (x, y, z)
entre -1 y 1. Por ejemplo, establecer la dirección de una luz como (1, 0, 0)
iluminará los objetos de p5.Geometry\ndesde la izquierda, ya que la luz apunta directamente hacia la derecha.
Hay cuatro formas de llamar a directionalLight()
con parámetros para establecer el color y la dirección de la luz.
La primera forma de llamar a directionalLight()
tiene seis parámetros. Los primeros tres parámetros, v1
, v2
y v3
, establecen el color de la luz utilizando el colorMode() actual. Los últimos tres parámetros, x
, y
y z
, establecen la dirección de la luz. Por ejemplo, directionalLight(255, 0, 0, 1, 0, 0)
crea una luz roja (255, 0, 0)
que brilla hacia la derecha (1, 0, 0)
.
La segunda forma de llamar a directionalLight()
tiene cuatro parámetros. Los primeros tres parámetros, v1
, v2
y v3
, establecen el color de la luz utilizando el colorMode() actual. El último parámetro, direction
, establece la dirección de la luz utilizando un objeto p5.Geometry. Por ejemplo, directionalLight(255, 0, 0, lightDir)
crea una luz roja (255, 0, 0)
que brilla en la dirección en la que apunta el vector lightDir
.
La tercera forma de llamar a directionalLight()
tiene cuatro parámetros. El primer parámetro, color
, establece el color de la luz utilizando un objeto p5.Color o un arreglo de valores de color. Los últimos tres parámetros, x
, y
y z
, establecen la dirección de la luz. Por ejemplo, directionalLight(myColor, 1, 0, 0)
crea una luz que brilla hacia la derecha (1, 0, 0)
con el valor de color de myColor
.
La cuarta forma de llamar a directionalLight()
tiene dos parámetros. El primer parámetro, color
, establece el color de la luz utilizando un objeto p5.Color o un arreglo de valores de color. El segundo parámetro, direction
, establece la dirección de la luz utilizando un objeto p5.Color. Por ejemplo, directionalLight(myColor, lightDir)
crea una luz que brilla en la dirección en la que apunta el vector lightDir
con el valor de color de myColor
.
valor rojo o de matiz en el actual\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"valor verde o de saturación en el actual\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"valor azul, brillo o luminosidad en el actual\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"x"],"description":[0,"Componente x de la dirección de la luz entre -1 and 1.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"Componente y de la dirección de la luz entre -1 y 1.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,"Componente z de la dirección de la luz entre -1 y 1.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"direction"],"description":[0,"dirección de la luz como un objeto\n p5.Vector.
\n"],"type":[0,"p5.Vector"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"color como un objeto p5.Color,\n un arreglo de valores de color, o como una cadena CSS.
\n"],"type":[0,"p5.Color|Number[]|String"]}],[0,{"name":[0,"x"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,""],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,""],"type":[0,"p5.Color|Number[]|String"]}],[0,{"name":[0,"direction"],"description":[0,""],"type":[0,"p5.Vector"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click to turn on the directional light.\n\nlet isLit = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere drawn on a gray background. A red light starts shining from above when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Control the light.\n if (isLit === true) {\n // Add a red directional light from above.\n // Use RGB values and XYZ directions.\n directionalLight(255, 0, 0, 0, 1, 0);\n }\n\n // Style the sphere.\n noStroke();\n\n // Draw the sphere.\n sphere(30);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere drawn on a gray background. The top of the sphere appears bright red. The color gets darker toward the bottom.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Add a red directional light from above.\n // Use a p5.Color object and XYZ directions.\n let c = color(255, 0, 0);\n directionalLight(c, 0, 1, 0);\n\n // Style the sphere.\n noStroke();\n\n // Draw the sphere.\n sphere(30);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere drawn on a gray background. The top of the sphere appears bright red. The color gets darker toward the bottom.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Add a red directional light from above.\n // Use a p5.Color object and a p5.Vector object.\n let c = color(255, 0, 0);\n let lightDir = createVector(0, 1, 0);\n directionalLight(c, lightDir);\n\n // Style the sphere.\n noStroke();\n\n // Draw the sphere.\n sphere(30);\n}\n
\nCrea una luz ambiental a partir de una imagen.
\nimageLight()
simula una luz que brilla desde todas las direcciones. El efecto es como colocar el boceto en el centro de una esfera gigante que utiliza la imagen como su textura. La luz difusa de la imagen se verá afectada por fill() y las reflexiones especulares se verán afectadas por specularMaterial() y shininess().
El parámetro img
es el objeto p5.Image que se utilizará como fuente de luz.
imagen a utilizar como fuente de luz.
\n"],"type":[0,"p5.image"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nlet img;\n\n// Load an image and create a p5.Image object.\nfunction preload() {\n img = loadImage('/assets/outdoor_spheremap.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere floating above a landscape. The surface of the sphere reflects the landscape.');\n}\n\nfunction draw() {\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Draw the image as a panorama (360˚ background).\n panorama(img);\n\n // Add a soft ambient light.\n ambientLight(50);\n\n // Add light from the image.\n imageLight(img);\n\n // Style the sphere.\n specularMaterial(20);\n shininess(100);\n noStroke();\n\n // Draw the sphere.\n sphere(30);\n}\n
\nEstablece la tasa de atenuación para pointLight()\ny spotLight().
\nLa atenuación de una luz describe la intensidad de su haz a una distancia. Por ejemplo, una linterna tiene una atenuación lenta, una linterna tiene una atenuación media y un puntero láser tiene una atenuación aguda.
\nlightFalloff()
tiene tres parámetros, constant
, linear
y quadratic
. Son números utilizados para calcular la atenuación a una distancia d
, de la siguiente manera:
falloff = 1 / (constant + d * linear + (d * d) * quadratic)
Nota: constant
, linear
y quadratic
siempre deben tener valores mayores a 0.
valor constante para calcular la atenuación.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"linear"],"description":[0,"valor lineal para calcular la atenuación.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"quadratic"],"description":[0,"valor cuadrático para calcular la atenuación.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click to change the falloff rate.\n\nlet useFalloff = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere drawn against a gray background. The intensity of the light changes when the user double-clicks.');\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Set the light falloff.\n if (useFalloff === true) {\n lightFalloff(2, 0, 0);\n }\n\n // Add a white point light from the front.\n pointLight(255, 255, 255, 0, 0, 100);\n\n // Style the sphere.\n noStroke();\n\n // Draw the sphere.\n sphere(30);\n}\n\n// Change the falloff value when the user double-clicks.\nfunction doubleClicked() {\n useFalloff = true;\n}\n
\nColoca una luz ambiental y direccional en la escena.\nLas luces están configuradas en ambientLight(128, 128, 128) y\ndirectionalLight(128, 128, 128, 0, 0, -1).
\nNota: las luces deben ser llamadas (ya sea directa o indirectamente)\ndentro de draw() para que sean persistentes en un programa en bucle.\nColocarlas en setup() hará que solo tengan efecto\nla primera vez que se ejecute el bucle.
\n"],"line":[0,1076],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click to turn on the lights.\n\nlet isLit = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white box drawn against a gray background. The quality of the light changes when the user double-clicks.');\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Control the lights.\n if (isLit === true) {\n lights();\n }\n\n // Draw the box.\n box();\n}\n\n// Turn on the lights when the user double-clicks.\nfunction doubleClicked() {\n isLit = true;\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white box drawn against a gray background.');\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n ambientLight(128, 128, 128);\n directionalLight(128, 128, 128, 0, 0, -1);\n\n // Draw the box.\n box();\n}\n
\nElimina todas las luces de la escena.
\nLlamar a noLights()
elimina cualquier luz creada con las funciones\nlights(),\nambientLight(),\ndirectionalLight(),\npointLight() o\nspotLight(). Estas funciones pueden ser llamadas\ndespués de noLights()
para crear un nuevo esquema de iluminación.
\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('Two spheres drawn against a gray background. The top sphere is white and the bottom sphere is red.');\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Style the spheres.\n noStroke();\n\n // Draw the top sphere.\n push();\n translate(0, -25, 0);\n sphere(20);\n pop();\n\n // Turn off the lights.\n noLights();\n\n // Add a red directional light that points into the screen.\n directionalLight(255, 0, 0, 0, 0, -1);\n\n // Draw the bottom sphere.\n push();\n translate(0, 25, 0);\n sphere(20);\n pop();\n}\n
\nCrea un fondo 3D inmersivo.
\npanorama()
transforma imágenes que contienen contenido de 360˚, como mapas o\nHDRIs, en fondos 3D inmersivos que rodean un boceto. Explorar el\nespacio requiere cambiar la perspectiva de la cámara con funciones como\norbitControl() o\ncamera().
Imagen de 360˚ para usar como fondo.
\n"],"type":[0,"p5.Image"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nlet img;\n\n// Load an image and create a p5.Image object.\nfunction preload() {\n img = loadImage('/assets/outdoor_spheremap.jpg');\n}\n\nfunction setup() {\n createCanvas(100 ,100 ,WEBGL);\n\n describe('A sphere floating above a landscape. The surface of the sphere reflects the landscape. The full landscape is viewable in 3D as the user drags the mouse.');\n}\n\nfunction draw() {\n // Add the panorama.\n panorama(img);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Use the image as a light source.\n imageLight(img);\n\n // Style the sphere.\n noStroke();\n specularMaterial(50);\n shininess(200);\n metalness(100);\n\n // Draw the sphere.\n sphere(30);\n}\n
\nCrea una luz que brilla desde un punto en todas las direcciones.
\nLas luces de punto son como bombillas que brillan en todas las direcciones. Se pueden colocar en diferentes posiciones para lograr diferentes efectos de iluminación. Se pueden activar un máximo de 5 luces de punto a la vez.
\nHay cuatro formas de llamar a pointLight()
con parámetros para establecer el color y la posición de la luz.
La primera forma de llamar a pointLight()
tiene seis parámetros. Los primeros tres parámetros, v1
, v2
y v3
, establecen el color de la luz utilizando el colorMode() actual. Los últimos tres parámetros, x
, y
y z
, establecen la posición de la luz. Por ejemplo, pointLight(255, 0, 0, 50, 0, 0)
crea una luz roja (255, 0, 0)
que brilla desde las coordenadas (50, 0, 0)
.
La segunda forma de llamar a pointLight()
tiene cuatro parámetros. Los primeros tres parámetros, v1
, v2
y v3
, establecen el color de la luz utilizando el colorMode() actual. El último parámetro, position
, establece la posición de la luz utilizando un objeto p5.Vector. Por ejemplo, pointLight(255, 0, 0, lightPos)
crea una luz roja (255, 0, 0)
que brilla desde la posición establecida por el vector lightPos
.
La tercera forma de llamar a pointLight()
tiene cuatro parámetros. El primer parámetro, color
, establece el color de la luz utilizando un objeto p5.Color o un arreglo de valores de color. Los últimos tres parámetros, x
, y
y z
, establecen la posición de la luz. Por ejemplo, directionalLight(myColor, 50, 0, 0)
crea una luz que brilla desde las coordenadas (50, 0, 0)
con el valor de color de myColor
.
La cuarta forma de llamar a pointLight()
tiene dos parámetros. El primer parámetro, color
, establece el color de la luz utilizando un objeto p5.Color o un arreglo de valores de color. El segundo parámetro, position
, establece la posición de la luz utilizando un objeto p5.Vector. Por ejemplo, directionalLight(myColor, lightPos)
crea una luz que brilla desde la posición establecida por el vector lightPos
con el valor de color de myColor
.
valor rojo o de matiz en el actual\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"valor verde o de saturación en el actual\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"valor azul, brillo o luminosidad en el actual\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"x"],"description":[0,"Coordenada x de la luz.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"Coordenada y de la luz.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,"Coordenada z de la luz.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"position"],"description":[0,"posición de la luz como un objeto\n p5.Vector.
\n"],"type":[0,"p5.Vector"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"color como un objeto p5.Color,\n un arreglo de valores de color o una cadena CSS.
\n"],"type":[0,"p5.Color|Number[]|String"]}],[0,{"name":[0,"x"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,""],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,""],"type":[0,"p5.Color|Number[]|String"]}],[0,{"name":[0,"position"],"description":[0,""],"type":[0,"p5.Vector"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click to turn on the point light.\n\nlet isLit = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere drawn on a gray background. A red light starts shining from above when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Control the light.\n if (isLit === true) {\n // Add a red point light from above.\n // Use RGB values and XYZ coordinates.\n pointLight(255, 0, 0, 0, -150, 0);\n }\n\n // Style the sphere.\n noStroke();\n\n // Draw the sphere.\n sphere(30);\n}\n\n// Turn on the point light when the user double-clicks.\nfunction doubleClicked() {\n isLit = true;\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere drawn on a gray background. The top of the sphere appears bright red. The color gets darker toward the bottom.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Add a red point light from above.\n // Use a p5.Color object and XYZ directions.\n let c = color(255, 0, 0);\n pointLight(c, 0, -150, 0);\n\n // Style the sphere.\n noStroke();\n\n // Draw the sphere.\n sphere(30);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere drawn on a gray background. The top of the sphere appears bright red. The color gets darker toward the bottom.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Add a red point light from above.\n // Use a p5.Color object and a p5.Vector object.\n let c = color(255, 0, 0);\n let lightPos = createVector(0, -150, 0);\n pointLight(c, lightPos);\n\n // Style the sphere.\n noStroke();\n\n // Draw the sphere.\n sphere(30);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('Four spheres arranged in a square and drawn on a gray background. The spheres appear bright red toward the center of the square. The color gets darker toward the corners of the square.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Add a red point light that points to the center of the scene.\n // Use a p5.Color object and a p5.Vector object.\n let c = color(255, 0, 0);\n let lightPos = createVector(0, 0, 65);\n pointLight(c, lightPos);\n\n // Style the spheres.\n noStroke();\n\n // Draw a sphere up and to the left.\n push();\n translate(-25, -25, 25);\n sphere(10);\n pop();\n\n // Draw a box up and to the right.\n push();\n translate(25, -25, 25);\n sphere(10);\n pop();\n\n // Draw a sphere down and to the left.\n push();\n translate(-25, 25, 25);\n sphere(10);\n pop();\n\n // Draw a box down and to the right.\n push();\n translate(25, 25, 25);\n sphere(10);\n pop();\n}\n
\nEstablece el color especular para las luces.
\nspecularColor()
afecta a las luces que rebotan en una superficie en una dirección preferida. Estas luces incluyen directionalLight(), pointLight() y spotLight(). La función ayuda a crear reflejos en objetos p5.Geometry que están estilizados con specularMaterial(). Si una geometría no utiliza specularMaterial(), entonces specularColor()
no tendrá efecto.
Nota: specularColor()
no afecta a las luces que rebotan en todas las direcciones, incluyendo ambientLight() e imageLight().
Hay tres formas de llamar a specularColor()
con parámetros opcionales para establecer el color del reflejo especular.
La primera forma de llamar a specularColor()
tiene dos parámetros opcionales, gray
y alpha
. Se pueden pasar valores de escala de grises y alfa entre 0 y 255, como en specularColor(50)
o specularColor(50, 80)
, para establecer el color del reflejo especular.
La segunda forma de llamar a specularColor()
tiene un parámetro opcional, color
. Se puede pasar un objeto p5.Color, un arreglo de valores de color o una cadena de color CSS para establecer el color del reflejo especular.
La tercera forma de llamar a specularColor()
tiene cuatro parámetros opcionales, v1
, v2
, v3
y alpha
. Se pueden pasar valores RGBA, HSBA o HSLA, como en specularColor(255, 0, 0, 80)
, para establecer el color del reflejo especular. Los valores de color se interpretarán utilizando el colorMode() actual.
valor rojo o de matiz en el actual\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"valor verde o de saturación en el actual\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"valor azul, de brillo o de luminosidad en el actual\n colorMode().
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gray"],"description":[0,"valor de escala de grises entre 0 y 255.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"color como una cadena CSS.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"values"],"description":[0,"color como un arreglo de valores RGBA, HSBA o HSLA.
\n"],"type":[0,"Number[]"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"color como un objeto p5.Color.
\n"],"type":[0,"p5.Color"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white sphere drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // No specular color.\n // Draw the sphere.\n sphere(30);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click the canvas to add a point light.\n\nlet isLit = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A sphere drawn on a gray background. A spotlight starts shining when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Style the sphere.\n noStroke();\n specularColor(100);\n specularMaterial(255, 255, 255);\n\n // Control the light.\n if (isLit === true) {\n // Add a white point light from the top-right.\n pointLight(255, 255, 255, 30, -20, 40);\n }\n\n // Draw the sphere.\n sphere(30);\n}\n\n// Turn on the point light when the user double-clicks.\nfunction doubleClicked() {\n isLit = true;\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A black sphere drawn on a gray background. An area on the surface of the sphere is highlighted in blue.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Add a specular highlight.\n // Use a p5.Color object.\n let c = color('dodgerblue');\n specularColor(c);\n\n // Add a white point light from the top-right.\n pointLight(255, 255, 255, 30, -20, 40);\n\n // Style the sphere.\n noStroke();\n\n // Add a white specular material.\n specularMaterial(255, 255, 255);\n\n // Draw the sphere.\n sphere(30);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A black sphere drawn on a gray background. An area on the surface of the sphere is highlighted in blue.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Add a specular highlight.\n // Use a CSS color string.\n specularColor('#1E90FF');\n\n // Add a white point light from the top-right.\n pointLight(255, 255, 255, 30, -20, 40);\n\n // Style the sphere.\n noStroke();\n\n // Add a white specular material.\n specularMaterial(255, 255, 255);\n\n // Draw the sphere.\n sphere(30);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A black sphere drawn on a gray background. An area on the surface of the sphere is highlighted in blue.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Add a specular highlight.\n // Use RGB values.\n specularColor(30, 144, 255);\n\n // Add a white point light from the top-right.\n pointLight(255, 255, 255, 30, -20, 40);\n\n // Style the sphere.\n noStroke();\n\n // Add a white specular material.\n specularMaterial(255, 255, 255);\n\n // Draw the sphere.\n sphere(30);\n}\n
\nCrea una luz que brilla desde un punto en una dirección.
\nLas luces de foco son como linternas que brillan en una dirección creando un cono de luz. La forma del cono se puede controlar utilizando los parámetros de ángulo y concentración. Se pueden activar como máximo 5 luces de foco a la vez.
\nHay ocho formas de llamar a spotLight()
con parámetros para establecer el color, la posición y la dirección de la luz. Por ejemplo, spotLight(255, 0, 0, 0, 0, 0, 1, 0, 0)
crea una luz roja (255, 0, 0)
en el origen (0, 0, 0)
que apunta hacia la derecha (1, 0, 0)
.
El parámetro angle
es opcional. Establece el radio del cono de luz. Por ejemplo, spotLight(255, 0, 0, 0, 0, 0, 1, 0, 0, PI / 16)
crea una luz roja (255, 0, 0)
en el origen (0, 0, 0)
que apunta hacia la derecha (1, 0, 0)
con un ángulo de PI / 16
radianes. Por defecto, angle
es PI / 3
radianes.
El parámetro concentration
también es opcional. Enfoca la luz hacia el centro del cono de luz. Por ejemplo, spotLight(255, 0, 0, 0, 0, 0, 1, 0, 0, PI / 16, 50)
crea una luz roja (255, 0, 0)
en el origen (0, 0, 0)
que apunta hacia la derecha (1, 0, 0)
con un ángulo de PI / 16
radianes y una concentración de 50. Por defecto, concentration
es 100.
valor rojo o de matiz en el\n colorMode() actual.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"valor verde o de saturación en el\n colorMode() actual.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"valor azul, de brillo o de luminosidad en el\n colorMode() actual.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"x"],"description":[0,"coordenada x de la luz.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"coordenada y de la luz.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,"coordenada z de la luz.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"rx"],"description":[0,"componente x de la dirección de la luz entre -1 y 1.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"ry"],"description":[0,"componente y de la dirección de la luz entre -1 y 1.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"rz"],"description":[0,"componente z de la dirección de la luz entre -1 y 1.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"angle"],"description":[0,"ángulo del cono de luz. Por defecto es PI / 3
.
concentración de la luz. Por defecto es 100.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"color como un objeto p5.Color,\n un arreglo de valores de color o una cadena CSS.
\n"],"type":[0,"p5.Color|Number[]|String"]}],[0,{"name":[0,"position"],"description":[0,"posición de la luz como un objeto p5.Vector.
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"direction"],"description":[0,"dirección de la luz como un objeto p5.Vector.
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"position"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"direction"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,""],"type":[0,"p5.Color|Number[]|String"]}],[0,{"name":[0,"x"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"direction"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,""],"type":[0,"p5.Color|Number[]|String"]}],[0,{"name":[0,"position"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"rx"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"ry"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"rz"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"x"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"direction"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"position"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"rx"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"ry"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"rz"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,""],"type":[0,"p5.Color|Number[]|String"]}],[0,{"name":[0,"x"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"z"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"rx"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"ry"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"rz"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click to adjust the spotlight.\n\nlet isLit = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white sphere drawn on a gray background. A red spotlight starts shining when the user double-clicks.');\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Control the spotlight.\n if (isLit === true) {\n // Add a red spot light that shines into the screen.\n // Set its angle to PI / 32 radians.\n spotLight(255, 0, 0, 0, 0, 100, 0, 0, -1, PI / 32);\n }\n\n // Draw the sphere.\n sphere(30);\n}\n\n// Turn on the spotlight when the user double-clicks.\nfunction doubleClicked() {\n isLit = true;\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click to adjust the spotlight.\n\nlet isLit = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A white sphere drawn on a gray background. A red spotlight starts shining when the user double-clicks.');\n}\n\nfunction draw() {\n background(50);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on the lights.\n lights();\n\n // Control the spotlight.\n if (isLit === true) {\n // Add a red spot light that shines into the screen.\n // Set its angle to PI / 3 radians (default).\n // Set its concentration to 1000.\n let c = color(255, 0, 0);\n let position = createVector(0, 0, 100);\n let direction = createVector(0, 0, -1);\n spotLight(c, position, direction, PI / 3, 1000);\n }\n\n // Draw the sphere.\n sphere(30);\n}\n\n// Turn on the spotlight when the user double-clicks.\nfunction doubleClicked() {\n isLit = true;\n}\n
\nEstablece el color ambiental del material de la superficie de las formas.
\nEl color ambientMaterial()
establece los componentes del color de la luz ambiental que las formas reflejarán. Por ejemplo, llamar a ambientMaterial(255, 255, 0)
haría que una forma refleje luz roja y verde, pero no luz azul.
ambientMaterial()
se puede llamar de tres formas diferentes con diferentes parámetros para establecer el color del material.
La primera forma de llamar a ambientMaterial()
tiene un parámetro, gray
. Se pueden pasar valores de escala de grises entre 0 y 255, como en ambientMaterial(50)
, para establecer el color del material. Valores de escala de grises más altos hacen que las formas parezcan más brillantes.
La segunda forma de llamar a ambientMaterial()
tiene un parámetro, color
. Se puede pasar un objeto p5.Color, un arreglo de valores de color o una cadena de color CSS, como en ambientMaterial('magenta')
, para establecer el color del material.
La tercera forma de llamar a ambientMaterial()
tiene tres parámetros, v1
, v2
y v3
. Se pueden pasar valores RGB, HSB o HSL, como en ambientMaterial(255, 0, 0)
, para establecer los colores del material. Los valores de color se interpretarán utilizando el colorMode() actual.
Nota: ambientMaterial()
solo se puede usar en el modo WebGL.
valor rojo o de matiz en el actual\n colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"valor verde o de saturación en el\n actual colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"valor azul, brillo o luminosidad en el\n actual colorMode().
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gray"],"description":[0,"valor de escala de grises entre 0 (negro) y 255 (blanco).
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"color como un objeto p5.Color,\n un arreglo de valores de color o una cadena CSS.
\n"],"type":[0,"p5.Color|Number[]|String"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A magenta cube drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a magenta ambient light.\n ambientLight(255, 0, 255);\n\n // Draw the box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A purple cube drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a magenta ambient light.\n ambientLight(255, 0, 255);\n\n // Add a dark gray ambient material.\n ambientMaterial(150);\n\n // Draw the box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A red cube drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a magenta ambient light.\n ambientLight(255, 0, 255);\n\n // Add a yellow ambient material using RGB values.\n ambientMaterial(255, 255, 0);\n\n // Draw the box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A red cube drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a magenta ambient light.\n ambientLight(255, 0, 255);\n\n // Add a yellow ambient material using a p5.Color object.\n let c = color(255, 255, 0);\n ambientMaterial(c);\n\n // Draw the box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A red cube drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a magenta ambient light.\n ambientLight(255, 0, 255);\n\n // Add a yellow ambient material using a color string.\n ambientMaterial('yellow');\n\n // Draw the box.\n box();\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A yellow cube drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a white ambient light.\n ambientLight(255, 255, 255);\n\n // Add a yellow ambient material using a color string.\n ambientMaterial('yellow');\n\n // Draw the box.\n box();\n}\n
\nCrea un objeto p5.Shader para ser utilizado con la función filter().
\ncreateFilterShader()
funciona de manera similar a createShader() pero incluye un vertex shader predeterminado. createFilterShader()
está diseñado para ser utilizado junto con filter() para filtrar el contenido de un lienzo.
Un filtro shader se aplicará a todo el lienzo en lugar de solo a los objetos p5.Geometry.
\nEl parámetro fragSrc
establece el fragment shader. Es una cadena que contiene el programa del fragment shader escrito en GLSL.
El objeto p5.Shader que se crea tiene algunos uniformes que se pueden establecer:
\nsampler2D tex0
, que contiene el contenido del lienzo como una textura.vec2 canvasSize
, que es el ancho y alto del lienzo, sin incluir la densidad de píxeles.vec2 texelSize
, que es el tamaño de un píxel físico, incluyendo la densidad de píxeles. Esto se calcula como 1.0 / (ancho * densidad)
para el ancho del píxel y 1.0 / (height * density)
para la altura del píxel.El p5.Shader que se crea también proporciona varying vec2 vTexCoord
, una coordenada con valores entre 0 y 1. vTexCoord
describe dónde se dibujará el píxel en el lienzo.
Para obtener más información sobre filtros y shaders, consulta el repositorio de Adam Ferriss de ejemplos de shaders de p5.js o el tutorial de Introducción a los Shaders.
\n"],"line":[0,429],"params":[1,[[0,{"name":[0,"fragSrc"],"description":[0,"Código fuente para el fragment shader.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"Objeto shader nuevo creado a partir del fragment shader."],"type":[0,"p5.Shader"]}],"example":[1,[[0,"\n\nfunction setup() {\n let fragSrc = `precision highp float;\n void main() {\n gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);\n }`;\n\n createCanvas(100, 100, WEBGL);\n let s = createFilterShader(fragSrc);\n filter(s);\n describe('a yellow canvas');\n}\n
\n\nlet img, s;\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\nfunction setup() {\n let fragSrc = `precision highp float;\n\n // x,y coordinates, given from the vertex shader\n varying vec2 vTexCoord;\n\n // the canvas contents, given from filter()\n uniform sampler2D tex0;\n // other useful information from the canvas\n uniform vec2 texelSize;\n uniform vec2 canvasSize;\n // a custom variable from this sketch\n uniform float darkness;\n\n void main() {\n // get the color at current pixel\n vec4 color = texture2D(tex0, vTexCoord);\n // set the output color\n color.b = 1.0;\n color *= darkness;\n gl_FragColor = vec4(color.rgb, 1.0);\n }`;\n\n createCanvas(100, 100, WEBGL);\n s = createFilterShader(fragSrc);\n}\nfunction draw() {\n image(img, -50, -50);\n s.setUniform('darkness', 0.5);\n filter(s);\n describe('a image of bricks tinted dark blue');\n}\n
\nCrea un nuevo objeto p5.Shader.
\nLos shaders son programas que se ejecutan en la unidad de procesamiento gráfico (GPU). Pueden procesar muchos píxeles al mismo tiempo, lo que los hace rápidos para muchas tareas gráficas. Están escritos en un lenguaje llamado GLSL y se ejecutan junto con el resto del código en un sketch.
\nUna vez que se crea el objeto p5.Shader, se puede utilizar con la función shader(), como en shader(miShader)
. Un programa de shader consta de dos partes, un vertex shader y un fragment shader. El vertex shader afecta dónde se dibuja la geometría 3D en la pantalla y el fragment shader afecta el color.
El primer parámetro, vertSrc
, establece el vertex shader. Es una cadena que contiene el programa del vertex shader escrito en GLSL.
El segundo parámetro, fragSrc
, establece el fragment shader. Es una cadena que contiene el programa del fragment shader escrito en GLSL.
Nota: Solo se pueden usar shaders de filtro en el modo 2D. Todos los shaders se pueden usar en el modo WebGL.
\n"],"line":[0,173],"params":[1,[[0,{"name":[0,"vertSrc"],"description":[0,"Código fuente para el vertex shader.
\n"],"type":[0,"String"]}],[0,{"name":[0,"fragSrc"],"description":[0,"Código fuente para el fragment shader.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"Nuevo objeto shader creado a partir de los\nshaders de vértices y fragmentos."],"type":[0,"p5.Shader"]}],"example":[1,[[0,"\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision highp float;\n\nvoid main() {\n // Set each pixel's RGBA value to yellow.\n gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);\n}\n`;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Shader object.\n let shaderProgram = createShader(vertSrc, fragSrc);\n\n // Compile and apply the p5.Shader object.\n shader(shaderProgram);\n\n // Style the drawing surface.\n noStroke();\n\n // Add a plane as a drawing surface.\n plane(100, 100);\n\n describe('A yellow square.');\n}\n
\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision highp float;\nuniform vec2 p;\nuniform float r;\nconst int numIterations = 500;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vec2 c = p + gl_FragCoord.xy * r;\n vec2 z = c;\n float n = 0.0;\n\n for (int i = numIterations; i > 0; i--) {\n if (z.x * z.x + z.y * z.y > 4.0) {\n n = float(i) / float(numIterations);\n break;\n }\n z = vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + c;\n }\n\n gl_FragColor = vec4(\n 0.5 - cos(n * 17.0) / 2.0,\n 0.5 - cos(n * 13.0) / 2.0,\n 0.5 - cos(n * 23.0) / 2.0,\n 1.0\n );\n}\n`;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Shader object.\n let mandelbrot = createShader(vertSrc, fragSrc);\n\n // Compile and apply the p5.Shader object.\n shader(mandelbrot);\n\n // Set the shader uniform p to an array.\n // p is the center point of the Mandelbrot image.\n mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);\n\n // Set the shader uniform r to 0.005.\n // r is the size of the image in Mandelbrot-space.\n mandelbrot.setUniform('r', 0.005);\n\n // Style the drawing surface.\n noStroke();\n\n // Add a plane as a drawing surface.\n plane(100, 100);\n\n describe('A black fractal image on a magenta background.');\n}\n
\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision highp float;\nuniform vec2 p;\nuniform float r;\nconst int numIterations = 500;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vec2 c = p + gl_FragCoord.xy * r;\n vec2 z = c;\n float n = 0.0;\n\n for (int i = numIterations; i > 0; i--) {\n if (z.x * z.x + z.y * z.y > 4.0) {\n n = float(i) / float(numIterations);\n break;\n }\n\n z = vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + c;\n }\n\n gl_FragColor = vec4(\n 0.5 - cos(n * 17.0) / 2.0,\n 0.5 - cos(n * 13.0) / 2.0,\n 0.5 - cos(n * 23.0) / 2.0,\n 1.0\n );\n}\n`;\n\nlet mandelbrot;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Shader object.\n mandelbrot = createShader(vertSrc, fragSrc);\n\n // Apply the p5.Shader object.\n shader(mandelbrot);\n\n // Set the shader uniform p to an array.\n // p is the center point of the Mandelbrot image.\n mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);\n\n describe('A fractal image zooms in and out of focus.');\n}\n\nfunction draw() {\n // Set the shader uniform r to a value that oscillates\n // between 0 and 0.005.\n // r is the size of the image in Mandelbrot-space.\n let radius = 0.005 * (sin(frameCount * 0.01) + 1);\n mandelbrot.setUniform('r', radius);\n\n // Style the drawing surface.\n noStroke();\n\n // Add a plane as a drawing surface.\n plane(100, 100);\n}\n
\nEstablece el color de emisión del material de la superficie de las formas.
\nEl color emissiveMaterial()
establece un color que las formas muestran a máxima intensidad, independientemente de la iluminación. Esto puede dar la apariencia de que una forma está brillando. Sin embargo, los materiales de emisión no emiten luz que pueda afectar a los objetos circundantes.
emissiveMaterial()
se puede llamar de tres formas diferentes con diferentes parámetros para establecer el color del material.
La primera forma de llamar a emissiveMaterial()
tiene un parámetro, gray
.\nSe pueden pasar valores de escala de grises entre 0 y 255, como en emissiveMaterial(50)
, para establecer el color del material. Valores de escala de grises más altos hacen que las formas parezcan más brillantes.
La segunda forma de llamar a emissiveMaterial()
tiene un parámetro, color
. Un objeto p5.Color, un arreglo de valores de color o una cadena de color CSS, como en emissiveMaterial('magenta')
, se pueden pasar para establecer el color del material.
La tercera forma de llamar a emissiveMaterial()
tiene cuatro parámetros, v1
, v2
, v3
y alpha
. alpha
es opcional. Se pueden pasar valores RGBA, HSBA o HSLA para establecer los colores del material, como en emissiveMaterial(255, 0, 0)
o emissiveMaterial(255, 0, 0, 30)
. Los valores de color se interpretarán utilizando el colorMode() actual.
Nota: emissiveMaterial()
solo se puede usar en el modo WebGL.
valor rojo o de tono en el\n colorMode() actual.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"valor verde o de saturación en el\n colorMode() actual.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"valor azul, de brillo o de luminosidad en el\n colorMode() actual.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,"valor alfa en el\n colorMode() actual.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gray"],"description":[0,"valor de escala de grises entre 0 (negro) y 255 (blanco).
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"color como un objeto p5.Color,\n un arreglo de valores de color o una cadena CSS.
\n"],"type":[0,"p5.Color|Number[]|String"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A red cube drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a white ambient light.\n ambientLight(255, 255, 255);\n\n // Add a red emissive material using RGB values.\n emissiveMaterial(255, 0, 0);\n\n // Draw the box.\n box();\n}\n
\nCarga shaders de vértices y fragmentos para crear un objeto p5.Shader.
\nLos shaders son programas que se ejecutan en la unidad de procesamiento gráfico (GPU). Pueden procesar muchos píxeles al mismo tiempo, lo que los hace rápidos para muchas tareas gráficas. Están escritos en un lenguaje llamado GLSL y se ejecutan junto con el resto del código en un sketch.
\nUna vez creado el objeto p5.Shader, se puede usar con la función shader(), como en shader(myShader)
. Un programa de shader consta de dos archivos, un shader de vértices y un shader de fragmentos. El shader de vértices afecta dónde se dibuja la geometría 3D en la pantalla y el shader de fragmentos afecta el color.
loadShader()
carga los shaders de vértices y fragmentos desde sus archivos .vert
y .frag
. Por ejemplo, llamar a loadShader('/assets/shader.vert', '/assets/shader.frag')
carga ambos shaders requeridos y devuelve un objeto p5.Shader.
El tercer parámetro, successCallback
, es opcional. Si se pasa una función, se llamará una vez que se haya cargado el shader. La función de devolución de llamada puede utilizar el nuevo objeto p5.Shader como su parámetro.
El cuarto parámetro, failureCallback
, también es opcional. Si se pasa una función, se llamará si el shader no se carga correctamente. La función de devolución de llamada puede utilizar el error del evento como su parámetro.
Los shaders pueden tardar en cargarse. Llamar a loadShader()
en preload() asegura que los shaders se carguen antes de que se utilicen en setup() o draw().
Nota: Los shaders solo se pueden usar en el modo WebGL.
\n"],"line":[0,12],"params":[1,[[0,{"name":[0,"vertFilename"],"description":[0,"Ruta del archivo del shader de vértices a cargar.
\n"],"type":[0,"String"]}],[0,{"name":[0,"fragFilename"],"description":[0,"Ruta del archivo del shader de fragmentos a cargar.
\n"],"type":[0,"String"]}],[0,{"name":[0,"successCallback"],"description":[0,"Función que se llamará una vez que se haya cargado el shader. Puede recibir el objeto p5.Shader.
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"failureCallback"],"description":[0,"Función que se llamará si el shader no se carga correctamente. Puede recibir un objeto de evento Error
.
\n// Note: A \"uniform\" is a global variable within a shader program.\n\nlet mandelbrot;\n\n// Load the shader and create a p5.Shader object.\nfunction preload() {\n mandelbrot = loadShader('/assets/shader.vert', '/assets/shader.frag');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Compile and apply the p5.Shader object.\n shader(mandelbrot);\n\n // Set the shader uniform p to an array.\n mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);\n\n // Set the shader uniform r to the value 1.5.\n mandelbrot.setUniform('r', 1.5);\n\n // Add a quad as a display surface for the shader.\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n\n describe('A black fractal image on a magenta background.');\n}\n
\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\nlet mandelbrot;\n\n// Load the shader and create a p5.Shader object.\nfunction preload() {\n mandelbrot = loadShader('/assets/shader.vert', '/assets/shader.frag');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Use the p5.Shader object.\n shader(mandelbrot);\n\n // Set the shader uniform p to an array.\n mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);\n\n describe('A fractal image zooms in and out of focus.');\n}\n\nfunction draw() {\n // Set the shader uniform r to a value that oscillates between 0 and 2.\n mandelbrot.setUniform('r', sin(frameCount * 0.01) + 1);\n\n // Add a quad as a display surface for the shader.\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n
\nEstablece la cantidad de \"metalness\" de un specularMaterial().
\nmetalness()
puede hacer que los materiales parezcan más metálicos. Afecta la forma en que los materiales reflejan las fuentes de luz, incluyendo directionalLight(), pointLight(), spotLight() y imageLight().
El parámetro metallic
es un número que establece la cantidad de metalness. metallic
debe ser mayor que 1, que es su valor predeterminado. Valores más altos, como metalness(100)
, hacen que los materiales especulares parezcan más metálicos.
Cantidad de metalness.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'Two blue spheres drawn on a gray background. White light reflects from their surfaces as the mouse moves. The right sphere is more metallic than the left sphere.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Turn on an ambient light.\n ambientLight(200);\n\n // Get the mouse's coordinates.\n let mx = mouseX - 50;\n let my = mouseY - 50;\n\n // Turn on a white point light that follows the mouse.\n pointLight(255, 255, 255, mx, my, 50);\n\n // Style the spheres.\n noStroke();\n fill(30, 30, 255);\n specularMaterial(255);\n shininess(20);\n\n // Draw the left sphere with low metalness.\n translate(-25, 0, 0);\n metalness(1);\n sphere(20);\n\n // Draw the right sphere with high metalness.\n translate(50, 0, 0);\n metalness(50);\n sphere(20);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nlet img;\n\nfunction preload() {\n img = loadImage('/assets/outdoor_spheremap.jpg');\n}\n\nfunction setup() {\n createCanvas(100 ,100 ,WEBGL);\n\n describe(\n 'Two spheres floating above a landscape. The surface of the spheres reflect the landscape. The right sphere is more reflective than the left sphere.'\n );\n}\n\nfunction draw() {\n // Add the panorama.\n panorama(img);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Use the image as a light source.\n imageLight(img);\n\n // Style the spheres.\n noStroke();\n specularMaterial(50);\n shininess(200);\n\n // Draw the left sphere with low metalness.\n translate(-25, 0, 0);\n metalness(1);\n sphere(20);\n\n // Draw the right sphere with high metalness.\n translate(50, 0, 0);\n metalness(50);\n sphere(20);\n}\n
\nEstablece el material actual como un material normal.
\nUn material normal establece las superficies que miran hacia el eje x en rojo, las que miran hacia el eje y en verde y las que miran hacia el eje z en azul. El material normal no se ve afectado por la luz. A menudo se utiliza como un material de reemplazo al depurar.
\nNota: normalMaterial()
solo se puede utilizar en modo WebGL.
\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A multicolor torus drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Style the torus.\n normalMaterial();\n\n // Draw the torus.\n torus(30);\n}\n
\nRestaura los shaders por defecto.
\nresetShader()
desactiva cualquier shader aplicado previamente por\nshader().
Nota: Los shaders solo pueden ser utilizados en modo WebGL.
\n"],"line":[0,773],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nuniform mat4 uProjectionMatrix;\nuniform mat4 uModelViewMatrix;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 position = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * position;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision mediump float;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vec2 uv = vTexCoord;\n vec3 color = vec3(uv.x, uv.y, min(uv.x + uv.y, 1.0));\n gl_FragColor = vec4(color, 1.0);\n}\n`;\n\nlet myShader;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Shader object.\n myShader = createShader(vertSrc, fragSrc);\n\n describe(\n 'Two rotating cubes on a gray background. The left one has a blue-purple gradient on each face. The right one is red.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw a box using the p5.Shader.\n // shader() sets the active shader to myShader.\n shader(myShader);\n push();\n translate(-25, 0, 0);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(width / 4);\n pop();\n\n // Draw a box using the default fill shader.\n // resetShader() restores the default fill shader.\n resetShader();\n fill(255, 0, 0);\n push();\n translate(25, 0, 0);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(width / 4);\n pop();\n}\n
\nEstablece el objeto p5.Shader para aplicar mientras se dibuja.
\nLos shaders son programas que se ejecutan en la unidad de procesamiento gráfico (GPU). Pueden procesar muchos píxeles o vértices al mismo tiempo, lo que los hace rápidos para muchas tareas gráficas. Están escritos en un lenguaje llamado GLSL y se ejecutan junto con el resto del código en un sketch.
\nLos objetos p5.Shader se pueden crear utilizando las funciones createShader() y loadShader().
\nEl parámetro s
es el objeto p5.Shader que se va a aplicar. Por ejemplo, llamar a shader(myShader)
aplica myShader
para procesar cada píxel en el lienzo. El shader se utilizará para:
sampler2D
.aNormal
, o si tiene alguno de los siguientes uniformes: uUseLighting
, uAmbientLightCount
, uDirectionalLightCount
, uPointLightCount
, uAmbientColor
, uDirectionalDiffuseColors
, uDirectionalSpecularColors
, uPointLightLocation
, uPointLightDiffuseColors
, uPointLightSpecularColors
, uLightingDirection
o uSpecular
.uStrokeWeight
.El código fuente de los shaders de fragmentos y vértices de un objeto p5.Shader se compilará la primera vez que se pase a shader()
. Consulta MDN para obtener más información sobre la compilación de shaders.
Llamar a resetShader() restaura los shaders predeterminados del sketch.
\nNota: Los shaders solo se pueden utilizar en el modo WebGL.
\n"],"line":[0,571],"params":[1,[[0,{"name":[0,"s"],"description":[0,"Objeto p5.Shader para aplicar.
\n"],"type":[0,"p5.Shader"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision highp float;\n\nvoid main() {\n // Set each pixel's RGBA value to yellow.\n gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);\n}\n`;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Shader object.\n let shaderProgram = createShader(vertSrc, fragSrc);\n\n // Apply the p5.Shader object.\n shader(shaderProgram);\n\n // Style the drawing surface.\n noStroke();\n\n // Add a plane as a drawing surface.\n plane(100, 100);\n\n describe('A yellow square.');\n}\n
\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\nlet mandelbrot;\n\n// Load the shader and create a p5.Shader object.\nfunction preload() {\n mandelbrot = loadShader('/assets/shader.vert', '/assets/shader.frag');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Use the p5.Shader object.\n shader(mandelbrot);\n\n // Set the shader uniform p to an array.\n mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);\n\n describe('A fractal image zooms in and out of focus.');\n}\n\nfunction draw() {\n // Set the shader uniform r to a value that oscillates between 0 and 2.\n mandelbrot.setUniform('r', sin(frameCount * 0.01) + 1);\n\n // Add a quad as a display surface for the shader.\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n
\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\nlet redGreen;\nlet orangeBlue;\nlet showRedGreen = false;\n\n// Load the shader and create two separate p5.Shader objects.\nfunction preload() {\n redGreen = loadShader('/assets/shader.vert', '/assets/shader-gradient.frag');\n orangeBlue = loadShader('/assets/shader.vert', '/assets/shader-gradient.frag');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Initialize the redGreen shader.\n shader(redGreen);\n\n // Set the redGreen shader's center and background color.\n redGreen.setUniform('colorCenter', [1.0, 0.0, 0.0]);\n redGreen.setUniform('colorBackground', [0.0, 1.0, 0.0]);\n\n // Initialize the orangeBlue shader.\n shader(orangeBlue);\n\n // Set the orangeBlue shader's center and background color.\n orangeBlue.setUniform('colorCenter', [1.0, 0.5, 0.0]);\n orangeBlue.setUniform('colorBackground', [0.226, 0.0, 0.615]);\n\n describe(\n 'The scene toggles between two circular gradients when the user double-clicks. An orange and blue gradient vertically, and red and green gradient moves horizontally.'\n );\n}\n\nfunction draw() {\n // Update the offset values for each shader.\n // Move orangeBlue vertically.\n // Move redGreen horizontally.\n orangeBlue.setUniform('offset', [0, sin(frameCount * 0.01) + 1]);\n redGreen.setUniform('offset', [sin(frameCount * 0.01), 1]);\n\n if (showRedGreen === true) {\n shader(redGreen);\n } else {\n shader(orangeBlue);\n }\n\n // Style the drawing surface.\n noStroke();\n\n // Add a quad as a drawing surface.\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n\n// Toggle between shaders when the user double-clicks.\nfunction doubleClicked() {\n showRedGreen = !showRedGreen;\n}\n
\nEstablece la cantidad de brillo (\"brillantez\") de un specularMaterial().
\nLos materiales brillantes enfocan la luz reflejada más que los materiales opacos. shininess()
afecta la forma en que los materiales reflejan las fuentes de luz, incluyendo directionalLight(), pointLight() y spotLight().
El parámetro shine
es un número que establece la cantidad de brillo. shine
debe ser mayor que 1, que es su valor predeterminado.
cantidad de brillo.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'Two red spheres drawn on a gray background. White light reflects from their surfaces as the mouse moves. The right sphere is shinier than the left sphere.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Turn on a red ambient light.\n ambientLight(255, 0, 0);\n\n // Get the mouse's coordinates.\n let mx = mouseX - 50;\n let my = mouseY - 50;\n\n // Turn on a white point light that follows the mouse.\n pointLight(255, 255, 255, mx, my, 50);\n\n // Style the sphere.\n noStroke();\n\n // Add a specular material with a grayscale value.\n specularMaterial(255);\n\n // Draw the left sphere with low shininess.\n translate(-25, 0, 0);\n shininess(10);\n sphere(20);\n\n // Draw the right sphere with high shininess.\n translate(50, 0, 0);\n shininess(100);\n sphere(20);\n}\n
\nEstablece el color especular del material de la superficie de las formas.
\nEl color specularMaterial()
establece los componentes del color de la luz que\nlos revestimientos brillantes en las formas reflejarán. Por ejemplo, llamar a\nspecularMaterial(255, 255, 0)
haría que una forma refleje luz roja y\nverde, pero no luz azul.
A diferencia de ambientMaterial(),\nspecularMaterial()
reflejará el color completo de las fuentes de luz, incluyendo\ndirectionalLight(),\npointLight(),\ny spotLight(). Esto es lo que le da a las formas\nsu apariencia \"brillante\". El brillo del material se puede controlar mediante la\nfunción shininess().
specularMaterial()
se puede llamar de tres formas diferentes con diferentes parámetros para\nestablecer el color del material.
La primera forma de llamar a specularMaterial()
tiene un parámetro, gray
.\nSe pueden pasar valores de escala de grises entre 0 y 255, como en specularMaterial(50)
, para establecer el color del material. Valores de escala de grises más altos hacen que las formas\nparezcan más brillantes.
La segunda forma de llamar a specularMaterial()
tiene un parámetro, color
. Un\nobjeto p5.Color, un arreglo de valores de color o una cadena de color CSS, como en specularMaterial('magenta')
, se pueden pasar para establecer el\ncolor del material.
La tercera forma de llamar a specularMaterial()
tiene cuatro parámetros, v1
, v2
,\nv3
y alpha
. alpha
es opcional. Se pueden pasar valores RGBA, HSBA o HSLA para establecer\nlos colores del material, como en specularMaterial(255, 0, 0)
o\nspecularMaterial(255, 0, 0, 30)
. Los valores de color se interpretarán\nutilizando el colorMode() actual.
valor de escala de grises entre 0 (negro) y 255 (blanco).
\n"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,"valor alfa en el actual\n colorMode().
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,"valor rojo o de matiz en\n el actual colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v2"],"description":[0,"valor verde o de saturación\n en el actual colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"v3"],"description":[0,"valor azul, de brillo o de luminosidad\n en el actual colorMode().
\n"],"type":[0,"Number"]}],[0,{"name":[0,"alpha"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"color como un objeto p5.Color,\n un arreglo de valores de color, o una cadena CSS.
\n"],"type":[0,"p5.Color|Number[]|String"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click the canvas to apply a specular material.\n\nlet isGlossy = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A red torus drawn on a gray background. It becomes glossy when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a white point light at the top-right.\n pointLight(255, 255, 255, 30, -40, 30);\n\n // Add a glossy coat if the user has double-clicked.\n if (isGlossy === true) {\n specularMaterial(255);\n shininess(50);\n }\n\n // Style the torus.\n noStroke();\n fill(255, 0, 0);\n\n // Draw the torus.\n torus(30);\n}\n\n// Make the torus glossy when the user double-clicks.\nfunction doubleClicked() {\n isGlossy = true;\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click the canvas to apply a specular material.\n\nlet isGlossy = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'A red torus drawn on a gray background. It becomes glossy and reflects green light when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a white point light at the top-right.\n pointLight(255, 255, 255, 30, -40, 30);\n\n // Add a glossy green coat if the user has double-clicked.\n if (isGlossy === true) {\n specularMaterial(0, 255, 0);\n shininess(50);\n }\n\n // Style the torus.\n noStroke();\n fill(255, 0, 0);\n\n // Draw the torus.\n torus(30);\n}\n\n// Make the torus glossy when the user double-clicks.\nfunction doubleClicked() {\n isGlossy = true;\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click the canvas to apply a specular material.\n\nlet isGlossy = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'A red torus drawn on a gray background. It becomes glossy and reflects green light when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a white point light at the top-right.\n pointLight(255, 255, 255, 30, -40, 30);\n\n // Add a glossy green coat if the user has double-clicked.\n if (isGlossy === true) {\n // Create a p5.Color object.\n let c = color('green');\n specularMaterial(c);\n shininess(50);\n }\n\n // Style the torus.\n noStroke();\n fill(255, 0, 0);\n\n // Draw the torus.\n torus(30);\n}\n\n// Make the torus glossy when the user double-clicks.\nfunction doubleClicked() {\n isGlossy = true;\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n// Double-click the canvas to apply a specular material.\n\nlet isGlossy = false;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'A red torus drawn on a gray background. It becomes glossy and reflects green light when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Turn on a white point light at the top-right.\n pointLight(255, 255, 255, 30, -40, 30);\n\n // Add a glossy green coat if the user has double-clicked.\n if (isGlossy === true) {\n specularMaterial('#00FF00');\n shininess(50);\n }\n\n // Style the torus.\n noStroke();\n fill(255, 0, 0);\n\n // Draw the torus.\n torus(30);\n}\n\n// Make the torus glossy when the user double-clicks.\nfunction doubleClicked() {\n isGlossy = true;\n}\n
\nEstablece la textura que se utilizará en las formas.
\nUna textura es como una piel que envuelve una forma. texture()
funciona con formas incorporadas, como square() y sphere(), y formas personalizadas creadas con funciones como buildGeometry(). Para texturizar una geometría creada con beginShape(), se deben pasar coordenadas UV a cada llamada de vertex().
El parámetro tex
es la textura a aplicar. texture()
puede usar una variedad de fuentes, incluyendo imágenes, videos y renderizadores externos como objetos p5.Graphics y p5.Framebuffer.
Para texturizar una geometría creada con beginShape(), deberás especificar coordenadas UV en vertex().
\nNota: texture()
solo se puede usar en modo WebGL.
medio a utilizar como textura.
\n"],"type":[0,"p5.Image|p5.MediaElement|p5.Graphics|p5.Texture|p5.Framebuffer|p5.FramebufferTexture"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\nlet img;\n\n// Load an image and create a p5.Image object.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A spinning cube with an image of a ceiling on each face.');\n}\n\nfunction draw() {\n background(0);\n\n // Rotate around the x-, y-, and z-axes.\n rotateZ(frameCount * 0.01);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n\n // Apply the image as a texture.\n texture(img);\n\n // Draw the box.\n box(50);\n}\n
\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Graphics object.\n pg = createGraphics(100, 100);\n\n // Draw a circle to the p5.Graphics object.\n pg.background(200);\n pg.circle(50, 50, 30);\n\n describe('A spinning cube with circle at the center of each face.');\n}\n\nfunction draw() {\n background(0);\n\n // Rotate around the x-, y-, and z-axes.\n rotateZ(frameCount * 0.01);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n\n // Apply the p5.Graphics object as a texture.\n texture(pg);\n\n // Draw the box.\n box(50);\n}\n
\n\nlet vid;\n\n// Load a video and create a p5.MediaElement object.\nfunction preload() {\n vid = createVideo('/assets/fingers.mov');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Hide the video.\n vid.hide();\n\n // Set the video to loop.\n vid.loop();\n\n describe('A rectangle with video as texture');\n}\n\nfunction draw() {\n background(0);\n\n // Rotate around the y-axis.\n rotateY(frameCount * 0.01);\n\n // Apply the video as a texture.\n texture(vid);\n\n // Draw the rectangle.\n rect(-40, -40, 80, 80);\n}\n
\n\nlet vid;\n\n// Load a video and create a p5.MediaElement object.\nfunction preload() {\n vid = createVideo('/assets/fingers.mov');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Hide the video.\n vid.hide();\n\n // Set the video to loop.\n vid.loop();\n\n describe('A rectangle with video as texture');\n}\n\nfunction draw() {\n background(0);\n\n // Rotate around the y-axis.\n rotateY(frameCount * 0.01);\n\n // Set the texture mode.\n textureMode(NORMAL);\n\n // Apply the video as a texture.\n texture(vid);\n\n // Draw a custom shape using uv coordinates.\n beginShape();\n vertex(-40, -40, 0, 0);\n vertex(40, -40, 1, 0);\n vertex(40, 40, 1, 1);\n vertex(-40, 40, 0, 1);\n endShape();\n}\n
\nCambia el sistema de coordenadas utilizado para las texturas cuando se aplican a formas personalizadas.
\nPara que texture() funcione, una forma necesita una forma de mapear los puntos de su superficie a los píxeles de una imagen. Las formas incorporadas como rect() y box() ya tienen estos mapeos de textura basados en sus vértices. Las formas personalizadas creadas con vertex() requieren que se pasen los mapeos de textura como coordenadas uv.
\nCada llamada a vertex() debe incluir 5 argumentos, como en vertex(x, y, z, u, v)
, para mapear el vértice en las coordenadas (x, y, z)
al píxel en las coordenadas (u, v)
dentro de una imagen. Por ejemplo, las esquinas de una imagen rectangular se mapean a las esquinas de un rectángulo por defecto:
\n// Apply the image as a texture.\ntexture(img);\n\n// Draw the rectangle.\nrect(0, 0, 30, 50);\n
\nSi la imagen en el fragmento de código anterior tiene dimensiones de 300 x 500 píxeles, se puede lograr el mismo resultado de la siguiente manera:
\n\n// Apply the image as a texture.\ntexture(img);\n\n// Draw the rectangle.\nbeginShape();
\n// Top-left.\n// u: 0, v: 0\nvertex(0, 0, 0, 0, 0);
\n// Top-right.\n// u: 300, v: 0\nvertex(30, 0, 0, 300, 0);
\n// Bottom-right.\n// u: 300, v: 500\nvertex(30, 50, 0, 300, 500);
\n// Bottom-left.\n// u: 0, v: 500\nvertex(0, 50, 0, 0, 500);
\nendShape();\n
\ntextureMode()
cambia el sistema de coordenadas para las coordenadas uv de la textura.
El parámetro mode
acepta dos constantes posibles. Si se pasa NORMAL
, como en textureMode(NORMAL)
, entonces las coordenadas uv de la textura se pueden proporcionar en el rango de 0 a 1 en lugar de las dimensiones de la imagen. Esto puede ser útil para usar el mismo código para múltiples imágenes de diferentes tamaños. Por ejemplo, el fragmento de código anterior se podría reescribir de la siguiente manera:
\n// Set the texture mode to use normalized coordinates.\ntextureMode(NORMAL);\n\n// Apply the image as a texture.\ntexture(img);
\n// Draw the rectangle.\nbeginShape();
\n// Top-left.\n// u: 0, v: 0\nvertex(0, 0, 0, 0, 0);
\n// Top-right.\n// u: 1, v: 0\nvertex(30, 0, 0, 1, 0);
\n// Bottom-right.\n// u: 1, v: 1\nvertex(30, 50, 0, 1, 1);
\n// Bottom-left.\n// u: 0, v: 1\nvertex(0, 50, 0, 0, 1);
\nendShape();\n
\nDe forma predeterminada, mode
es IMAGE
, lo que escala las coordenadas uv a las dimensiones de la imagen. Llamar a textureMode(IMAGE)
aplica el valor predeterminado.
Nota: textureMode()
solo se puede usar en el modo WebGL.
ya sea IMAGE o NORMAL.
\n"],"type":[0,"Constant"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\n// Load an image and create a p5.Image object.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('An image of a ceiling against a black background.');\n}\n\nfunction draw() {\n background(0);\n\n // Apply the image as a texture.\n texture(img);\n\n // Draw the custom shape.\n // Use the image's width and height as uv coordinates.\n beginShape();\n vertex(-30, -30, 0, 0);\n vertex(30, -30, img.width, 0);\n vertex(30, 30, img.width, img.height);\n vertex(-30, 30, 0, img.height);\n endShape();\n}\n
\n\nlet img;\n\n// Load an image and create a p5.Image object.\nfunction preload() {\n img = loadImage('/assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('An image of a ceiling against a black background.');\n}\n\nfunction draw() {\n background(0);\n\n // Set the texture mode.\n textureMode(NORMAL);\n\n // Apply the image as a texture.\n texture(img);\n\n // Draw the custom shape.\n // Use normalized uv coordinates.\n beginShape();\n vertex(-30, -30, 0, 0);\n vertex(30, -30, 1, 0);\n vertex(30, 30, 1, 1);\n vertex(-30, 30, 0, 1);\n endShape();\n}\n
\nCambia la forma en que las texturas se comportan cuando las coordenadas uv de una forma van más allá de la textura.
\nPara que texture() funcione, una forma necesita una forma de mapear los puntos de su superficie a los píxeles de una imagen. Las formas incorporadas como rect() y box() ya tienen estos mapeos de textura basados en sus vértices. Las formas personalizadas creadas con vertex() requieren que se pasen los mapeos de textura como coordenadas uv.
\nCada llamada a vertex() debe incluir 5 argumentos, como en vertex(x, y, z, u, v)
, para mapear el vértice en las coordenadas (x, y, z)
al píxel en las coordenadas (u, v)
dentro de una imagen. Por ejemplo, las esquinas de una imagen rectangular se mapean a las esquinas de un rectángulo por defecto:
\n// Apply the image as a texture.\ntexture(img);\n\n// Draw the rectangle.\nrect(0, 0, 30, 50);\n
\nSi la imagen en el fragmento de código anterior tiene dimensiones de 300 x 500 píxeles, el mismo resultado se podría lograr de la siguiente manera:
\n\n// Apply the image as a texture.\ntexture(img);\n\n// Draw the rectangle.\nbeginShape();
\n// Top-left.\n// u: 0, v: 0\nvertex(0, 0, 0, 0, 0);
\n// Top-right.\n// u: 300, v: 0\nvertex(30, 0, 0, 300, 0);
\n// Bottom-right.\n// u: 300, v: 500\nvertex(30, 50, 0, 300, 500);
\n// Bottom-left.\n// u: 0, v: 500\nvertex(0, 50, 0, 0, 500);
\nendShape();\n
\ntextureWrap()
controla cómo se comportan las texturas cuando sus coordenadas uv van más allá de la textura. Hacerlo puede producir efectos visuales interesantes como el mosaico. Por ejemplo, la forma personalizada anterior podría tener coordenadas u mayores que el ancho de la imagen:
\n// Apply the image as a texture.\ntexture(img);\n\n// Draw the rectangle.\nbeginShape();\nvertex(0, 0, 0, 0, 0);
\n// Top-right.\n// u: 600\nvertex(30, 0, 0, 600, 0);
\n// Bottom-right.\n// u: 600\nvertex(30, 50, 0, 600, 500);
\nvertex(0, 50, 0, 0, 500);\nendShape();\n
\nLas coordenadas u de 600 son mayores que el ancho de la imagen de textura de 300. Esto crea posibilidades interesantes.
\nEl primer parámetro, wrapX
, acepta tres constantes posibles. Si se pasa CLAMP
, como en textureWrap(CLAMP)
, los píxeles en el borde de la textura se extenderán hasta los bordes de la forma. Si se pasa REPEAT
, como en textureWrap(REPEAT)
, la textura se repetirá en mosaico hasta alcanzar los bordes de la forma. Si se pasa MIRROR
, como en textureWrap(MIRROR)
, la textura se repetirá en mosaico hasta alcanzar los bordes de la forma, volteando su orientación entre los mosaicos. Por defecto, las texturas se ajustan a CLAMP
.
El segundo parámetro, wrapY
, es opcional. Acepta las mismas tres constantes: CLAMP
, REPEAT
y MIRROR
. Si se pasa una de estas constantes, como en textureWRAP(MIRROR, REPEAT)
, entonces la textura se MIRROR
horizontalmente y se REPEAT
verticalmente. Por defecto, wrapY
se establecerá en el mismo valor que wrapX
.
Nota: textureWrap()
solo se puede usar en el modo WebGL.
ya sea CLAMP, REPEAT o MIRROR
\n"],"type":[0,"Constant"]}],[0,{"name":[0,"wrapY"],"description":[0,"ya sea CLAMP, REPEAT o MIRROR
\n"],"type":[0,"Constant"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\nfunction preload() {\n img = loadImage('/assets/rockies128.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'An image of a landscape occupies the top-left corner of a square. Its edge colors smear to cover the other thre quarters of the square.'\n );\n}\n\nfunction draw() {\n background(0);\n\n // Set the texture mode.\n textureMode(NORMAL);\n\n // Set the texture wrapping.\n // Note: CLAMP is the default mode.\n textureWrap(CLAMP);\n\n // Apply the image as a texture.\n texture(img);\n\n // Style the shape.\n noStroke();\n\n // Draw the shape.\n // Use uv coordinates > 1.\n beginShape();\n vertex(-30, -30, 0, 0, 0);\n vertex(30, -30, 0, 2, 0);\n vertex(30, 30, 0, 2, 2);\n vertex(-30, 30, 0, 0, 2);\n endShape();\n}\n
\n\nlet img;\n\nfunction preload() {\n img = loadImage('/assets/rockies128.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('Four identical images of a landscape arranged in a grid.');\n}\n\nfunction draw() {\n background(0);\n\n // Set the texture mode.\n textureMode(NORMAL);\n\n // Set the texture wrapping.\n textureWrap(REPEAT);\n\n // Apply the image as a texture.\n texture(img);\n\n // Style the shape.\n noStroke();\n\n // Draw the shape.\n // Use uv coordinates > 1.\n beginShape();\n vertex(-30, -30, 0, 0, 0);\n vertex(30, -30, 0, 2, 0);\n vertex(30, 30, 0, 2, 2);\n vertex(-30, 30, 0, 0, 2);\n endShape();\n}\n
\n\nlet img;\n\nfunction preload() {\n img = loadImage('/assets/rockies128.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'Four identical images of a landscape arranged in a grid. The images are reflected horizontally and vertically, creating a kaleidoscope effect.'\n );\n}\n\nfunction draw() {\n background(0);\n\n // Set the texture mode.\n textureMode(NORMAL);\n\n // Set the texture wrapping.\n textureWrap(MIRROR);\n\n // Apply the image as a texture.\n texture(img);\n\n // Style the shape.\n noStroke();\n\n // Draw the shape.\n // Use uv coordinates > 1.\n beginShape();\n vertex(-30, -30, 0, 0, 0);\n vertex(30, -30, 0, 2, 0);\n vertex(30, 30, 0, 2, 2);\n vertex(-30, 30, 0, 0, 2);\n endShape();\n}\n
\n\nlet img;\n\nfunction preload() {\n img = loadImage('/assets/rockies128.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'Four identical images of a landscape arranged in a grid. The top row and bottom row are reflections of each other.'\n );\n}\n\nfunction draw() {\n background(0);\n\n // Set the texture mode.\n textureMode(NORMAL);\n\n // Set the texture wrapping.\n textureWrap(REPEAT, MIRROR);\n\n // Apply the image as a texture.\n texture(img);\n\n // Style the shape.\n noStroke();\n\n // Draw the shape.\n // Use uv coordinates > 1.\n beginShape();\n vertex(-30, -30, 0, 0, 0);\n vertex(30, -30, 0, 2, 0);\n vertex(30, 30, 0, 2, 2);\n vertex(-30, 30, 0, 0, 2);\n endShape();\n}\n
\nGet the shader used when no lights or materials are applied.
\nYou can call baseColorShader().modify()
\nand change any of the following hooks:
Hook | \nDescription | \n
---|---|
void beforeVertex | \nCalled at the start of the vertex shader. | \n
vec3 getLocalPosition | \nUpdate the position of vertices before transforms are applied. It takes in vec3 position and must return a modified version. | \n
vec3 getWorldPosition | \nUpdate the position of vertices after transforms are applied. It takes in vec3 position and pust return a modified version. | \n
vec3 getLocalNormal | \nUpdate the normal before transforms are applied. It takes in vec3 normal and must return a modified version. | \n
vec3 getWorldNormal | \nUpdate the normal after transforms are applied. It takes in vec3 normal and must return a modified version. | \n
vec2 getUV | \nUpdate the texture coordinates. It takes in vec2 uv and must return a modified version. | \n
vec4 getVertexColor | \nUpdate the color of each vertex. It takes in a vec4 color and must return a modified version. | \n
void afterVertex | \nCalled at the end of the vertex shader. | \n
void beforeFragment | \nCalled at the start of the fragment shader. | \n
vec4 getFinalColor | \nUpdate the final color after mixing. It takes in a vec4 color and must return a modified version. | \n
void afterFragment | \nCalled at the end of the fragment shader. | \n
Most of the time, you will need to write your hooks in GLSL ES version 300. If you\nare using WebGL 1 instead of 2, write your hooks in GLSL ES 100 instead.
\nCall baseColorShader().inspectHooks()
to see all the possible hooks and\ntheir default implementations.
\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseColorShader().modify({\n uniforms: {\n 'float time': () => millis()\n },\n 'vec3 getWorldPosition': `(vec3 pos) {\n pos.y += 20. * sin(time * 0.001 + pos.x * 0.05);\n return pos;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n noStroke();\n fill('red');\n circle(0, 0, 50);\n}\n
\nGet the default shader used with lights, materials,\nand textures.
\nYou can call baseMaterialShader().modify()
\nand change any of the following hooks:
Hook | Description |
---|---|
\n\n
| \n\n Called at the start of the vertex shader. \n |
\n\n
| \n\n Update the position of vertices before transforms are applied. It takes in |
\n\n
| \n\n Update the position of vertices after transforms are applied. It takes in |
\n\n
| \n\n Update the normal before transforms are applied. It takes in |
\n\n
| \n\n Update the normal after transforms are applied. It takes in |
\n\n
| \n\n Update the texture coordinates. It takes in |
\n\n
| \n\n Update the color of each vertex. It takes in a |
\n\n
| \n\n Called at the end of the vertex shader. \n |
\n\n
| \n\n Called at the start of the fragment shader. \n |
\n\n
| \n\n Update the per-pixel inputs of the material. It takes in an
|
\n\n
| \n\n Take in a
|
\n\n
| \n\n Update the final color after mixing. It takes in a |
\n\n
| \n\n Called at the end of the fragment shader. \n |
Most of the time, you will need to write your hooks in GLSL ES version 300. If you\nare using WebGL 1 instead of 2, write your hooks in GLSL ES 100 instead.
\nCall baseMaterialShader().inspectHooks()
to see all the possible hooks and\ntheir default implementations.
\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseMaterialShader().modify({\n uniforms: {\n 'float time': () => millis()\n },\n 'vec3 getWorldPosition': `(vec3 pos) {\n pos.y += 20.0 * sin(time * 0.001 + pos.x * 0.05);\n return pos;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n lights();\n noStroke();\n fill('red');\n sphere(50);\n}\n
\n\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseMaterialShader().modify({\n declarations: 'vec3 myNormal;',\n 'Inputs getPixelInputs': `(Inputs inputs) {\n myNormal = inputs.normal;\n return inputs;\n }`,\n 'vec4 getFinalColor': `(vec4 color) {\n return mix(\n vec4(1.0, 1.0, 1.0, 1.0),\n color,\n abs(dot(myNormal, vec3(0.0, 0.0, 1.0)))\n );\n }`\n });\n}\n\nfunction draw() {\n background(255);\n rotateY(millis() * 0.001);\n shader(myShader);\n lights();\n noStroke();\n fill('red');\n torus(30);\n}\n
\n\nlet myShader;\nlet environment;\n\nfunction preload() {\n environment = loadImage('/assets/outdoor_spheremap.jpg');\n}\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseMaterialShader().modify({\n 'Inputs getPixelInputs': `(Inputs inputs) {\n float factor =\n sin(\n inputs.texCoord.x * ${TWO_PI} +\n inputs.texCoord.y * ${TWO_PI}\n ) * 0.4 + 0.5;\n inputs.shininess = mix(1., 100., factor);\n inputs.metalness = factor;\n return inputs;\n }`\n });\n}\n\nfunction draw() {\n panorama(environment);\n ambientLight(100);\n imageLight(environment);\n rotateY(millis() * 0.001);\n shader(myShader);\n noStroke();\n fill(255);\n specularMaterial(150);\n sphere(50);\n}\n
\n\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseMaterialShader().modify({\n 'Inputs getPixelInputs': `(Inputs inputs) {\n vec3 newNormal = inputs.normal;\n // Simple bump mapping: adjust the normal based on position\n newNormal.x += 0.2 * sin(\n sin(\n inputs.texCoord.y * ${TWO_PI} * 10.0 +\n inputs.texCoord.x * ${TWO_PI} * 25.0\n )\n );\n newNormal.y += 0.2 * sin(\n sin(\n inputs.texCoord.x * ${TWO_PI} * 10.0 +\n inputs.texCoord.y * ${TWO_PI} * 25.0\n )\n );\n inputs.normal = normalize(newNormal);\n return inputs;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n ambientLight(150);\n pointLight(\n 255, 255, 255,\n 100*cos(frameCount*0.04), -50, 100*sin(frameCount*0.04)\n );\n noStroke();\n fill('red');\n shininess(200);\n specularMaterial(255);\n sphere(50);\n}\n
\nGet the shader used by normalMaterial()
.
You can call baseNormalShader().modify()
\nand change any of the following hooks:
Hook | \nDescription | \n
---|---|
void beforeVertex | \nCalled at the start of the vertex shader. | \n
vec3 getLocalPosition | \nUpdate the position of vertices before transforms are applied. It takes in vec3 position and must return a modified version. | \n
vec3 getWorldPosition | \nUpdate the position of vertices after transforms are applied. It takes in vec3 position and pust return a modified version. | \n
vec3 getLocalNormal | \nUpdate the normal before transforms are applied. It takes in vec3 normal and must return a modified version. | \n
vec3 getWorldNormal | \nUpdate the normal after transforms are applied. It takes in vec3 normal and must return a modified version. | \n
vec2 getUV | \nUpdate the texture coordinates. It takes in vec2 uv and must return a modified version. | \n
vec4 getVertexColor | \nUpdate the color of each vertex. It takes in a vec4 color and must return a modified version. | \n
void afterVertex | \nCalled at the end of the vertex shader. | \n
void beforeFragment | \nCalled at the start of the fragment shader. | \n
vec4 getFinalColor | \nUpdate the final color after mixing. It takes in a vec4 color and must return a modified version. | \n
void afterFragment | \nCalled at the end of the fragment shader. | \n
Most of the time, you will need to write your hooks in GLSL ES version 300. If you\nare using WebGL 1 instead of 2, write your hooks in GLSL ES 100 instead.
\nCall baseNormalShader().inspectHooks()
to see all the possible hooks and\ntheir default implementations.
\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseNormalShader().modify({\n uniforms: {\n 'float time': () => millis()\n },\n 'vec3 getWorldPosition': `(vec3 pos) {\n pos.y += 20. * sin(time * 0.001 + pos.x * 0.05);\n return pos;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n noStroke();\n sphere(50);\n}\n
\n\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseNormalShader().modify({\n 'vec3 getWorldNormal': '(vec3 normal) { return abs(normal); }',\n 'vec4 getFinalColor': `(vec4 color) {\n // Map the r, g, and b values of the old normal to new colors\n // instead of just red, green, and blue:\n vec3 newColor =\n color.r * vec3(89.0, 240.0, 232.0) / 255.0 +\n color.g * vec3(240.0, 237.0, 89.0) / 255.0 +\n color.b * vec3(205.0, 55.0, 222.0) / 255.0;\n newColor = newColor / (color.r + color.g + color.b);\n return vec4(newColor, 1.0) * color.a;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n noStroke();\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.015);\n box(100);\n}\n
\nGet the shader used when drawing the strokes of shapes.
\nYou can call baseStrokeShader().modify()
\nand change any of the following hooks:
Hook | Description |
---|---|
\n\n
| \n\n Called at the start of the vertex shader. \n |
\n\n
| \n\n Update the position of vertices before transforms are applied. It takes in |
\n\n
| \n\n Update the position of vertices after transforms are applied. It takes in |
\n\n
| \n\n Update the stroke weight. It takes in |
\n\n
| \n\n Update the center of the line. It takes in |
\n\n
| \n\n Update the position of each vertex on the edge of the line. It takes in |
\n\n
| \n\n Update the color of each vertex. It takes in a |
\n\n
| \n\n Called at the end of the vertex shader. \n |
\n\n
| \n\n Called at the start of the fragment shader. \n |
\n\n
| \n\n Update the inputs to the shader. It takes in a struct
|
\n\n
| \n\n Caps and joins are made by discarded pixels in the fragment shader to carve away unwanted areas. Use this to change this logic. It takes in a |
\n\n
| \n\n Update the final color after mixing. It takes in a |
\n\n
| \n\n Called at the end of the fragment shader. \n |
Most of the time, you will need to write your hooks in GLSL ES version 300. If you\nare using WebGL 1 instead of 2, write your hooks in GLSL ES 100 instead.
\nCall baseStrokeShader().inspectHooks()
to see all the possible hooks and\ntheir default implementations.
\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseStrokeShader().modify({\n 'Inputs getPixelInputs': `(Inputs inputs) {\n float opacity = 1.0 - smoothstep(\n 0.0,\n 15.0,\n length(inputs.position - inputs.center)\n );\n inputs.color *= opacity;\n return inputs;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n strokeWeight(30);\n line(\n -width/3,\n sin(millis()*0.001) * height/4,\n width/3,\n sin(millis()*0.001 + 1) * height/4\n );\n}\n
\n\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseStrokeShader().modify({\n uniforms: {\n 'float time': () => millis()\n },\n declarations: 'vec3 myPosition;',\n 'vec3 getWorldPosition': `(vec3 pos) {\n myPosition = pos;\n return pos;\n }`,\n 'float getStrokeWeight': `(float w) {\n // Add a somewhat random offset to the weight\n // that varies based on position and time\n float scale = 0.8 + 0.2*sin(10.0 * sin(\n floor(time/250.) +\n myPosition.x*0.01 +\n myPosition.y*0.01\n ));\n return w * scale;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n myShader.setUniform('time', millis());\n strokeWeight(10);\n beginShape();\n for (let i = 0; i <= 50; i++) {\n let r = map(i, 0, 50, 0, width/3);\n let x = r*cos(i*0.2);\n let y = r*sin(i*0.2);\n vertex(x, y);\n }\n endShape();\n}\n
\n\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseStrokeShader().modify({\n 'float random': `(vec2 p) {\n vec3 p3 = fract(vec3(p.xyx) * .1031);\n p3 += dot(p3, p3.yzx + 33.33);\n return fract((p3.x + p3.y) * p3.z);\n }`,\n 'Inputs getPixelInputs': `(Inputs inputs) {\n // Replace alpha in the color with dithering by\n // randomly setting pixel colors to 0 based on opacity\n float a = inputs.color.a;\n inputs.color.a = 1.0;\n inputs.color *= random(inputs.position.xy) > a ? 0.0 : 1.0;\n return inputs;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n strokeWeight(10);\n beginShape();\n for (let i = 0; i <= 50; i++) {\n stroke(\n 0,\n 255\n * map(i, 0, 20, 0, 1, true)\n * map(i, 30, 50, 1, 0, true)\n );\n vertex(\n map(i, 0, 50, -1, 1) * width/3,\n 50 * sin(i/10 + frameCount/100)\n );\n }\n endShape();\n}\n
\nUna clase para describir un programa de sombreado.
\nCada objeto p5.Shader
contiene un programa de sombreado que se ejecuta en la unidad de procesamiento gráfico (GPU). Los sombreadores pueden procesar muchos píxeles o vértices al mismo tiempo, lo que los hace rápidos para muchas tareas gráficas. Están escritos en un lenguaje llamado GLSL y se ejecutan junto con el resto del código en un sketch.
Un programa de sombreado consta de dos archivos, un sombreador de vértices y un sombreador de fragmentos. El sombreador de vértices afecta dónde se dibuja la geometría 3D en la pantalla y el sombreador de fragmentos afecta el color. Una vez que se crea el objeto p5.Shader
, se puede usar con la función shader(), como en shader(myShader)
.
Nota: createShader(), createFilterShader() y loadShader() son las formas recomendadas de crear una instancia de esta clase.
\n"],"line":[0,11],"params":[1,[[0,{"name":[0,"renderer"],"description":[0,"Contexto WebGL para este sombreador.
\n"],"type":[0,"p5.RendererGL"]}],[0,{"name":[0,"vertSrc"],"description":[0,"Código fuente para el programa de sombreado de vértices.
\n"],"type":[0,"String"]}],[0,{"name":[0,"fragSrc"],"description":[0,"Código fuente para el programa de sombreado de fragmentos.
\n"],"type":[0,"String"]}]]],"chainable":[0,false],"example":[1,[[0,"\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision highp float;\n\nvoid main() {\n // Set each pixel's RGBA value to yellow.\n gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);\n}\n`;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Shader object.\n let myShader = createShader(vertSrc, fragSrc);\n\n // Apply the p5.Shader object.\n shader(myShader);\n\n // Style the drawing surface.\n noStroke();\n\n // Add a plane as a drawing surface.\n plane(100, 100);\n\n describe('A yellow square.');\n}\n
\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\nlet mandelbrot;\n\n// Load the shader and create a p5.Shader object.\nfunction preload() {\n mandelbrot = loadShader('/assets/shader.vert', '/assets/shader.frag');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Use the p5.Shader object.\n shader(mandelbrot);\n\n // Set the shader uniform p to an array.\n mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);\n\n describe('A fractal image zooms in and out of focus.');\n}\n\nfunction draw() {\n // Set the shader uniform r to a value that oscillates between 0 and 2.\n mandelbrot.setUniform('r', sin(frameCount * 0.01) + 1);\n\n // Add a quad as a display surface for the shader.\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n
\nCopia el sombreador de un contexto de dibujo a otro.
\nCada objeto p5.Shader
debe ser compilado llamando a la función shader() antes de poder ejecutarse. La compilación se realiza en un contexto de dibujo que generalmente es el lienzo principal o una instancia de p5.Graphics. Un sombreador solo se puede usar en el contexto donde se compiló. El método copyToContext()
vuelve a compilar el sombreador y lo copia a otro contexto de dibujo donde se puede reutilizar.
El parámetro context
es el contexto de dibujo donde se utilizará el sombreador. El sombreador se puede copiar a una instancia de p5.Graphics, como en myShader.copyToContext(pg)
. También se puede copiar el sombreador desde un objeto p5.Graphics al lienzo principal utilizando la variable window
, como en myShader.copyToContext(window)
.
Nota: Un objeto p5.Shader creado con createShader(), createFilterShader() o loadShader() se puede utilizar directamente con un objeto p5.Framebuffer creado con createFramebuffer(). Ambos objetos tienen el mismo contexto que el lienzo principal.
\n"],"path":[0,"p5.Shader/copyToContext"]}],"setUniform":[0,{"description":[0,"Establece las variables uniformes (globales) del sombreador.
\nLos programas de sombreado se ejecutan en la unidad de procesamiento gráfico (GPU) de la computadora.\nViven en una parte de la memoria de la computadora que es completamente separada\ndel sketch que los ejecuta. Las variables uniformes son variables globales dentro de un\nprograma de sombreado. Proporcionan una forma de pasar valores desde un sketch que se ejecuta\nen la CPU a un programa de sombreado que se ejecuta en la GPU.
\nEl primer parámetro, uniformName
, es una cadena con el nombre de la variable uniforme.\nPara el sombreador anterior, uniformName
sería 'r'
.
El segundo parámetro, data
, es el valor que se debe utilizar para establecer la\nvariable uniforme. Por ejemplo, llamar a myShader.setUniform('r', 0.5)
establecería\nla variable uniforme r
en el sombreador anterior a 0.5
. data debe coincidir con el\ntipo de la variable uniforme. Números, cadenas, booleanos, matrices y muchos tipos de\nimágenes se pueden pasar a un sombreador con setUniform()
.
Copia el shader de un contexto de dibujo a otro.
\nCada objeto p5.Shader
debe ser compilado llamando a la función shader() antes de poder ejecutarse. La compilación ocurre en un contexto de dibujo que generalmente es el lienzo principal o una instancia de p5.Graphics. Un shader solo puede ser utilizado en el contexto donde fue compilado. El método copyToContext()
compila el shader nuevamente y lo copia a otro contexto de dibujo donde puede ser reutilizado.
El parámetro context
es el contexto de dibujo donde se utilizará el shader. El shader puede ser copiado a una instancia de p5.Graphics, como en miShader.copyToContext(pg)
. El shader también puede ser copiado desde un objeto p5.Graphics al lienzo principal utilizando la variable window
, como en miShader.copyToContext(window)
.
Nota: Un objeto p5.Shader creado con createShader(), createFilterShader() o loadShader() puede ser utilizado directamente con un objeto p5.Framebuffer creado con createFramebuffer(). Ambos objetos tienen el mismo contexto que el lienzo principal.
\n"],"line":[0,211],"params":[1,[[0,{"name":[0,"context"],"description":[0,"Contexto WebGL para el shader copiado.
\n"],"type":[0,"p5|p5.Graphics"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Shader"],"chainable":[0,false],"return":[0,{"description":[0,"nuevo shader compilado para el contexto objetivo."],"type":[0,"p5.Shader"]}],"example":[1,[[0,"\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision mediump float;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vec2 uv = vTexCoord;\n vec3 color = vec3(uv.x, uv.y, min(uv.x + uv.y, 1.0));\n gl_FragColor = vec4(color, 1.0);\\\n}\n`;\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // Create a p5.Shader object.\n let original = createShader(vertSrc, fragSrc);\n\n // Compile the p5.Shader object.\n shader(original);\n\n // Create a p5.Graphics object.\n pg = createGraphics(50, 50, WEBGL);\n\n // Copy the original shader to the p5.Graphics object.\n let copied = original.copyToContext(pg);\n\n // Apply the copied shader to the p5.Graphics object.\n pg.shader(copied);\n\n // Style the display surface.\n pg.noStroke();\n\n // Add a display surface for the shader.\n pg.plane(50, 50);\n\n describe('A square with purple-blue gradient on its surface drawn against a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw the p5.Graphics object to the main canvas.\n image(pg, -25, -25);\n}\n
\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision mediump float;\n\nvarying vec2 vTexCoord;\n\nvoid main() {\n vec2 uv = vTexCoord;\n vec3 color = vec3(uv.x, uv.y, min(uv.x + uv.y, 1.0));\n gl_FragColor = vec4(color, 1.0);\n}\n`;\n\nlet copied;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Graphics object.\n let pg = createGraphics(25, 25, WEBGL);\n\n // Create a p5.Shader object.\n let original = pg.createShader(vertSrc, fragSrc);\n\n // Compile the p5.Shader object.\n pg.shader(original);\n\n // Copy the original shader to the main canvas.\n copied = original.copyToContext(window);\n\n // Apply the copied shader to the main canvas.\n shader(copied);\n\n describe('A rotating cube with a purple-blue gradient on its surface drawn against a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Rotate around the x-, y-, and z-axes.\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n\n // Draw the box.\n box(50);\n}\n
\nEstablece los valores de las variables uniformes (globales) del shader.
\nLos shaders corren en parte de la memoria del computador que es separada\ndel sketch que los ejecuta. Las variables uniformes son variables globales\ndentro de un programa de shader. Permiten pasar valores del sketch que se está\nejecutando en el CPU al programa de shader que se está ejecutando en el GPU.
\nEl primer parámetro, uniformName
, es una string con el nombre de la variable uniform.\nEn el shader anterior, uniformName
sería 'r'
.
El segundo parámetro, data
, es el valor que se debe usar para establecer la\nvariable uniform. Por ejemplo, llamar a myShader.setUniform('r', 0.5)
establecería\nla variable uniform r
en el shader anterior a 0.5
. data
debe coincidir con el tipo de dato de la variable uniform. Números, string, booleanos, arreglos y muchos tipos de imágenes\npueden pasarse a un shader con setUniform()
.
Nombre del uniform. Debe coincidir con el\n nombre utilizado en los shaders vertex y fragment.
\n"],"type":[0,"String"]}],[0,{"name":[0,"data"],"description":[0,"Valor a asignar al uniform. Debe coincidir con el tipo de dato del uniform.
\n"],"type":[0,"Boolean|Number|Number[]|p5.Image|p5.Graphics|p5.MediaElement|p5.Texture"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Shader"],"chainable":[0,true],"example":[1,[[0,"\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision mediump float;\n\nuniform float r;\n\nvoid main() {\n gl_FragColor = vec4(r, 1.0, 1.0, 1.0);\n}\n`;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Shader object.\n let myShader = createShader(vertSrc, fragSrc);\n\n // Apply the p5.Shader object.\n shader(myShader);\n\n // Set the r uniform to 0.5.\n myShader.setUniform('r', 0.5);\n\n // Style the drawing surface.\n noStroke();\n\n // Add a plane as a drawing surface for the shader.\n plane(100, 100);\n\n describe('A cyan square.');\n}\n
\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision mediump float;\n\nuniform float r;\n\nvoid main() {\n gl_FragColor = vec4(r, 1.0, 1.0, 1.0);\n}\n`;\n\nlet myShader;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Shader object.\n myShader = createShader(vertSrc, fragSrc);\n\n // Compile and apply the p5.Shader object.\n shader(myShader);\n\n describe('A square oscillates color between cyan and white.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the drawing surface.\n noStroke();\n\n // Update the r uniform.\n let nextR = 0.5 * (sin(frameCount * 0.01) + 1);\n myShader.setUniform('r', nextR);\n\n // Add a plane as a drawing surface.\n plane(100, 100);\n}\n
\n\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vTexCoord = aTexCoord;\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision highp float;\nuniform vec2 p;\nuniform float r;\nconst int numIterations = 500;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vec2 c = p + gl_FragCoord.xy * r;\n vec2 z = c;\n float n = 0.0;\n\n for (int i = numIterations; i > 0; i--) {\n if (z.x * z.x + z.y * z.y > 4.0) {\n n = float(i) / float(numIterations);\n break;\n }\n\n z = vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + c;\n }\n\n gl_FragColor = vec4(\n 0.5 - cos(n * 17.0) / 2.0,\n 0.5 - cos(n * 13.0) / 2.0,\n 0.5 - cos(n * 23.0) / 2.0,\n 1.0\n );\n}\n`;\n\nlet mandelbrot;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Shader object.\n mandelbrot = createShader(vertSrc, fragSrc);\n\n // Compile and apply the p5.Shader object.\n shader(mandelbrot);\n\n // Set the shader uniform p to an array.\n // p is the center point of the Mandelbrot image.\n mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);\n\n describe('A fractal image zooms in and out of focus.');\n}\n\nfunction draw() {\n // Set the shader uniform r to a value that oscillates\n // between 0 and 0.005.\n // r is the size of the image in Mandelbrot-space.\n let radius = 0.005 * (sin(frameCount * 0.01) + 1);\n mandelbrot.setUniform('r', radius);\n\n // Style the drawing surface.\n noStroke();\n\n // Add a plane as a drawing surface.\n plane(100, 100);\n}\n
\nLogs the hooks available in this shader, and their current implementation.
\nEach shader may let you override bits of its behavior. Each bit is called\na hook. A hook is either for the vertex shader, if it affects the\nposition of vertices, or in the fragment shader, if it affects the pixel\ncolor. This method logs those values to the console, letting you know what\nyou are able to use in a call to\nmodify()
.
For example, this shader will produce the following output:
\nmyShader = baseMaterialShader().modify({\n declarations: 'uniform float time;',\n 'vec3 getWorldPosition': `(vec3 pos) {\n pos.y += 20. * sin(time * 0.001 + pos.x * 0.05);\n return pos;\n }`\n});\nmyShader.inspectHooks();\n
\n==== Vertex shader hooks: ====\nvoid beforeVertex() {}\nvec3 getLocalPosition(vec3 position) { return position; }\n[MODIFIED] vec3 getWorldPosition(vec3 pos) {\n pos.y += 20. * sin(time * 0.001 + pos.x * 0.05);\n return pos;\n }\nvec3 getLocalNormal(vec3 normal) { return normal; }\nvec3 getWorldNormal(vec3 normal) { return normal; }\nvec2 getUV(vec2 uv) { return uv; }\nvec4 getVertexColor(vec4 color) { return color; }\nvoid afterVertex() {}\n\n==== Fragment shader hooks: ====\nvoid beforeFragment() {}\nInputs getPixelInputs(Inputs inputs) { return inputs; }\nvec4 combineColors(ColorComponents components) {\n vec4 color = vec4(0.);\n color.rgb += components.diffuse * components.baseColor;\n color.rgb += components.ambient * components.ambientColor;\n color.rgb += components.specular * components.specularColor;\n color.rgb += components.emissive;\n color.a = components.opacity;\n return color;\n }\nvec4 getFinalColor(vec4 color) { return color; }\nvoid afterFragment() {}\n
\n"],"line":[0,259],"itemtype":[0,"method"],"class":[0,"p5.Shader"],"chainable":[0,false],"beta":[0,true],"isConstructor":[0,false],"path":[0,"p5.Shader/inspectHooks"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Shader/modify.mdx"],"slug":[0,"en/p5shader/modify"],"body":[0,"\n\n# modify\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"modify()"],"module":[0,"3D"],"submodule":[0,"Material"],"file":[0,"src/webgl/p5.Shader.js"],"description":[0,"Returns a new shader, based on the original, but with custom snippets\nof shader code replacing default behaviour.
\nEach shader may let you override bits of its behavior. Each bit is called\na hook. A hook is either for the vertex shader, if it affects the\nposition of vertices, or in the fragment shader, if it affects the pixel\ncolor. You can inspect the different hooks available by calling\nyourShader.inspectHooks()
. You can\nalso read the reference for the default material, normal material, color, line, and point shaders to\nsee what hooks they have available.
modify()
takes one parameter, hooks
, an object with the hooks you want\nto override. Each key of the hooks
object is the name\nof a hook, and the value is a string with the GLSL code for your hook.
If you supply functions that aren't existing hooks, they will get added at the start of\nthe shader as helper functions so that you can use them in your hooks.
\nTo add new uniforms to your shader, you can pass in a uniforms
object containing\nthe type and name of the uniform as the key, and a default value or function returning\na default value as its value. These will be automatically set when the shader is set\nwith shader(yourShader)
.
You can also add a declarations
key, where the value is a GLSL string declaring\ncustom uniform variables, globals, and functions shared\nbetween hooks. To add declarations just in a vertex or fragment shader, add\nvertexDeclarations
and fragmentDeclarations
keys.
The hooks in the shader to replace.
\n"],"type":[0,"Object"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Shader"],"chainable":[0,false],"beta":[0,true],"return":[0,{"description":[0,""],"type":[0,"p5.Shader"]}],"example":[1,[[0,"\n\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseMaterialShader().modify({\n uniforms: {\n 'float time': () => millis()\n },\n 'vec3 getWorldPosition': `(vec3 pos) {\n pos.y += 20. * sin(time * 0.001 + pos.x * 0.05);\n return pos;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n lights();\n noStroke();\n fill('red');\n sphere(50);\n}\n
\n\nlet myShader;\n\nfunction setup() {\n createCanvas(200, 200, WEBGL);\n myShader = baseMaterialShader().modify({\n // Manually specifying a uniform\n declarations: 'uniform float time;',\n 'vec3 getWorldPosition': `(vec3 pos) {\n pos.y += 20. * sin(time * 0.001 + pos.x * 0.05);\n return pos;\n }`\n });\n}\n\nfunction draw() {\n background(255);\n shader(myShader);\n myShader.setUniform('time', millis());\n lights();\n noStroke();\n fill('red');\n sphere(50);\n}\n
\nSets the way colors blend when added to the canvas.
\nBy default, drawing with a solid color paints over the current pixel values\non the canvas. blendMode()
offers many options for blending colors.
Shapes, images, and text can be used as sources for drawing to the canvas.\nA source pixel changes the color of the canvas pixel where it's drawn. The\nfinal color results from blending the source pixel's color with the canvas\npixel's color. RGB color values from the source and canvas pixels are\ncompared, added, subtracted, multiplied, and divided to create different\neffects. Red values with red values, greens with greens, and blues with\nblues.
\nThe parameter, mode
, sets the blend mode. For example, calling\nblendMode(ADD)
sets the blend mode to ADD
. The following blend modes\nare available in both 2D and WebGL mode:
BLEND
: color values from the source overwrite the canvas. This is the default mode.ADD
: color values from the source are added to values from the canvas.DARKEST
: keeps the darkest color value.LIGHTEST
: keeps the lightest color value.EXCLUSION
: similar to DIFFERENCE
but with less contrast.MULTIPLY
: color values from the source are multiplied with values from the canvas. The result is always darker.SCREEN
: all color values are inverted, then multiplied, then inverted again. The result is always lighter. (Opposite of MULTIPLY
)REPLACE
: the last source drawn completely replaces the rest of the canvas.REMOVE
: overlapping pixels are removed by making them completely transparent.The following blend modes are only available in 2D mode:
\nDIFFERENCE
: color values from the source are subtracted from the values from the canvas. If the difference is a negative number, it's made positive.OVERLAY
: combines MULTIPLY
and SCREEN
. Dark values in the canvas get darker and light values get lighter.HARD_LIGHT
: combines MULTIPLY
and SCREEN
. Dark values in the source get darker and light values get lighter.SOFT_LIGHT
: a softer version of HARD_LIGHT
.DODGE
: lightens light tones and increases contrast. Divides the canvas color values by the inverted color values from the source.BURN
: darkens dark tones and increases contrast. Divides the source color values by the inverted color values from the canvas, then inverts the result.The following blend modes are only available in WebGL mode:
\nSUBTRACT
: RGB values from the source are subtracted from the values from the canvas. If the difference is a negative number, it's made positive. Alpha (transparency) values from the source and canvas are added.blend mode to set.\n either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY,\n EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD, REMOVE or SUBTRACT
\n"],"type":[0,"Constant"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Use the default blend mode.\n blendMode(BLEND);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('A Sky Blue line and a Deep Rose line form an X on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(HARD_LIGHT);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('An ocean blue line and a hot pink line form an X on a gray background. The area where they overlap is Magenta purple.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(ADD);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('An icy blue line and a light lavender line form an X on a gray background. The area where they overlap is white.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(DARKEST);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('A steel blue line and a cranberry line form an X on a gray background. The area where they overlap is deep purple.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(BURN);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('A cobalt blue line and a burgundy line form an X on a gray background. The area where they overlap is black.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(LIGHTEST);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('A pale lavender line and a soft beige line form an X on a gray background. The area where they overlap is pale lilac.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(EXCLUSION);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('An earthy brown line and a muted sage line form an X on a gray background. The area where they overlap is sage green.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(MULTIPLY);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('A slate blue line and a plum line form an X on a gray background. The area where they overlap is dark Indigo.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(SCREEN);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('A baby blue line and a peach pink line form an X on a gray background. The area where they overlap is misty lilac.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(REPLACE);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('A diagonal deep rose line.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(REMOVE);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('The silhouette of an X is missing from a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(DIFFERENCE);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('A light burgundy line and a forest green line form an X on a gray background. The area where they overlap is dark cocoa.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(OVERLAY);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('A cornflower blue line and a light rose line form an X on a gray background. The area where they overlap is violet.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(SOFT_LIGHT);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('A pale sky line and a rose blush line form an X on a gray background. The area where they overlap is lavender.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Set the blend mode.\n blendMode(DODGE);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the first line.\n stroke('#1a85ff');\n line(25, 25, 75, 75);\n\n // Draw the second line.\n stroke('#d41159');\n line(75, 25, 25, 75);\n\n describe('An aqua blue line and a light pink line form an X on a gray background. The area where they overlap is white.');\n}\n
\n\nfunction setup() {\n // Create a canvas with WEBGL mode.\n createCanvas(100, 100, WEBGL);\n\n // Set the background color.\n background(180);\n\n // Set the blend mode to SUBTRACT.\n blendMode(SUBTRACT);\n\n // Style the lines.\n strokeWeight(30);\n\n // Draw the blue line.\n stroke('#1a85ff');\n line(-25, -25, 25, 25);\n\n // Draw the red line.\n stroke('#d41159');\n line(25, -25, -25, 25);\n\n describe('A burnt orange and a sea green line form an X on a gray background. The area where they overlap is forest green.');\n}\n
\nClears the depth buffer in WebGL mode.
\nclearDepth()
clears information about how far objects are from the camera\nin 3D space. This information is stored in an object called the\ndepth buffer. Clearing the depth buffer ensures new objects aren't drawn\nbehind old ones. Doing so can be useful for feedback effects in which the\nprevious frame serves as the background for the current frame.
The parameter, depth
, is optional. If a number is passed, as in\nclearDepth(0.5)
, it determines the range of objects to clear from the\ndepth buffer. 0 doesn't clear any depth information, 0.5 clears depth\ninformation halfway between the near and far clipping planes, and 1 clears\ndepth information all the way to the far clipping plane. By default,\ndepth
is 1.
Note: clearDepth()
can only be used in WebGL mode.
amount of the depth buffer to clear between 0\n (none) and 1 (far clipping plane). Defaults to 1.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nlet previous;\nlet current;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create the p5.Framebuffer objects.\n previous = createFramebuffer({ format: FLOAT });\n current = createFramebuffer({ format: FLOAT });\n\n describe(\n 'A multicolor box drifts from side to side on a white background. It leaves a trail that fades over time.'\n );\n}\n\nfunction draw() {\n // Swap the previous p5.Framebuffer and the\n // current one so it can be used as a texture.\n [previous, current] = [current, previous];\n\n // Start drawing to the current p5.Framebuffer.\n current.begin();\n\n // Paint the background.\n background(255);\n\n // Draw the previous p5.Framebuffer.\n // Clear the depth buffer so the previous\n // frame doesn't block the current one.\n push();\n tint(255, 250);\n image(previous, -50, -50);\n clearDepth();\n pop();\n\n // Draw the box on top of the previous frame.\n push();\n let x = 25 * sin(frameCount * 0.01);\n let y = 25 * sin(frameCount * 0.02);\n translate(x, y, 0);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n normalMaterial();\n box(12);\n pop();\n\n // Stop drawing to the current p5.Framebuffer.\n current.end();\n\n // Display the current p5.Framebuffer.\n image(current, -50, -50);\n}\n
\nCreates a canvas element on the web page.
\ncreateCanvas()
creates the main drawing canvas for a sketch. It should\nonly be called once at the beginning of setup().\nCalling createCanvas()
more than once causes unpredictable behavior.
The first two parameters, width
and height
, are optional. They set the\ndimensions of the canvas and the values of the\nwidth and height system\nvariables. For example, calling createCanvas(900, 500)
creates a canvas\nthat's 900×500 pixels. By default, width
and height
are both 100.
The third parameter is also optional. If either of the constants P2D
or\nWEBGL
is passed, as in createCanvas(900, 500, WEBGL)
, then it will set\nthe sketch's rendering mode. If an existing\nHTMLCanvasElement\nis passed, as in createCanvas(900, 500, myCanvas)
, then it will be used\nby the sketch.
The fourth parameter is also optional. If an existing\nHTMLCanvasElement\nis passed, as in createCanvas(900, 500, WEBGL, myCanvas)
, then it will be\nused by the sketch.
Note: In WebGL mode, the canvas will use a WebGL2 context if it's supported\nby the browser. Check the webglVersion\nsystem variable to check what version is being used, or call\nsetAttributes({ version: 1 })
to create a WebGL1 context.
width of the canvas. Defaults to 100.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"height"],"description":[0,"height of the canvas. Defaults to 100.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"renderer"],"description":[0,"either P2D or WEBGL. Defaults to P2D
.
existing canvas element that should be used for the sketch.
\n"],"type":[0,"HTMLCanvasElement"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"width"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"height"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"canvas"],"description":[0,""],"type":[0,"HTMLCanvasElement"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new `p5.Renderer` that holds the canvas."],"type":[0,"p5.Renderer"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Draw a diagonal line.\n line(0, 0, width, height);\n\n describe('A diagonal line drawn from top-left to bottom-right on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 50);\n\n background(180);\n\n // Draw a diagonal line.\n line(0, 0, width, height);\n\n describe('A diagonal line drawn from top-left to bottom-right on a gray background.');\n}\n
\n\n// Use WebGL mode.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(180);\n\n // Draw a diagonal line.\n line(-width / 2, -height / 2, width / 2, height / 2);\n\n describe('A diagonal line drawn from top-left to bottom-right on a gray background.');\n}\n
\n\nfunction setup() {\n // Create a p5.Render object.\n let cnv = createCanvas(50, 50);\n\n // Position the canvas.\n cnv.position(10, 20);\n\n background(180);\n\n // Draw a diagonal line.\n line(0, 0, width, height);\n\n describe('A diagonal line drawn from top-left to bottom-right on a gray background.');\n}\n
\nCreates and a new p5.Framebuffer object.
\np5.Framebuffer objects are separate drawing\nsurfaces that can be used as textures in WebGL mode. They're similar to\np5.Graphics objects and generally run much\nfaster when used as textures.
\nThe parameter, options
, is optional. An object can be passed to configure\nthe p5.Framebuffer object. The available\nproperties are:
format
: data format of the texture, either UNSIGNED_BYTE
, FLOAT
, or HALF_FLOAT
. Default is UNSIGNED_BYTE
.channels
: whether to store RGB
or RGBA
color channels. Default is to match the main canvas which is RGBA
.depth
: whether to include a depth buffer. Default is true
.depthFormat
: data format of depth information, either UNSIGNED_INT
or FLOAT
. Default is FLOAT
.stencil
: whether to include a stencil buffer for masking. depth
must be true
for this feature to work. Defaults to the value of depth
which is true
.antialias
: whether to perform anti-aliasing. If set to true
, as in { antialias: true }
, 2 samples will be used by default. The number of samples can also be set, as in { antialias: 4 }
. Default is to match setAttributes() which is false
(true
in Safari).width
: width of the p5.Framebuffer object. Default is to always match the main canvas width.height
: height of the p5.Framebuffer object. Default is to always match the main canvas height.density
: pixel density of the p5.Framebuffer object. Default is to always match the main canvas pixel density.textureFiltering
: how to read values from the p5.Framebuffer object. Either LINEAR
(nearby pixels will be interpolated) or NEAREST
(no interpolation). Generally, use LINEAR
when using the texture as an image and NEAREST
if reading the texture as data. Default is LINEAR
.If the width
, height
, or density
attributes are set, they won't automatically match the main canvas and must be changed manually.
Note: createFramebuffer()
can only be used in WebGL mode.
configuration options.
\n"],"type":[0,"Object"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new framebuffer."],"type":[0,"p5.Framebuffer"]}],"example":[1,[[0,"\n\nlet myBuffer;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n describe('A grid of white toruses rotating against a dark gray background.');\n}\n\nfunction draw() {\n background(50);\n\n // Start drawing to the p5.Framebuffer object.\n myBuffer.begin();\n\n // Clear the drawing surface.\n clear();\n\n // Turn on the lights.\n lights();\n\n // Rotate the coordinate system.\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n\n // Style the torus.\n noStroke();\n\n // Draw the torus.\n torus(20);\n\n // Stop drawing to the p5.Framebuffer object.\n myBuffer.end();\n\n // Iterate from left to right.\n for (let x = -50; x < 50; x += 25) {\n // Iterate from top to bottom.\n for (let y = -50; y < 50; y += 25) {\n // Draw the p5.Framebuffer object to the canvas.\n image(myBuffer, x, y, 25, 25);\n }\n }\n}\n
\n\nlet myBuffer;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create an options object.\n let options = { width: 25, height: 25 };\n\n // Create a p5.Framebuffer object.\n // Use options for configuration.\n myBuffer = createFramebuffer(options);\n\n describe('A grid of white toruses rotating against a dark gray background.');\n}\n\nfunction draw() {\n background(50);\n\n // Start drawing to the p5.Framebuffer object.\n myBuffer.begin();\n\n // Clear the drawing surface.\n clear();\n\n // Turn on the lights.\n lights();\n\n // Rotate the coordinate system.\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n\n // Style the torus.\n noStroke();\n\n // Draw the torus.\n torus(5, 2.5);\n\n // Stop drawing to the p5.Framebuffer object.\n myBuffer.end();\n\n // Iterate from left to right.\n for (let x = -50; x < 50; x += 25) {\n // Iterate from top to bottom.\n for (let y = -50; y < 50; y += 25) {\n // Draw the p5.Framebuffer object to the canvas.\n image(myBuffer, x, y);\n }\n }\n}\n
\nCreates a p5.Graphics object.
\ncreateGraphics()
creates an offscreen drawing canvas (graphics buffer)\nand returns it as a p5.Graphics object. Drawing\nto a separate graphics buffer can be helpful for performance and for\norganizing code.
The first two parameters, width
and height
, are optional. They set the\ndimensions of the p5.Graphics object. For\nexample, calling createGraphics(900, 500)
creates a graphics buffer\nthat's 900×500 pixels.
The third parameter is also optional. If either of the constants P2D
or\nWEBGL
is passed, as in createGraphics(900, 500, WEBGL)
, then it will set\nthe p5.Graphics object's rendering mode. If an\nexisting\nHTMLCanvasElement\nis passed, as in createGraphics(900, 500, myCanvas)
, then it will be used\nby the graphics buffer.
The fourth parameter is also optional. If an existing\nHTMLCanvasElement\nis passed, as in createGraphics(900, 500, WEBGL, myCanvas)
, then it will be\nused by the graphics buffer.
Note: In WebGL mode, the p5.Graphics object\nwill use a WebGL2 context if it's supported by the browser. Check the\nwebglVersion system variable to check what\nversion is being used, or call setAttributes({ version: 1 })
to create a\nWebGL1 context.
width of the graphics buffer.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"height"],"description":[0,"height of the graphics buffer.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"renderer"],"description":[0,"either P2D or WEBGL. Defaults to P2D.
\n"],"type":[0,"Constant"],"optional":[0,true]}],[0,{"name":[0,"canvas"],"description":[0,"existing canvas element that should be\n used for the graphics buffer..
\n"],"type":[0,"HTMLCanvasElement"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"width"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"height"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"canvas"],"description":[0,""],"type":[0,"HTMLCanvasElement"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new graphics buffer."],"type":[0,"p5.Graphics"]}],"example":[1,[[0,"\n\n// Double-click to draw the contents of the graphics buffer.\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Create the p5.Graphics object.\n pg = createGraphics(50, 50);\n\n // Draw to the graphics buffer.\n pg.background(100);\n pg.circle(pg.width / 2, pg.height / 2, 20);\n\n describe('A gray square. A smaller, darker square with a white circle at its center appears when the user double-clicks.');\n}\n\n// Display the graphics buffer when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n image(pg, 25, 25);\n }\n}\n
\n\n// Double-click to draw the contents of the graphics buffer.\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Create the p5.Graphics object in WebGL mode.\n pg = createGraphics(50, 50, WEBGL);\n\n // Draw to the graphics buffer.\n pg.background(100);\n pg.lights();\n pg.noStroke();\n pg.rotateX(QUARTER_PI);\n pg.rotateY(QUARTER_PI);\n pg.torus(15, 5);\n\n describe('A gray square. A smaller, darker square with a white torus at its center appears when the user double-clicks.');\n}\n\n// Display the graphics buffer when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n image(pg, 25, 25);\n }\n}\n
\nA system variable that provides direct access to the sketch's\n element.
The element provides many specialized features that aren't\nincluded in the p5.js library. The
drawingContext
system variable\nprovides access to these features by exposing the sketch's\nCanvasRenderingContext2D\nobject.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(180);\n\n // Style the circle using shadows.\n drawingContext.shadowOffsetX = 5;\n drawingContext.shadowOffsetY = -5;\n drawingContext.shadowBlur = 10;\n drawingContext.shadowColor = 'black';\n\n // Draw the circle.\n circle(50, 50, 40);\n\n describe(\"A white circle on a gray background. The circle's edges are shadowy.\");\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background('skyblue');\n\n // Style the circle using a color gradient.\n let myGradient = drawingContext.createRadialGradient(50, 50, 3, 50, 50, 40);\n myGradient.addColorStop(0, 'yellow');\n myGradient.addColorStop(0.6, 'orangered');\n myGradient.addColorStop(1, 'yellow');\n drawingContext.fillStyle = myGradient;\n drawingContext.strokeStyle = 'rgba(0, 0, 0, 0)';\n\n // Draw the circle.\n circle(50, 50, 40);\n\n describe('A fiery sun drawn on a light blue background.');\n}\n
\nRemoves the default canvas.
\nBy default, a 100×100 pixels canvas is created without needing to call\ncreateCanvas(). noCanvas()
removes the\ndefault canvas for sketches that don't need it.
\nfunction setup() {\n noCanvas();\n}\n
\nResizes the canvas to a given width and height.
\nresizeCanvas()
immediately clears the canvas and calls\nredraw(). It's common to call resizeCanvas()
\nwithin the body of windowResized() like\nso:
function windowResized() {\n resizeCanvas(windowWidth, windowHeight);\n}\n
\nThe first two parameters, width
and height
, set the dimensions of the\ncanvas. They also the values of the width and\nheight system variables. For example, calling\nresizeCanvas(300, 500)
resizes the canvas to 300×500 pixels, then sets\nwidth to 300 and\nheight 500.
The third parameter, noRedraw
, is optional. If true
is passed, as in\nresizeCanvas(300, 500, true)
, then the canvas will be canvas to 300×500\npixels but the redraw() function won't be called\nimmediately. By default, redraw() is called\nimmediately when resizeCanvas()
finishes executing.
width of the canvas.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"height"],"description":[0,"height of the canvas.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"noRedraw"],"description":[0,"whether to delay calling\n redraw(). Defaults\n to false
.
\n// Double-click to resize the canvas.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A white circle drawn on a gray background. The canvas shrinks by half the first time the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(180);\n\n // Draw a circle at the center of the canvas.\n circle(width / 2, height / 2, 20);\n}\n\n// Resize the canvas when the user double-clicks.\nfunction doubleClicked() {\n resizeCanvas(50, 50);\n}\n
\n\n// Resize the web browser to change the canvas size.\n\nfunction setup() {\n createCanvas(windowWidth, windowHeight);\n\n describe('A white circle drawn on a gray background.');\n}\n\nfunction draw() {\n background(180);\n\n // Draw a circle at the center of the canvas.\n circle(width / 2, height / 2, 20);\n}\n\n// Always resize the canvas to fill the browser window.\nfunction windowResized() {\n resizeCanvas(windowWidth, windowHeight);\n}\n
\nSet attributes for the WebGL Drawing context.\nThis is a way of adjusting how the WebGL\nrenderer works to fine-tune the display and performance.
\nNote that this will reinitialize the drawing context\nif called after the WebGL canvas is made.
\nIf an object is passed as the parameter, all attributes\nnot declared in the object will be set to defaults.
\nThe available attributes are:\n
\nalpha - indicates if the canvas contains an alpha buffer\ndefault is true
depth - indicates whether the drawing buffer has a depth buffer\nof at least 16 bits - default is true
\nstencil - indicates whether the drawing buffer has a stencil buffer\nof at least 8 bits
\nantialias - indicates whether or not to perform anti-aliasing\ndefault is false (true in Safari)
\npremultipliedAlpha - indicates that the page compositor will assume\nthe drawing buffer contains colors with pre-multiplied alpha\ndefault is true
\npreserveDrawingBuffer - if true the buffers will not be cleared and\nand will preserve their values until cleared or overwritten by author\n(note that p5 clears automatically on draw loop)\ndefault is true
\nperPixelLighting - if true, per-pixel lighting will be used in the\nlighting shader otherwise per-vertex lighting is used.\ndefault is true.
\nversion - either 1 or 2, to specify which WebGL version to ask for. By\ndefault, WebGL 2 will be requested. If WebGL2 is not available, it will\nfall back to WebGL 1. You can check what version is used with by looking at\nthe global webglVersion
property.
Name of attribute
\n"],"type":[0,"String"]}],[0,{"name":[0,"value"],"description":[0,"New value of named attribute
\n"],"type":[0,"Boolean"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"obj"],"description":[0,"object with key-value pairs
\n"],"type":[0,"Object"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n
\n\nfunction setup() {\n setAttributes('antialias', true);\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n
\n\n// press the mouse button to disable perPixelLighting\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n fill(255);\n}\n\nlet lights = [\n { c: '#f00', t: 1.12, p: 1.91, r: 0.2 },\n { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 },\n { c: '#00f', t: 1.37, p: 1.57, r: 0.2 },\n { c: '#ff0', t: 1.12, p: 1.91, r: 0.7 },\n { c: '#0ff', t: 1.21, p: 1.31, r: 0.7 },\n { c: '#f0f', t: 1.37, p: 1.57, r: 0.7 }\n];\n\nfunction draw() {\n let t = millis() / 1000 + 1000;\n background(0);\n directionalLight(color('#222'), 1, 1, 1);\n\n for (let i = 0; i < lights.length; i++) {\n let light = lights[i];\n pointLight(\n color(light.c),\n p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r)\n );\n }\n\n specularMaterial(255);\n sphere(width * 0.1);\n\n rotateX(t * 0.77);\n rotateY(t * 0.83);\n rotateZ(t * 0.91);\n torus(width * 0.3, width * 0.07, 24, 10);\n}\n\nfunction mousePressed() {\n setAttributes('perPixelLighting', false);\n noStroke();\n fill(255);\n}\nfunction mouseReleased() {\n setAttributes('perPixelLighting', true);\n noStroke();\n fill(255);\n}\n
\nA class to describe a high-performance drawing surface for textures.
\nEach p5.Framebuffer
object provides a dedicated drawing surface called\na framebuffer. They're similar to\np5.Graphics objects but can run much faster.\nPerformance is improved because the framebuffer shares the same WebGL\ncontext as the canvas used to create it.
p5.Framebuffer
objects have all the drawing features of the main\ncanvas. Drawing instructions meant for the framebuffer must be placed\nbetween calls to\nmyBuffer.begin() and\nmyBuffer.end(). The resulting image\ncan be applied as a texture by passing the p5.Framebuffer
object to the\ntexture() function, as in texture(myBuffer)
.\nIt can also be displayed on the main canvas by passing it to the\nimage() function, as in image(myBuffer, 0, 0)
.
Note: createFramebuffer() is the\nrecommended way to create an instance of this class.
\n"],"line":[0,76],"params":[1,[[0,{"name":[0,"target"],"description":[0,"sketch instance or\n p5.Graphics\n object.
\n"],"type":[0,"p5.Graphics|p5"]}],[0,{"name":[0,"settings"],"description":[0,"configuration options.
\n"],"type":[0,"Object"],"optional":[0,true]}]]],"chainable":[0,false],"methods":[0,{"resize":[0,{"description":[0,"Resizes the framebuffer to a given width and height.
\nThe parameters, width
and height
, set the dimensions of the\nframebuffer. For example, calling myBuffer.resize(300, 500)
resizes\nthe framebuffer to 300×500 pixels, then sets myBuffer.width
to 300\nand myBuffer.height
500.
Sets the framebuffer's pixel density or returns its current density.
\nComputer displays are grids of little lights called pixels. A display's\npixel density describes how many pixels it packs into an area. Displays\nwith smaller pixels have a higher pixel density and create sharper\nimages.
\nThe parameter, density
, is optional. If a number is passed, as in\nmyBuffer.pixelDensity(1)
, it sets the framebuffer's pixel density. By\ndefault, the framebuffer's pixel density will match that of the canvas\nwhere it was created. All canvases default to match the display's pixel\ndensity.
Calling myBuffer.pixelDensity()
without an argument returns its current\npixel density.
Toggles the framebuffer's autosizing mode or returns the current mode.
\nBy default, the framebuffer automatically resizes to match the canvas\nthat created it. Calling myBuffer.autoSized(false)
disables this\nbehavior and calling myBuffer.autoSized(true)
re-enables it.
Calling myBuffer.autoSized()
without an argument returns true
if\nthe framebuffer automatically resizes and false
if not.
Creates a new\np5.Camera object to use with the framebuffer.
\nThe new camera is initialized with a default position (0, 0, 800)
and a\ndefault perspective projection. Its properties can be controlled with\np5.Camera methods such as myCamera.lookAt(0, 0, 0)
.
Framebuffer cameras should be created between calls to\nmyBuffer.begin() and\nmyBuffer.end() like so:
\nlet myCamera;\n\nmyBuffer.begin();\n\n// Create the camera for the framebuffer.\nmyCamera = myBuffer.createCamera();\n\nmyBuffer.end();\n
\nCalling setCamera() updates the\nframebuffer's projection using the camera.\nresetMatrix() must also be called for the\nview to change properly:
\nmyBuffer.begin();\n\n// Set the camera for the framebuffer.\nsetCamera(myCamera);\n\n// Reset all transformations.\nresetMatrix();\n\n// Draw stuff...\n\nmyBuffer.end();\n
\n"],"path":[0,"p5.Framebuffer/createCamera"]}],"remove":[0,{"description":[0,"Deletes the framebuffer from GPU memory.
\nCalling myBuffer.remove()
frees the GPU memory used by the framebuffer.\nThe framebuffer also uses a bit of memory on the CPU which can be freed\nlike so:
// Delete the framebuffer from GPU memory.\nmyBuffer.remove();\n\n// Delete the framebuffer from CPU memory.\nmyBuffer = undefined;\n
\nNote: All variables that reference the framebuffer must be assigned\nthe value undefined
to delete the framebuffer from CPU memory. If any\nvariable still refers to the framebuffer, then it won't be garbage\ncollected.
Begins drawing shapes to the framebuffer.
\nmyBuffer.begin()
and myBuffer.end()\nallow shapes to be drawn to the framebuffer. myBuffer.begin()
begins\ndrawing to the framebuffer and\nmyBuffer.end() stops drawing to the\nframebuffer. Changes won't be visible until the framebuffer is displayed\nas an image or texture.
Stops drawing shapes to the framebuffer.
\nmyBuffer.begin() and myBuffer.end()
\nallow shapes to be drawn to the framebuffer.\nmyBuffer.begin() begins drawing to\nthe framebuffer and myBuffer.end()
stops drawing to the framebuffer.\nChanges won't be visible until the framebuffer is displayed as an image\nor texture.
Draws to the framebuffer by calling a function that contains drawing\ninstructions.
\nThe parameter, callback
, is a function with the drawing instructions\nfor the framebuffer. For example, calling myBuffer.draw(myFunction)
\nwill call a function named myFunction()
to draw to the framebuffer.\nDoing so has the same effect as the following:
myBuffer.begin();\nmyFunction();\nmyBuffer.end();\n
\n"],"path":[0,"p5.Framebuffer/draw"]}],"loadPixels":[0,{"description":[0,"Loads the current value of each pixel in the framebuffer into its\npixels array.
\nmyBuffer.loadPixels()
must be called before reading from or writing to\nmyBuffer.pixels.
Gets a pixel or a region of pixels from the framebuffer.
\nmyBuffer.get()
is easy to use but it's not as fast as\nmyBuffer.pixels. Use\nmyBuffer.pixels to read many pixel\nvalues.
The version of myBuffer.get()
with no parameters returns the entire\nframebuffer as a a p5.Image object.
The version of myBuffer.get()
with two parameters interprets them as\ncoordinates. It returns an array with the [R, G, B, A]
values of the\npixel at the given point.
The version of myBuffer.get()
with four parameters interprets them as\ncoordinates and dimensions. It returns a subsection of the framebuffer as\na p5.Image object. The first two parameters are\nthe coordinates for the upper-left corner of the subsection. The last two\nparameters are the width and height of the subsection.
Updates the framebuffer with the RGBA values in the\npixels array.
\nmyBuffer.updatePixels()
only needs to be called after changing values\nin the myBuffer.pixels array. Such\nchanges can be made directly after calling\nmyBuffer.loadPixels().
An array containing the color of each pixel in the framebuffer.
\nmyBuffer.loadPixels() must be\ncalled before accessing the myBuffer.pixels
array.\nmyBuffer.updatePixels()\nmust be called after any changes are made.
Note: Updating pixels via this property is slower than drawing to the\nframebuffer directly. Consider using a\np5.Shader object instead of looping over\nmyBuffer.pixels
.
An object that stores the framebuffer's color data.
\nEach framebuffer uses a\nWebGLTexture\nobject internally to store its color data. The myBuffer.color
property\nmakes it possible to pass this data directly to other functions. For\nexample, calling texture(myBuffer.color)
or\nmyShader.setUniform('colorTexture', myBuffer.color)
may be helpful for\nadvanced use cases.
Note: By default, a framebuffer's y-coordinates are flipped compared to\nimages and videos. It's easy to flip a framebuffer's y-coordinates as\nneeded when applying it as a texture. For example, calling\nplane(myBuffer.width, -myBuffer.height)
will flip the framebuffer.
An object that stores the framebuffer's depth data.
\nEach framebuffer uses a\nWebGLTexture\nobject internally to store its depth data. The myBuffer.depth
property\nmakes it possible to pass this data directly to other functions. For\nexample, calling texture(myBuffer.depth)
or\nmyShader.setUniform('depthTexture', myBuffer.depth)
may be helpful for\nadvanced use cases.
Note: By default, a framebuffer's y-coordinates are flipped compared to\nimages and videos. It's easy to flip a framebuffer's y-coordinates as\nneeded when applying it as a texture. For example, calling\nplane(myBuffer.width, -myBuffer.height)
will flip the framebuffer.
Toggles the framebuffer's autosizing mode or returns the current mode.
\nBy default, the framebuffer automatically resizes to match the canvas\nthat created it. Calling myBuffer.autoSized(false)
disables this\nbehavior and calling myBuffer.autoSized(true)
re-enables it.
Calling myBuffer.autoSized()
without an argument returns true
if\nthe framebuffer automatically resizes and false
if not.
whether to automatically resize the framebuffer to match the canvas.
\n"],"type":[0,"Boolean"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Framebuffer"],"chainable":[0,false],"return":[0,{"description":[0,"current autosize setting."],"type":[0,"Boolean"]}],"example":[1,[[0,"\n\n// Double-click to toggle the autosizing mode.\n\nlet myBuffer;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n describe('A multicolor sphere on a gray background. The image resizes when the user moves the mouse.');\n}\n\nfunction draw() {\n background(50);\n\n // Draw to the p5.Framebuffer object.\n myBuffer.begin();\n background(200);\n normalMaterial();\n sphere(width / 4);\n myBuffer.end();\n\n // Display the p5.Framebuffer object.\n image(myBuffer, -width / 2, -height / 2);\n}\n\n// Resize the canvas when the user moves the mouse.\nfunction mouseMoved() {\n let w = constrain(mouseX, 0, 100);\n let h = constrain(mouseY, 0, 100);\n resizeCanvas(w, h);\n}\n\n// Toggle autoSizing when the user double-clicks.\n// Note: opened an issue to fix(?) this.\nfunction doubleClicked() {\n let isAuto = myBuffer.autoSized();\n myBuffer.autoSized(!isAuto);\n}\n
\nBegins drawing shapes to the framebuffer.
\nmyBuffer.begin()
and myBuffer.end()\nallow shapes to be drawn to the framebuffer. myBuffer.begin()
begins\ndrawing to the framebuffer and\nmyBuffer.end() stops drawing to the\nframebuffer. Changes won't be visible until the framebuffer is displayed\nas an image or texture.
\nlet myBuffer;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n describe('An empty gray canvas. The canvas gets darker and a rotating, multicolor torus appears while the user presses and holds the mouse.');\n}\n\nfunction draw() {\n background(200);\n\n // Start drawing to the p5.Framebuffer object.\n myBuffer.begin();\n\n background(50);\n rotateY(frameCount * 0.01);\n normalMaterial();\n torus(30);\n\n // Stop drawing to the p5.Framebuffer object.\n myBuffer.end();\n\n // Display the p5.Framebuffer object while\n // the user presses the mouse.\n if (mouseIsPressed === true) {\n image(myBuffer, -50, -50);\n }\n}\n
\nAn object that stores the framebuffer's color data.
\nEach framebuffer uses a\nWebGLTexture\nobject internally to store its color data. The myBuffer.color
property\nmakes it possible to pass this data directly to other functions. For\nexample, calling texture(myBuffer.color)
or\nmyShader.setUniform('colorTexture', myBuffer.color)
may be helpful for\nadvanced use cases.
Note: By default, a framebuffer's y-coordinates are flipped compared to\nimages and videos. It's easy to flip a framebuffer's y-coordinates as\nneeded when applying it as a texture. For example, calling\nplane(myBuffer.width, -myBuffer.height)
will flip the framebuffer.
\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // Create a p5.Framebuffer object.\n let myBuffer = createFramebuffer();\n\n // Start drawing to the p5.Framebuffer object.\n myBuffer.begin();\n\n triangle(-25, 25, 0, -25, 25, 25);\n\n // Stop drawing to the p5.Framebuffer object.\n myBuffer.end();\n\n // Use the p5.Framebuffer object's WebGLTexture.\n texture(myBuffer.color);\n\n // Style the plane.\n noStroke();\n\n // Draw the plane.\n plane(myBuffer.width, myBuffer.height);\n\n describe('A white triangle on a gray background.');\n}\n
\nCreates a new\np5.Camera object to use with the framebuffer.
\nThe new camera is initialized with a default position (0, 0, 800)
and a\ndefault perspective projection. Its properties can be controlled with\np5.Camera methods such as myCamera.lookAt(0, 0, 0)
.
Framebuffer cameras should be created between calls to\nmyBuffer.begin() and\nmyBuffer.end() like so:
\nlet myCamera;\n\nmyBuffer.begin();\n\n// Create the camera for the framebuffer.\nmyCamera = myBuffer.createCamera();\n\nmyBuffer.end();\n
\nCalling setCamera() updates the\nframebuffer's projection using the camera.\nresetMatrix() must also be called for the\nview to change properly:
\nmyBuffer.begin();\n\n// Set the camera for the framebuffer.\nsetCamera(myCamera);\n\n// Reset all transformations.\nresetMatrix();\n\n// Draw stuff...\n\nmyBuffer.end();\n
\n"],"line":[0,892],"itemtype":[0,"method"],"class":[0,"p5.Framebuffer"],"chainable":[0,false],"return":[0,{"description":[0,"new camera."],"type":[0,"p5.Camera"]}],"example":[1,[[0,"\n\n// Double-click to toggle between cameras.\n\nlet myBuffer;\nlet cam1;\nlet cam2;\nlet usingCam1 = true;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n // Create the cameras between begin() and end().\n myBuffer.begin();\n\n // Create the first camera.\n // Keep its default settings.\n cam1 = myBuffer.createCamera();\n\n // Create the second camera.\n // Place it at the top-left.\n // Point it at the origin.\n cam2 = myBuffer.createCamera();\n cam2.setPosition(400, -400, 800);\n cam2.lookAt(0, 0, 0);\n\n myBuffer.end();\n\n describe(\n 'A white cube on a gray background. The camera toggles between frontal and aerial views when the user double-clicks.'\n );\n}\n\nfunction draw() {\n // Draw to the p5.Framebuffer object.\n myBuffer.begin();\n background(200);\n\n // Set the camera.\n if (usingCam1 === true) {\n setCamera(cam1);\n } else {\n setCamera(cam2);\n }\n\n // Reset all transformations.\n resetMatrix();\n\n // Draw the box.\n box();\n\n myBuffer.end();\n\n // Display the p5.Framebuffer object.\n image(myBuffer, -50, -50);\n}\n\n// Toggle the current camera when the user double-clicks.\nfunction doubleClicked() {\n if (usingCam1 === true) {\n usingCam1 = false;\n } else {\n usingCam1 = true;\n }\n}\n
\nAn object that stores the framebuffer's depth data.
\nEach framebuffer uses a\nWebGLTexture\nobject internally to store its depth data. The myBuffer.depth
property\nmakes it possible to pass this data directly to other functions. For\nexample, calling texture(myBuffer.depth)
or\nmyShader.setUniform('depthTexture', myBuffer.depth)
may be helpful for\nadvanced use cases.
Note: By default, a framebuffer's y-coordinates are flipped compared to\nimages and videos. It's easy to flip a framebuffer's y-coordinates as\nneeded when applying it as a texture. For example, calling\nplane(myBuffer.width, -myBuffer.height)
will flip the framebuffer.
\n// Note: A \"uniform\" is a global variable within a shader program.\n\n// Create a string with the vertex shader program.\n// The vertex shader is called for each vertex.\nlet vertSrc = `\nprecision highp float;\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nvarying vec2 vTexCoord;\n\nvoid main() {\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * viewModelPosition;\n vTexCoord = aTexCoord;\n}\n`;\n\n// Create a string with the fragment shader program.\n// The fragment shader is called for each pixel.\nlet fragSrc = `\nprecision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D depth;\n\nvoid main() {\n // Get the pixel's depth value.\n float depthVal = texture2D(depth, vTexCoord).r;\n\n // Set the pixel's color based on its depth.\n gl_FragColor = mix(\n vec4(0., 0., 0., 1.),\n vec4(1., 0., 1., 1.),\n depthVal);\n}\n`;\n\nlet myBuffer;\nlet myShader;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n // Create a p5.Shader object.\n myShader = createShader(vertSrc, fragSrc);\n\n // Compile and apply the shader.\n shader(myShader);\n\n describe('The shadow of a box rotates slowly against a magenta background.');\n}\n\nfunction draw() {\n // Draw to the p5.Framebuffer object.\n myBuffer.begin();\n background(255);\n rotateX(frameCount * 0.01);\n box(20, 20, 80);\n myBuffer.end();\n\n // Set the shader's depth uniform using\n // the framebuffer's depth texture.\n myShader.setUniform('depth', myBuffer.depth);\n\n // Style the plane.\n noStroke();\n\n // Draw the plane.\n plane(myBuffer.width, myBuffer.height);\n}\n
\nDraws to the framebuffer by calling a function that contains drawing\ninstructions.
\nThe parameter, callback
, is a function with the drawing instructions\nfor the framebuffer. For example, calling myBuffer.draw(myFunction)
\nwill call a function named myFunction()
to draw to the framebuffer.\nDoing so has the same effect as the following:
myBuffer.begin();\nmyFunction();\nmyBuffer.end();\n
\n"],"line":[0,1323],"params":[1,[[0,{"name":[0,"callback"],"description":[0,"function that draws to the framebuffer.
\n"],"type":[0,"Function"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Framebuffer"],"chainable":[0,false],"example":[1,[[0,"\n\n// Click the canvas to display the framebuffer.\n\nlet myBuffer;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n describe('An empty gray canvas. The canvas gets darker and a rotating, multicolor torus appears while the user presses and holds the mouse.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw to the p5.Framebuffer object.\n myBuffer.draw(bagel);\n\n // Display the p5.Framebuffer object while\n // the user presses the mouse.\n if (mouseIsPressed === true) {\n image(myBuffer, -50, -50);\n }\n}\n\n// Draw a rotating, multicolor torus.\nfunction bagel() {\n background(50);\n rotateY(frameCount * 0.01);\n normalMaterial();\n torus(30);\n}\n
\nStops drawing shapes to the framebuffer.
\nmyBuffer.begin() and myBuffer.end()
\nallow shapes to be drawn to the framebuffer.\nmyBuffer.begin() begins drawing to\nthe framebuffer and myBuffer.end()
stops drawing to the framebuffer.\nChanges won't be visible until the framebuffer is displayed as an image\nor texture.
\nlet myBuffer;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n describe('An empty gray canvas. The canvas gets darker and a rotating, multicolor torus appears while the user presses and holds the mouse.');\n}\n\nfunction draw() {\n background(200);\n\n // Start drawing to the p5.Framebuffer object.\n myBuffer.begin();\n\n background(50);\n rotateY(frameCount * 0.01);\n normalMaterial();\n torus(30);\n\n // Stop drawing to the p5.Framebuffer object.\n myBuffer.end();\n\n // Display the p5.Framebuffer object while\n // the user presses the mouse.\n if (mouseIsPressed === true) {\n image(myBuffer, -50, -50);\n }\n}\n
\nGets a pixel or a region of pixels from the framebuffer.
\nmyBuffer.get()
is easy to use but it's not as fast as\nmyBuffer.pixels. Use\nmyBuffer.pixels to read many pixel\nvalues.
The version of myBuffer.get()
with no parameters returns the entire\nframebuffer as a a p5.Image object.
The version of myBuffer.get()
with two parameters interprets them as\ncoordinates. It returns an array with the [R, G, B, A]
values of the\npixel at the given point.
The version of myBuffer.get()
with four parameters interprets them as\ncoordinates and dimensions. It returns a subsection of the framebuffer as\na p5.Image object. The first two parameters are\nthe coordinates for the upper-left corner of the subsection. The last two\nparameters are the width and height of the subsection.
x-coordinate of the pixel. Defaults to 0.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"y-coordinate of the pixel. Defaults to 0.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"w"],"description":[0,"width of the subsection to be returned.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"h"],"description":[0,"height of the subsection to be returned.
\n"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[]]}],[0,{"params":[1,[[0,{"name":[0,"x"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"Number"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Framebuffer"],"chainable":[0,false],"return":[0,{"description":[0,"subsection as a p5.Image object."],"type":[0,"p5.Image"]}],"isConstructor":[0,false],"path":[0,"p5.Framebuffer/get"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Framebuffer/loadPixels.mdx"],"slug":[0,"en/p5framebuffer/loadpixels"],"body":[0,"\n\n# loadPixels\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"loadPixels()"],"module":[0,"Rendering"],"submodule":[0,""],"file":[0,"src/webgl/p5.Framebuffer.js"],"description":[0,"Loads the current value of each pixel in the framebuffer into its\npixels array.
\nmyBuffer.loadPixels()
must be called before reading from or writing to\nmyBuffer.pixels.
\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // Create a p5.Framebuffer object.\n let myBuffer = createFramebuffer();\n\n // Load the pixels array.\n myBuffer.loadPixels();\n\n // Get the number of pixels in the\n // top half of the framebuffer.\n let numPixels = myBuffer.pixels.length / 2;\n\n // Set the framebuffer's top half to pink.\n for (let i = 0; i < numPixels; i += 4) {\n myBuffer.pixels[i] = 255;\n myBuffer.pixels[i + 1] = 102;\n myBuffer.pixels[i + 2] = 204;\n myBuffer.pixels[i + 3] = 255;\n }\n\n // Update the pixels array.\n myBuffer.updatePixels();\n\n // Draw the p5.Framebuffer object to the canvas.\n image(myBuffer, -50, -50);\n\n describe('A pink rectangle above a gray rectangle.');\n}\n
\nSets the framebuffer's pixel density or returns its current density.
\nComputer displays are grids of little lights called pixels. A display's\npixel density describes how many pixels it packs into an area. Displays\nwith smaller pixels have a higher pixel density and create sharper\nimages.
\nThe parameter, density
, is optional. If a number is passed, as in\nmyBuffer.pixelDensity(1)
, it sets the framebuffer's pixel density. By\ndefault, the framebuffer's pixel density will match that of the canvas\nwhere it was created. All canvases default to match the display's pixel\ndensity.
Calling myBuffer.pixelDensity()
without an argument returns its current\npixel density.
pixel density to set.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Framebuffer"],"chainable":[0,false],"return":[0,{"description":[0,"current pixel density."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nlet myBuffer;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n describe(\"A white circle on a gray canvas. The circle's edge become fuzzy while the user presses and holds the mouse.\");\n}\n\nfunction draw() {\n // Draw to the p5.Framebuffer object.\n myBuffer.begin();\n background(200);\n circle(0, 0, 40);\n myBuffer.end();\n\n // Display the p5.Framebuffer object.\n image(myBuffer, -50, -50);\n}\n\n// Decrease the pixel density when the user\n// presses the mouse.\nfunction mousePressed() {\n myBuffer.pixelDensity(1);\n}\n\n// Increase the pixel density when the user\n// releases the mouse.\nfunction mouseReleased() {\n myBuffer.pixelDensity(2);\n}\n
\n\nlet myBuffer;\nlet myFont;\n\n// Load a font and create a p5.Font object.\nfunction preload() {\n myFont = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n // Get the p5.Framebuffer object's pixel density.\n let d = myBuffer.pixelDensity();\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont(myFont);\n textSize(16);\n fill(0);\n\n // Display the pixel density.\n text(`Density: ${d}`, 0, 0);\n\n describe(`The text \"Density: ${d}\" written in black on a gray background.`);\n}\n
\nAn array containing the color of each pixel in the framebuffer.
\nmyBuffer.loadPixels() must be\ncalled before accessing the myBuffer.pixels
array.\nmyBuffer.updatePixels()\nmust be called after any changes are made.
Note: Updating pixels via this property is slower than drawing to the\nframebuffer directly. Consider using a\np5.Shader object instead of looping over\nmyBuffer.pixels
.
\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // Create a p5.Framebuffer object.\n let myBuffer = createFramebuffer();\n\n // Load the pixels array.\n myBuffer.loadPixels();\n\n // Get the number of pixels in the\n // top half of the framebuffer.\n let numPixels = myBuffer.pixels.length / 2;\n\n // Set the framebuffer's top half to pink.\n for (let i = 0; i < numPixels; i += 4) {\n myBuffer.pixels[i] = 255;\n myBuffer.pixels[i + 1] = 102;\n myBuffer.pixels[i + 2] = 204;\n myBuffer.pixels[i + 3] = 255;\n }\n\n // Update the pixels array.\n myBuffer.updatePixels();\n\n // Draw the p5.Framebuffer object to the canvas.\n image(myBuffer, -50, -50);\n\n describe('A pink rectangle above a gray rectangle.');\n}\n
\nDeletes the framebuffer from GPU memory.
\nCalling myBuffer.remove()
frees the GPU memory used by the framebuffer.\nThe framebuffer also uses a bit of memory on the CPU which can be freed\nlike so:
// Delete the framebuffer from GPU memory.\nmyBuffer.remove();\n\n// Delete the framebuffer from CPU memory.\nmyBuffer = undefined;\n
\nNote: All variables that reference the framebuffer must be assigned\nthe value undefined
to delete the framebuffer from CPU memory. If any\nvariable still refers to the framebuffer, then it won't be garbage\ncollected.
\n// Double-click to remove the p5.Framebuffer object.\n\nlet myBuffer;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create an options object.\n let options = { width: 60, height: 60 };\n\n // Create a p5.Framebuffer object and\n // configure it using options.\n myBuffer = createFramebuffer(options);\n\n describe('A white circle at the center of a dark gray square disappears when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Display the p5.Framebuffer object if\n // it's available.\n if (myBuffer) {\n // Draw to the p5.Framebuffer object.\n myBuffer.begin();\n background(100);\n circle(0, 0, 20);\n myBuffer.end();\n\n image(myBuffer, -30, -30);\n }\n}\n\n// Remove the p5.Framebuffer object when the\n// the user double-clicks.\nfunction doubleClicked() {\n // Delete the framebuffer from GPU memory.\n myBuffer.remove();\n\n // Delete the framebuffer from CPU memory.\n myBuffer = undefined;\n}\n
\nResizes the framebuffer to a given width and height.
\nThe parameters, width
and height
, set the dimensions of the\nframebuffer. For example, calling myBuffer.resize(300, 500)
resizes\nthe framebuffer to 300×500 pixels, then sets myBuffer.width
to 300\nand myBuffer.height
500.
width of the framebuffer.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"height"],"description":[0,"height of the framebuffer.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Framebuffer"],"chainable":[0,false],"example":[1,[[0,"\n\nlet myBuffer;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // Create a p5.Framebuffer object.\n myBuffer = createFramebuffer();\n\n describe('A multicolor sphere on a white surface. The image grows larger or smaller when the user moves the mouse, revealing a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw to the p5.Framebuffer object.\n myBuffer.begin();\n background(255);\n normalMaterial();\n sphere(20);\n myBuffer.end();\n\n // Display the p5.Framebuffer object.\n image(myBuffer, -50, -50);\n}\n\n// Resize the p5.Framebuffer object when the\n// user moves the mouse.\nfunction mouseMoved() {\n myBuffer.resize(mouseX, mouseY);\n}\n
\nUpdates the framebuffer with the RGBA values in the\npixels array.
\nmyBuffer.updatePixels()
only needs to be called after changing values\nin the myBuffer.pixels array. Such\nchanges can be made directly after calling\nmyBuffer.loadPixels().
\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n background(200);\n\n // Create a p5.Framebuffer object.\n let myBuffer = createFramebuffer();\n\n // Load the pixels array.\n myBuffer.loadPixels();\n\n // Get the number of pixels in the\n // top half of the framebuffer.\n let numPixels = myBuffer.pixels.length / 2;\n\n // Set the framebuffer's top half to pink.\n for (let i = 0; i < numPixels; i += 4) {\n myBuffer.pixels[i] = 255;\n myBuffer.pixels[i + 1] = 102;\n myBuffer.pixels[i + 2] = 204;\n myBuffer.pixels[i + 3] = 255;\n }\n\n // Update the pixels array.\n myBuffer.updatePixels();\n\n // Draw the p5.Framebuffer object to the canvas.\n image(myBuffer, -50, -50);\n\n describe('A pink rectangle above a gray rectangle.');\n}\n
\nA class to describe a drawing surface that's separate from the main canvas.
\nEach p5.Graphics
object provides a dedicated drawing surface called a\ngraphics buffer. Graphics buffers are helpful when drawing should happen\noffscreen. For example, separate scenes can be drawn offscreen and\ndisplayed only when needed.
p5.Graphics
objects have nearly all the drawing features of the main\ncanvas. For example, calling the method myGraphics.circle(50, 50, 20)
\ndraws to the graphics buffer. The resulting image can be displayed on the\nmain canvas by passing the p5.Graphics
object to the\nimage() function, as in image(myGraphics, 0, 0)
.
Note: createGraphics() is the recommended\nway to create an instance of this class.
\n"],"line":[0,10],"params":[1,[[0,{"name":[0,"width"],"description":[0,"width of the graphics buffer in pixels.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"height"],"description":[0,"height of the graphics buffer in pixels.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"renderer"],"description":[0,"renderer to use, either P2D or WEBGL.
\n"],"type":[0,"Constant"]}],[0,{"name":[0,"pInst"],"description":[0,"sketch instance.
\n"],"type":[0,"P5"],"optional":[0,true]}],[0,{"name":[0,"canvas"],"description":[0,"existing <canvas>
element to use.
\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Graphics object.\n pg = createGraphics(50, 50);\n\n // Draw to the p5.Graphics object.\n pg.background(100);\n pg.circle(25, 25, 20);\n\n describe('A dark gray square with a white circle at its center drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Display the p5.Graphics object.\n image(pg, 25, 25);\n}\n
\n\n// Click the canvas to display the graphics buffer.\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Graphics object.\n pg = createGraphics(50, 50);\n\n describe('A square appears on a gray background when the user presses the mouse. The square cycles between white and black.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the background color.\n let bg = frameCount % 255;\n\n // Draw to the p5.Graphics object.\n pg.background(bg);\n\n // Display the p5.Graphics object while\n // the user presses the mouse.\n if (mouseIsPressed === true) {\n image(pg, 25, 25);\n }\n}\n
\nResets the graphics buffer's transformations and lighting.
\nBy default, the main canvas resets certain transformation and lighting\nvalues each time draw() executes. p5.Graphics
\nobjects must reset these values manually by calling myGraphics.reset()
.
Removes the graphics buffer from the web page.
\nCalling myGraphics.remove()
removes the graphics buffer's\n element from the web page. The graphics buffer also uses\na bit of memory on the CPU that can be freed like so:
// Remove the graphics buffer from the web page.\nmyGraphics.remove();\n\n// Delete the graphics buffer from CPU memory.\nmyGraphics = undefined;\n
\nNote: All variables that reference the graphics buffer must be assigned\nthe value undefined
to delete the graphics buffer from CPU memory. If any\nvariable still refers to the graphics buffer, then it won't be garbage\ncollected.
Creates a new p5.Framebuffer object with\nthe same WebGL context as the graphics buffer.
\np5.Framebuffer objects are separate drawing\nsurfaces that can be used as textures in WebGL mode. They're similar to\np5.Graphics objects and generally run much\nfaster when used as textures. Creating a\np5.Framebuffer object in the same context\nas the graphics buffer makes this speedup possible.
\nThe parameter, options
, is optional. An object can be passed to configure\nthe p5.Framebuffer object. The available\nproperties are:
format
: data format of the texture, either UNSIGNED_BYTE
, FLOAT
, or HALF_FLOAT
. Default is UNSIGNED_BYTE
.channels
: whether to store RGB
or RGBA
color channels. Default is to match the graphics buffer which is RGBA
.depth
: whether to include a depth buffer. Default is true
.depthFormat
: data format of depth information, either UNSIGNED_INT
or FLOAT
. Default is FLOAT
.stencil
: whether to include a stencil buffer for masking. depth
must be true
for this feature to work. Defaults to the value of depth
which is true
.antialias
: whether to perform anti-aliasing. If set to true
, as in { antialias: true }
, 2 samples will be used by default. The number of samples can also be set, as in { antialias: 4 }
. Default is to match setAttributes() which is false
(true
in Safari).width
: width of the p5.Framebuffer object. Default is to always match the graphics buffer width.height
: height of the p5.Framebuffer object. Default is to always match the graphics buffer height.density
: pixel density of the p5.Framebuffer object. Default is to always match the graphics buffer pixel density.textureFiltering
: how to read values from the p5.Framebuffer object. Either LINEAR
(nearby pixels will be interpolated) or NEAREST
(no interpolation). Generally, use LINEAR
when using the texture as an image and NEAREST
if reading the texture as data. Default is LINEAR
.If the width
, height
, or density
attributes are set, they won't\nautomatically match the graphics buffer and must be changed manually.
Creates a new p5.Framebuffer object with\nthe same WebGL context as the graphics buffer.
\np5.Framebuffer objects are separate drawing\nsurfaces that can be used as textures in WebGL mode. They're similar to\np5.Graphics objects and generally run much\nfaster when used as textures. Creating a\np5.Framebuffer object in the same context\nas the graphics buffer makes this speedup possible.
\nThe parameter, options
, is optional. An object can be passed to configure\nthe p5.Framebuffer object. The available\nproperties are:
format
: data format of the texture, either UNSIGNED_BYTE
, FLOAT
, or HALF_FLOAT
. Default is UNSIGNED_BYTE
.channels
: whether to store RGB
or RGBA
color channels. Default is to match the graphics buffer which is RGBA
.depth
: whether to include a depth buffer. Default is true
.depthFormat
: data format of depth information, either UNSIGNED_INT
or FLOAT
. Default is FLOAT
.stencil
: whether to include a stencil buffer for masking. depth
must be true
for this feature to work. Defaults to the value of depth
which is true
.antialias
: whether to perform anti-aliasing. If set to true
, as in { antialias: true }
, 2 samples will be used by default. The number of samples can also be set, as in { antialias: 4 }
. Default is to match setAttributes() which is false
(true
in Safari).width
: width of the p5.Framebuffer object. Default is to always match the graphics buffer width.height
: height of the p5.Framebuffer object. Default is to always match the graphics buffer height.density
: pixel density of the p5.Framebuffer object. Default is to always match the graphics buffer pixel density.textureFiltering
: how to read values from the p5.Framebuffer object. Either LINEAR
(nearby pixels will be interpolated) or NEAREST
(no interpolation). Generally, use LINEAR
when using the texture as an image and NEAREST
if reading the texture as data. Default is LINEAR
.If the width
, height
, or density
attributes are set, they won't\nautomatically match the graphics buffer and must be changed manually.
configuration options.
\n"],"type":[0,"Object"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Graphics"],"chainable":[0,false],"return":[0,{"description":[0,"new framebuffer."],"type":[0,"p5.Framebuffer"]}],"example":[1,[[0,"\n\n// Click and hold a mouse button to change shapes.\n\nlet pg;\nlet torusLayer;\nlet boxLayer;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Graphics object using WebGL mode.\n pg = createGraphics(100, 100, WEBGL);\n\n // Create the p5.Framebuffer objects.\n torusLayer = pg.createFramebuffer();\n boxLayer = pg.createFramebuffer();\n\n describe('A grid of white toruses rotating against a dark gray background. The shapes become boxes while the user holds a mouse button.');\n}\n\nfunction draw() {\n // Update and draw the layers offscreen.\n drawTorus();\n drawBox();\n\n // Choose the layer to display.\n let layer;\n if (mouseIsPressed === true) {\n layer = boxLayer;\n } else {\n layer = torusLayer;\n }\n\n // Draw to the p5.Graphics object.\n pg.background(50);\n\n // Iterate from left to right.\n for (let x = -50; x < 50; x += 25) {\n // Iterate from top to bottom.\n for (let y = -50; y < 50; y += 25) {\n // Draw the layer to the p5.Graphics object\n pg.image(layer, x, y, 25, 25);\n }\n }\n\n // Display the p5.Graphics object.\n image(pg, 0, 0);\n}\n\n// Update and draw the torus layer offscreen.\nfunction drawTorus() {\n // Start drawing to the torus p5.Framebuffer.\n torusLayer.begin();\n\n // Clear the drawing surface.\n pg.clear();\n\n // Turn on the lights.\n pg.lights();\n\n // Rotate the coordinate system.\n pg.rotateX(frameCount * 0.01);\n pg.rotateY(frameCount * 0.01);\n\n // Style the torus.\n pg.noStroke();\n\n // Draw the torus.\n pg.torus(20);\n\n // Start drawing to the torus p5.Framebuffer.\n torusLayer.end();\n}\n\n// Update and draw the box layer offscreen.\nfunction drawBox() {\n // Start drawing to the box p5.Framebuffer.\n boxLayer.begin();\n\n // Clear the drawing surface.\n pg.clear();\n\n // Turn on the lights.\n pg.lights();\n\n // Rotate the coordinate system.\n pg.rotateX(frameCount * 0.01);\n pg.rotateY(frameCount * 0.01);\n\n // Style the box.\n pg.noStroke();\n\n // Draw the box.\n pg.box(30);\n\n // Start drawing to the box p5.Framebuffer.\n boxLayer.end();\n}\n
\n\n// Click and hold a mouse button to change shapes.\n\nlet pg;\nlet torusLayer;\nlet boxLayer;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create an options object.\n let options = { width: 25, height: 25 };\n\n // Create a p5.Graphics object using WebGL mode.\n pg = createGraphics(100, 100, WEBGL);\n\n // Create the p5.Framebuffer objects.\n // Use options for configuration.\n torusLayer = pg.createFramebuffer(options);\n boxLayer = pg.createFramebuffer(options);\n\n describe('A grid of white toruses rotating against a dark gray background. The shapes become boxes while the user holds a mouse button.');\n}\n\nfunction draw() {\n // Update and draw the layers offscreen.\n drawTorus();\n drawBox();\n\n // Choose the layer to display.\n let layer;\n if (mouseIsPressed === true) {\n layer = boxLayer;\n } else {\n layer = torusLayer;\n }\n\n // Draw to the p5.Graphics object.\n pg.background(50);\n\n // Iterate from left to right.\n for (let x = -50; x < 50; x += 25) {\n // Iterate from top to bottom.\n for (let y = -50; y < 50; y += 25) {\n // Draw the layer to the p5.Graphics object\n pg.image(layer, x, y);\n }\n }\n\n // Display the p5.Graphics object.\n image(pg, 0, 0);\n}\n\n// Update and draw the torus layer offscreen.\nfunction drawTorus() {\n // Start drawing to the torus p5.Framebuffer.\n torusLayer.begin();\n\n // Clear the drawing surface.\n pg.clear();\n\n // Turn on the lights.\n pg.lights();\n\n // Rotate the coordinate system.\n pg.rotateX(frameCount * 0.01);\n pg.rotateY(frameCount * 0.01);\n\n // Style the torus.\n pg.noStroke();\n\n // Draw the torus.\n pg.torus(5, 2.5);\n\n // Start drawing to the torus p5.Framebuffer.\n torusLayer.end();\n}\n\n// Update and draw the box layer offscreen.\nfunction drawBox() {\n // Start drawing to the box p5.Framebuffer.\n boxLayer.begin();\n\n // Clear the drawing surface.\n pg.clear();\n\n // Turn on the lights.\n pg.lights();\n\n // Rotate the coordinate system.\n pg.rotateX(frameCount * 0.01);\n pg.rotateY(frameCount * 0.01);\n\n // Style the box.\n pg.noStroke();\n\n // Draw the box.\n pg.box(7.5);\n\n // Start drawing to the box p5.Framebuffer.\n boxLayer.end();\n}\n
\nRemoves the graphics buffer from the web page.
\nCalling myGraphics.remove()
removes the graphics buffer's\n element from the web page. The graphics buffer also uses\na bit of memory on the CPU that can be freed like so:
// Remove the graphics buffer from the web page.\nmyGraphics.remove();\n\n// Delete the graphics buffer from CPU memory.\nmyGraphics = undefined;\n
\nNote: All variables that reference the graphics buffer must be assigned\nthe value undefined
to delete the graphics buffer from CPU memory. If any\nvariable still refers to the graphics buffer, then it won't be garbage\ncollected.
\n// Double-click to remove the p5.Graphics object.\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Graphics object.\n pg = createGraphics(60, 60);\n\n // Draw to the p5.Graphics object.\n pg.background(100);\n pg.circle(30, 30, 20);\n\n describe('A white circle at the center of a dark gray square disappears when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Display the p5.Graphics object if\n // it's available.\n if (pg) {\n image(pg, 20, 20);\n }\n}\n\n// Remove the p5.Graphics object when the\n// the user double-clicks.\nfunction doubleClicked() {\n // Remove the p5.Graphics object from the web page.\n pg.remove();\n pg = undefined;\n}\n
\nResets the graphics buffer's transformations and lighting.
\nBy default, the main canvas resets certain transformation and lighting\nvalues each time draw() executes. p5.Graphics
\nobjects must reset these values manually by calling myGraphics.reset()
.
\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Graphics object.\n pg = createGraphics(60, 60);\n\n describe('A white circle moves downward slowly within a dark square. The circle resets at the top of the dark square when the user presses the mouse.');\n}\n\nfunction draw() {\n background(200);\n\n // Translate the p5.Graphics object's coordinate system.\n // The translation accumulates; the white circle moves.\n pg.translate(0, 0.1);\n\n // Draw to the p5.Graphics object.\n pg.background(100);\n pg.circle(30, 0, 10);\n\n // Display the p5.Graphics object.\n image(pg, 20, 20);\n\n // Translate the main canvas' coordinate system.\n // The translation doesn't accumulate; the dark\n // square is always in the same place.\n translate(0, 0.1);\n\n // Reset the p5.Graphics object when the\n // user presses the mouse.\n if (mouseIsPressed === true) {\n pg.reset();\n }\n}\n
\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Graphics object.\n pg = createGraphics(60, 60);\n\n describe('A white circle at the center of a dark gray square. The image is drawn on a light gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Translate the p5.Graphics object's coordinate system.\n pg.translate(30, 30);\n\n // Draw to the p5.Graphics object.\n pg.background(100);\n pg.circle(0, 0, 10);\n\n // Display the p5.Graphics object.\n image(pg, 20, 20);\n\n // Reset the p5.Graphics object automatically.\n pg.reset();\n}\n
\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Graphics object using WebGL mode.\n pg = createGraphics(100, 100, WEBGL);\n\n describe(\"A sphere lit from above with a red light. The sphere's surface becomes glossy while the user clicks and holds the mouse.\");\n}\n\nfunction draw() {\n background(200);\n\n // Add a red point light from the top-right.\n pg.pointLight(255, 0, 0, 50, -100, 50);\n\n // Style the sphere.\n // It should appear glossy when the\n // lighting values are reset.\n pg.noStroke();\n pg.specularMaterial(255);\n pg.shininess(100);\n\n // Draw the sphere.\n pg.sphere(30);\n\n // Display the p5.Graphics object.\n image(pg, -50, -50);\n\n // Reset the p5.Graphics object when\n // the user presses the mouse.\n if (mouseIsPressed === true) {\n pg.reset();\n }\n}\n
\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Graphics object using WebGL mode.\n pg = createGraphics(100, 100, WEBGL);\n\n describe('A sphere with a glossy surface is lit from the top-right by a red light.');\n}\n\nfunction draw() {\n background(200);\n\n // Add a red point light from the top-right.\n pg.pointLight(255, 0, 0, 50, -100, 50);\n\n // Style the sphere.\n pg.noStroke();\n pg.specularMaterial(255);\n pg.shininess(100);\n\n // Draw the sphere.\n pg.sphere(30);\n\n // Display the p5.Graphics object.\n image(pg, 0, 0);\n\n // Reset the p5.Graphics object automatically.\n pg.reset();\n}\n
\nMain graphics and rendering context, as well as the base API\nimplementation for p5.js \"core\". To be used as the superclass for\nRenderer2D and Renderer3D classes, respectively.
\n"],"line":[0,10],"params":[1,[[0,{"name":[0,"elt"],"description":[0,"DOM node that is wrapped
\n"],"type":[0,"HTMLElement"]}],[0,{"name":[0,"pInst"],"description":[0,"pointer to p5 instance
\n"],"type":[0,"P5"],"optional":[0,true]}],[0,{"name":[0,"isMainCanvas"],"description":[0,"whether we're using it as main canvas
\n"],"type":[0,"Boolean"],"optional":[0,true]}]]],"chainable":[0,false],"isConstructor":[0,true],"path":[0,"p5/p5.Renderer"]}],"render":[0,null]}],"entries":[1,[]]}]]]}],[0,{"name":[0,"Matemáticas"],"subcats":[1,[[0,{"name":[0],"entry":[0],"entries":[1,[]]}],[0,{"name":[0,"Aleatorio"],"entry":[0],"entries":[1,[[0,{"id":[0,"es/p5/random.mdx"],"slug":[0,"es/p5/random"],"body":[0,"\n# random\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"random()"],"module":[0,"Matemáticas"],"submodule":[0,"Aleatorio"],"file":[0,"src/math/random.js"],"description":[0,"Devuelve un número aleatorio o un elemento aleatorio de una matriz.
\nrandom()
sigue una distribución uniforme, lo que significa que todos los resultados son\nigualmente probables. Cuando se utiliza random()
para generar números, todos los números en el rango de salida tienen la misma probabilidad de ser producidos. Cuando\nrandom()
se utiliza para seleccionar elementos de una matriz, todos los elementos tienen la misma probabilidad de ser elegidos.
De forma predeterminada, random()
produce resultados diferentes cada vez que se ejecuta un boceto.\nLa función randomSeed() se puede utilizar para\ngenerar la misma secuencia de números o elecciones cada vez que se ejecuta un boceto.
La versión de random()
sin parámetros devuelve un número aleatorio desde 0\nhasta 1 (sin incluirlo).
La versión de random()
con un parámetro funciona de dos maneras. Si el argumento es un número, random()
devuelve un número aleatorio desde 0\nhasta el número (sin incluirlo). Por ejemplo, llamar random(5)
devuelve\nvalores entre 0 y 5. Si el argumento es una matriz, random()
\ndevuelve un elemento aleatorio de esa matriz. Por ejemplo, llamando\nrandom(['🦁', '🐯', '🐻'])
devuelve un emoji de león, tigre u oso.
La versión de random()
con dos parámetros devuelve un número aleatorio dentro de\nun rango dado. Los argumentos pasados establecen los límites superior e inferior del rango.\nPor ejemplo, llamar a random(-5, 10.2)
devuelve valores desde -5 hasta 10.2 (sin incluirlo).
límite inferior (incluido).
"],"type":[0,"Número"],"optional":[0,true]}],[0,{"name":[0,"max"],"description":[0,"\nlímite superior (excluido).
"],"type":[0,"Número"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"choices"],"description":[0,"\nmatriz de la cual elegir.
"],"type":[0,"Arreglo"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"número aleatorio."],"type":[0,"Número"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get random coordinates between 0 and 100.\n let x = random(0, 100);\n let y = random(0, 100);\n\n // Draw a point.\n strokeWeight(5);\n point(x, y);\n\n describe('A black dot appears in a random position on a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get random coordinates between 0 and 100.\n let x = random(100);\n let y = random(100);\n\n // Draw the point.\n strokeWeight(5);\n point(x, y);\n\n describe('A black dot appears in a random position on a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of emoji strings.\n let animals = ['🦁', '🐯', '🐻'];\n\n // Choose a random element from the array.\n let choice = random(animals);\n\n // Style the text.\n textAlign(CENTER);\n textSize(20);\n\n // Display the emoji.\n text(choice, 50, 50);\n\n describe('An animal face is displayed at random. Either a lion, tiger, or bear.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(5);\n\n describe('A black dot moves around randomly on a gray square.');\n}\n\nfunction draw() {\n background(200);\n\n // Get random coordinates between 0 and 100.\n let x = random(100);\n let y = random(100);\n\n // Draw the point.\n strokeWeight(5);\n point(x, y);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(5);\n\n describe('A black dot moves around randomly in the middle of a gray square.');\n}\n\nfunction draw() {\n background(200);\n\n // Get random coordinates between 45 and 55.\n let x = random(45, 55);\n let y = random(45, 55);\n\n // Draw the point.\n strokeWeight(5);\n point(x, y);\n}\n
\n\nlet x = 50;\nlet y = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A black dot moves around randomly leaving a trail.');\n}\n\nfunction draw() {\n // Update x and y randomly.\n x += random(-1, 1);\n y += random(-1, 1);\n\n // Draw the point.\n point(x, y);\n}\n
\nDevuelve un número aleatorio que se ajusta a una distribución gaussiana o normal.
\n\nLas distribuciones normales parecen curvas de campana cuando se grafican. Los valores de una distribución normal se agrupan alrededor de un valor central llamado media. La desviación estándar del conglomerado describe su dispersión.
\n\nPor defecto, randomGaussian()
produce resultados diferentes cada vez que se ejecuta un boceto.\nLa función randomSeed()\npuede ser utilizada para generar la misma secuencia de números cada vez que se ejecuta un boceto.
No hay mínimo o máximo para los valores que randomGaussian()
puede regresar.\nLos valores alejados de la media son muy improbables, mientras que los valores cercanos a la media son altamente probables.
La versión de randomGaussian()
sin parámetros devuelve\nvalores con una\nmedia de 0 y desviación estándar de 1.
La versión de randomGaussian()
con un parámetro interpreta\nsu argumento como la media. La desviación estándar es 1.
La versión de randomGaussian()
con dos parámetros interpreta\nel primer argumento como la media y el segundo como la desviación estándar.
media.
"],"type":[0,"Número"],"optional":[0,true]}],[0,{"name":[0,"sd"],"description":[0,"\ndesviación estándar.
"],"type":[0,"Número"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"número aleatorio."],"type":[0,"Número"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('Three horizontal black lines are filled in randomly. The top line spans entire canvas. The middle line is very short. The bottom line spans two-thirds of the canvas.');\n}\n\nfunction draw() {\n // Style the circles.\n noStroke();\n fill(0, 10);\n\n // Uniform distribution between 0 and 100.\n let x = random(100);\n let y = 25;\n circle(x, y, 5);\n\n // Gaussian distribution with a mean of 50 and sd of 1.\n x = randomGaussian(50);\n y = 50;\n circle(x, y, 5);\n\n // Gaussian distribution with a mean of 50 and sd of 10.\n x = randomGaussian(50, 10);\n y = 75;\n circle(x, y, 5);\n}\n
\nEstablece la semilla aleatoria para las funciones random() y\n\n\nrandomGaussian().
\n\n\nPor defeto, random() y\n\n\nrandomGaussian() producen diferentes\n\n\nresultados cada vez que se ejecuta un boceto. Llamar a randomSeed()
con un argumento constante, como randomSeed(99)
, hace que estas funciones produzcan\nlos mismos\n\n\nresultados cada vez que se ejecuta un boceto.
valor de la semilla aleatoria.
"],"type":[0,"Número"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get random coordinates.\n let x = random(0, 100);\n let y = random(0, 100);\n\n // Draw the white circle.\n circle(x, y, 10);\n\n // Set a random seed for consistency.\n randomSeed(99);\n\n // Get random coordinates.\n x = random(0, 100);\n y = random(0, 100);\n\n // Draw the black circle.\n fill(0);\n circle(x, y, 10);\n\n describe('A white circle appears at a random position. A black circle appears at (27.4, 25.8).');\n}\n
\nceil()
redondea al número entero más cercano. El resultado será mayor o igual que el valor que se ha proporcionado.
Por ejemplo, al llamar a ceil(9.03)
y ceil(9.97)
, ambos números se redondearán a 10.
número a redondear.
"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"número redondeado."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use RGB color with values from 0 to 1.\n colorMode(RGB, 1);\n\n noStroke();\n\n // Draw the left rectangle.\n let r = 0.3;\n fill(r, 0, 0);\n rect(0, 0, 50, 100);\n\n // Round r up to 1.\n r = ceil(r);\n\n // Draw the right rectangle.\n fill(r, 0, 0);\n rect(50, 0, 50, 100);\n\n describe('Two rectangles. The one on the left is dark red and the one on the right is bright red.');\n}\n
\nabs()
calcula el valor absoluto de un número.
El valor absoluto de un número se calcula como la distancia de ese número a cero en la línea numérica, sin tener en cuenta su dirección. Por ejemplo, tanto -5 como 5 se encuentran a una distancia de 5 unidades del 0, por lo que llamar a abs(-5)
o abs(5)
resulta en 5. Es importante recordar que el valor absoluto de un número siempre es positivo.
número a calcular.
"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"valor absoluto de un número dado."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A gray square with a vertical black line that divides it in half. A white rectangle gets taller when the user moves the mouse away from the line.');\n}\n\nfunction draw() {\n background(200);\n\n // Divide the canvas.\n line(50, 0, 50, 100);\n\n // Calculate the mouse's distance from the middle.\n let h = abs(mouseX - 50);\n\n // Draw a rectangle based on the mouse's distance\n // from the middle.\n rect(0, 100 - h, 100, h);\n}\n
\nconstrain()
limita un número para que esté dentro de un rango definido por un valor mínimo y un valor máximo
constrain()
toma tres parámetros.
El primer parámetro define el número que se va a limitar, el segundo parámetro es el valor mínimo permitido, y el tercer parámetro es el valor máximo permitido que el número puede tomar. Por ejemplo en constrain(mouseX, 33, 67)
, el valor de mouseX
se limita para que esté dentro del rango entre 33 y 67.
número a limitar/ restringir.
"],"type":[0,"Number"]}],[0,{"name":[0,"low"],"description":[0,"\nvalor mínimo.
"],"type":[0,"Number"]}],[0,{"name":[0,"high"],"description":[0,"\nvalor máximo.
"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"número limitado/ restringido."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A black dot drawn on a gray square follows the mouse from left to right. Its movement is constrained to the middle third of the square.');\n}\n\nfunction draw() {\n background(200);\n\n let x = constrain(mouseX, 33, 67);\n let y = 50;\n\n strokeWeight(5);\n point(x, y);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Two vertical lines. Two circles move horizontally with the mouse. One circle stops at the vertical lines.');\n}\n\nfunction draw() {\n background(200);\n\n // Set boundaries and draw them.\n let leftWall = 25;\n let rightWall = 75;\n line(leftWall, 0, leftWall, 100);\n line(rightWall, 0, rightWall, 100);\n\n // Draw a circle that follows the mouse freely.\n fill(255);\n circle(mouseX, 33, 9);\n\n // Draw a circle that's constrained.\n let xc = constrain(mouseX, leftWall, rightWall);\n fill(0);\n circle(xc, 67, 9);\n}\n
\ndist()
calcula la distancia entre dos puntos.
La versión de dist()
que toma cuatro parámetros calcula la distancia en un plano 2D.
La versión de dist()
que toma seis parámetros calcula la distancia en un plano 3D.
Usa p5.Vector.dist() para calcular la distancia entre dos vectores p5.Vector
"],"line":[0,155],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"x1"],"description":[0,"\ncoordenada x del primer punto.
"],"type":[0,"Number"]}],[0,{"name":[0,"y1"],"description":[0,"\ncoordenada y del primer punto.
"],"type":[0,"Number"]}],[0,{"name":[0,"x2"],"description":[0,"\nla coordenada x del segundo punto.
"],"type":[0,"Number"]}],[0,{"name":[0,"y2"],"description":[0,"\nla coordenada y del segundo punto.
"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"x1"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y1"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"z1"],"description":[0,"\nla coordenada z del primer punto.
"],"type":[0,"Number"]}],[0,{"name":[0,"x2"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"y2"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"z2"],"description":[0,"\nla coordenada z del segundo punto.
"],"type":[0,"Number"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"distancia entre dos puntos."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Set the coordinates.\n let x1 = 10;\n let y1 = 50;\n let x2 = 90;\n let y2 = 50;\n\n // Draw the points and a line connecting them.\n line(x1, y1, x2, y2);\n strokeWeight(5);\n point(x1, y1);\n point(x2, y2);\n\n // Calculate the distance.\n let d = dist(x1, y1, x2, y2);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the distance.\n text(d, 43, 40);\n\n describe('Two dots connected by a horizontal line. The number 80 is written above the center of the line.');\n}\n
\nexp()
calcula el número de Euler (e = 2.71828...) elevado a la potencia de un numero 'n'
Este número 'n' se pasa como argumento a exp()
. Por ejemplo, exp(2)
, representa el número de Euler elevado a la potencia de dos.
exponente de la potencia
"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"e^n"],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top-left.\n let d = exp(1);\n circle(10, 10, d);\n\n // Left-center.\n d = exp(2);\n circle(20, 20, d);\n\n // Right-center.\n d = exp(3);\n circle(40, 40, d);\n\n // Bottom-right.\n d = exp(4);\n circle(80, 80, d);\n\n describe('A series of circles that grow exponentially from top left to bottom right.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots that grow exponentially from left to right.');\n}\n\nfunction draw() {\n // Invert the y-axis.\n scale(1, -1);\n translate(0, -100);\n\n // Calculate the coordinates.\n let x = frameCount;\n let y = 0.005 * exp(x * 0.1);\n\n // Draw a point.\n point(x, y);\n}\n
\nfloor()
redondea al número entero más cercano que sea menor o igual al valor que se ha proporcionado.
Por ejemplo, al llamar a floor(1.3)
y ceil(1.9)
, ambos números se redondearán a 1.
número a redondear hacia abajo.
"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"número redondeado hacia abajo."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use RGB color with values from 0 to 1.\n colorMode(RGB, 1);\n\n noStroke();\n\n // Draw the left rectangle.\n let r = 0.8;\n fill(r, 0, 0);\n rect(0, 0, 50, 100);\n\n // Round r down to 0.\n r = floor(r);\n\n // Draw the right rectangle.\n fill(r, 0, 0);\n rect(50, 0, 50, 100);\n\n describe('Two rectangles. The one on the left is bright red and the one on the right is black.');\n}\n
\nCalcula la parte fraccionaria de un número.
\n\nLa parte fraccionaria de un número incluye sus valores decimales. Por ejemplo,\n\nfract(12.34)
devuelve 0.34.
el número cuya parte fraccionaria será encontrada.
"],"type":[0,"Número"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"parte fraccionaria de n."],"type":[0,"Número"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Original number.\n let n = 56.78;\n text(n, 50, 33);\n\n // Fractional part.\n let f = fract(n);\n text(f, 50, 67);\n\n describe('The number 56.78 written above the number 0.78.');\n}\n
\nlerp()
calcula un número que se encuentra entre dos números, con un incremento específico.
Esta función toma tres parámetros. El parámetro start
define el primer número, mientras que el parámetro stop
define el segundo número. El tercer parámetro amt
define la cantidad con la cual se va a interpolar (encontrar un valor) entre los dos números start
y stop
.
amt
es 0.0, el resultado será igual al número start
.amt
es 0.1, el resultado será un número muy cercano al número start
.amt
es 0.5, el resultado será la mitad exacta entre el número start
y el número stop.amt
es 1, el resultado será igual al número stop
.amt
es menor que 0 o mayor que 1, lerp()
devolverá un número fuera del rango original. Por ejemplo, si llamamos lerp(0, 10, 1.5)
, obtendremos 15 como resultado.La función lerp()
es conveniente para crear movimiento a lo largo de un camino recto, y para dibujar líneas punteadas.
primer número.
"],"type":[0,"Number"]}],[0,{"name":[0,"stop"],"description":[0,"\nsegundo número .
"],"type":[0,"Number"]}],[0,{"name":[0,"amt"],"description":[0,"\nnúmero entre 0 y 1.
"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"valor interpolado."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Declare variables for coordinates.\n let a = 20;\n let b = 80;\n let c = lerp(a, b, 0.2);\n let d = lerp(a, b, 0.5);\n let e = lerp(a, b, 0.8);\n\n strokeWeight(5);\n\n // Draw the original points in black.\n stroke(0);\n point(a, 50);\n point(b, 50);\n\n // Draw the lerped points in gray.\n stroke(100);\n point(c, 50);\n point(d, 50);\n point(e, 50);\n\n describe('Five points in a horizontal line. The outer points are black and the inner points are gray.');\n}\n
\n\nlet x = 50;\nlet y = 50;\nlet targetX = 50;\nlet targetY = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A white circle at the center of a gray canvas. The circle moves to where the user clicks, then moves smoothly back to the center.');\n}\n\nfunction draw() {\n background(220);\n\n // Move x and y toward the target.\n x = lerp(x, targetX, 0.05);\n y = lerp(y, targetY, 0.05);\n\n // Draw the circle.\n circle(x, y, 20);\n}\n\n// Set x and y when the user clicks the mouse.\nfunction mouseClicked() {\n x = mouseX;\n y = mouseY;\n}\n
\nCalcula el logaritmo natural (logaritmo con base e) de un número.
\nLa función log()
espera que el parámetro n
sea un valor mayor que 0, ya que el logaritmo natural se define de esta manera.
un número mayor que 0.
"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"logaritmo natural de n."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top-left.\n let d = log(50);\n circle(33, 33, d);\n\n // Bottom-right.\n d = log(500000000);\n circle(67, 67, d);\n\n describe('Two white circles. The circle at the top-left is small. The circle at the bottom-right is about five times larger.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots that get higher slowly from left to right.');\n}\n\nfunction draw() {\n // Invert the y-axis.\n scale(1, -1);\n translate(0, -100);\n\n // Calculate coordinates.\n let x = frameCount;\n let y = 15 * log(x);\n\n // Draw a point.\n point(x, y);\n}\n
\nmag()
calcula la magnitud, o distancia de un vector.
Un vector puede ser pensado de diferente maneras. Una de ellas, es pensando en vectores como puntos en un espacio. Los componentes de un vector, x
y y
, son las coordenadas que definen su posición (x,y)
. La magnitud de un vector es entonces la distancia desde el punto origen (0,0)
hasta el punto donde se encuentra el vector (x,y)
. Utilizar mag(x,y)
es una opción rápida equivalente a llamar a dist(0,0,x,y)
.
Un vector también puede ser pensado como una flecha que puede apuntar a distintas direcciones en un espacio. Esta perspectiva es útil para programar movimiento.
\nConsulta p5.Vector para más detalles.
\nUsa p5.Vector.mag() para calcular la magnitud de un objeto p5.Vector .
"],"line":[0,481],"params":[1,[[0,{"name":[0,"x"],"description":[0,"\nprimer componente del vector.
"],"type":[0,"Number"]}],[0,{"name":[0,"y"],"description":[0,"\nsegundo componente del vector.
"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"magnitud del vector."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Set the vector's components.\n let x = 30;\n let y = 40;\n\n // Calculate the magnitude.\n let m = mag(x, y);\n\n // Style the text.\n textSize(16);\n\n // Display the vector and its magnitude.\n line(0, 0, x, y);\n text(m, x, y);\n\n describe('A diagonal line is drawn from the top left of the canvas. The number 50 is written at the end of the line.');\n}\n
\nmap()
reasigna un número que se encuentra en un rango inicial, dentro de un nuevo rango.
Por ejemplo, si llamamos map(2, 0, 10, 0, 100)
obtenemos 20 como resultado. Los primeros tres argumentos definen el valor de 2 dentro del rango original que va de 0 a 10. Los últimos dos argumentos definen el nuevo rango, que va de 0 a 100. La posición de 20 en el rango [0, 100] es proporcional a la posición de 2 en el rango original [0, 10].
map()
puede tomar un sexto argumento, el cual es opcional. Por defecto, map()
puede devolver valores que se encuentran fuera del rango objetivo. Por ejemplo, si llamamos map(11, 0, 10, 0, 100)
obtenemos 110 como resultado, a pesar de que está fuera del rango [0, 100]. Cuando pasamos true
como sexto parámetro, estamos restringiendo el valor dentro del rango objetivo. Entonces, si llamamos map(11, 0, 10, 0, 100, true)
, obtenemos 100 como resultado.
el valor que se va a reasignar.
"],"type":[0,"Number"]}],[0,{"name":[0,"start1"],"description":[0,"\nlímite inferior del rango original.
"],"type":[0,"Number"]}],[0,{"name":[0,"stop1"],"description":[0,"\nlímite superior del rango original.
"],"type":[0,"Number"]}],[0,{"name":[0,"start2"],"description":[0,"\nlímite inferior del rango objetivo.
"],"type":[0,"Number"]}],[0,{"name":[0,"stop2"],"description":[0,"\nlímite superior del rango objetivo.
"],"type":[0,"Number"]}],[0,{"name":[0,"withinBounds"],"description":[0,"\nrestringe el valor al rango recién asignado.
"],"type":[0,"Boolean"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"número reasignado."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Two horizontal lines. The top line grows horizontally as the mouse moves to the right. The bottom line also grows horizontally but is scaled to stay on the left half of the canvas.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw the top line.\n line(0, 25, mouseX, 25);\n\n // Remap mouseX from [0, 100] to [0, 50].\n let x = map(mouseX, 0, 100, 0, 50);\n\n // Draw the bottom line.\n line(0, 75, 0, x);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A circle changes color from black to white as the mouse moves from left to right.');\n}\n\nfunction draw() {\n background(200);\n\n // Remap mouseX from [0, 100] to [0, 255]\n let c = map(mouseX, 0, 100, 0, 255);\n\n // Style the circle.\n fill(c);\n\n // Draw the circle.\n circle(50, 50, 20);\n}\n
\nmax()
determina el valor más grande dentro de una secuencia de números.
La versión de max()
con un parámetro, interpreta el parámetro como un arreglo de números y devuelve el número más grande. Por ejemplo, si llamamos max(numbers), el argumento numbers
debe ser un arreglo de números.
La versión de max()
con dos o mas parámetros, interpreta los parámetros como número individuales, y devuelve el número más grande. Por ejemplo, si llamamos max (10, 5,20), obtenemos 20 como resultado.
primer número a comparar.
"],"type":[0,"Number"]}],[0,{"name":[0,"n1"],"description":[0,"\nsegundo número a comparar.
"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"nums"],"description":[0,"\nnúmeros a comparar.
"],"type":[0,"Number[]"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"número más grande."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate the maximum of 10, 5, and 20.\n let m = max(10, 5, 20);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the max.\n text(m, 50, 50);\n\n describe('The number 20 written in the middle of a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of numbers.\n let numbers = [10, 5, 20];\n\n // Calculate the maximum of the array.\n let m = max(numbers);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the max.\n text(m, 50, 50);\n\n describe('The number 20 written in the middle of a gray square.');\n}\n
\nmin()
determina el valor más pequeño dentro de una secuencia de números.
La versión de min()
con un parámetro, interpreta el parámetro como un arreglo de números y devuelve el número más pequeño. Por ejemplo, si llamamos min(numbers), el argumento numbers
debe ser un arreglo de números.
La versión de min()
con dos o más parámetros, interpreta los parámetros como número individuales, y devuelve el número más pequeño. Por ejemplo, si llamamos min(10, 5,20), obtenemos 5 como resultado.
primer número a comparar.
"],"type":[0,"Number"]}],[0,{"name":[0,"n1"],"description":[0,"\nsegundo número a comparar.
"],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"nums"],"description":[0,"\nnúmeros a comparar.
"],"type":[0,"Number[]"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"número más pequeño."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate the minimum of 10, 5, and 20.\n let m = min(10, 5, 20);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the min.\n text(m, 50, 50);\n\n describe('The number 5 written in the middle of a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of numbers.\n let numbers = [10, 5, 20];\n\n // Calculate the minimum of the array.\n let m = min(numbers);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the min.\n text(m, 50, 50);\n\n describe('The number 5 written in the middle of a gray square.');\n}\n
\nnorm()
normaliza un número que se encuentra en un rango inicial, dentro de un nuevo rango que va del 0 al 1 [0,1].
Por ejemplo, si llamamos norm(2, 0, 10)
obtenemos 0.2 como resultado. La posición del número 2 dentro del rango original [0,10] es proporcional a la posición de 0.2 en el rango [0,1]. Este comportamiento es muy similar a la función map()
, y es equivalente a map(2, 0, 10, 0, 1)
.
Los números fuera del rango original no están limitados entre 0 y 1. Los valores fuera de rango suelen ser intencionales y útiles.
"],"line":[0,772],"params":[1,[[0,{"name":[0,"value"],"description":[0,"\nvalor a normalizar.
"],"type":[0,"Number"]}],[0,{"name":[0,"start"],"description":[0,"\nlímite inferior del rango actual.
"],"type":[0,"Number"]}],[0,{"name":[0,"stop"],"description":[0,"\nlímite superior del rango actual.
"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"número normalizado."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use RGB color with values from 0 to 1.\n colorMode(RGB, 1);\n\n describe('A square changes color from black to red as the mouse moves from left to right.');\n}\n\nfunction draw() {\n // Calculate the redValue.\n let redValue = norm(mouseX, 0, 100);\n\n // Paint the background.\n background(redValue, 0, 0);\n}\n
\nCalcula expresiones exponenciales como por ejemplo 23.
\nLa función pow()
facilita la multiplicación de números por sí mismos, también conocida como potencias. Por ejemplo pow(2, 3)
evalúa a la expresión 2 x 2 x 2, mientras que pow(2, -3)
, evalúa a la expresión 1 ÷ (2 × 2 × 2).
base de la expresión exponencial.
"],"type":[0,"Number"]}],[0,{"name":[0,"e"],"description":[0,"\nexponente
"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"n^e."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Set the base of the exponent.\n let base = 3;\n\n // Top-left.\n let d = pow(base, 1);\n circle(10, 10, d);\n\n // Left-center.\n d = pow(base, 2);\n circle(20, 20, d);\n\n // Right-center.\n d = pow(base, 3);\n circle(40, 40, d);\n\n // Bottom-right.\n d = pow(base, 4);\n circle(80, 80, d);\n\n describe('A series of circles that grow exponentially from top left to bottom right.');\n}\n
\nround()
Redondea al número entero más cercano.
Por ejemplo, round(133.8)
devuelve 134.
El segundo parámetro decimals
, es opcional y su valor predeterminado es 0. Este parámetro define la cantidad de números decimales utilizados para redondear. Por ejemplo, si llamamos round(12.34, 1)
, obtenemos 12.3, ya que se ha utilizado un número después del punto decimal para redondear. En otro ejemplo, si llamamos round(12.782383, 2)
obtenemos 12.78, porque se han usado dos números después del punto decimal, para redondear.
número a redondear.
"],"type":[0,"Number"]}],[0,{"name":[0,"decimals"],"description":[0,"\n\"número de decimales usados para redondear; el valor predeterminado es 0.
\""],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"número redondeado."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Round a number.\n let x = round(4.2);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the rounded number.\n text(x, 50, 50);\n\n describe('The number 4 written in middle of the canvas.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Round a number to 2 decimal places.\n let x = round(12.782383, 2);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the rounded number.\n text(x, 50, 50);\n\n describe('The number 12.78 written in middle of canvas.');\n}\n
\nsq()
eleva un número al cuadrado.
Elevar un número al cuadrado significa multiplicar el número por sí mismo. Por ejemplo sq(3)
evalúa a 3 x 3, cuyo resultado es 9. La expresión sq(-3)
evalúa a -3 x -3, cuyo resultado también es 9. Cuando dos números negativos se multiplican, el número resultante es positivo. Por esta razón, el resultado de sq()
siempre es positivo.
número a elevar al cuadrado.
"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"número elevado al cuadrado."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top-left.\n let d = sq(3);\n circle(33, 33, d);\n\n // Bottom-right.\n d = sq(6);\n circle(67, 67, d);\n\n describe('Two white circles. The circle at the top-left is small. The circle at the bottom-right is four times larger.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots that get higher quickly from left to right.');\n}\n\nfunction draw() {\n // Invert the y-axis.\n scale(1, -1);\n translate(0, -100);\n\n // Calculate the coordinates.\n let x = frameCount;\n let y = 0.01 * sq(x);\n\n // Draw the point.\n point(x, y);\n}\n
\nsqrt()
calcula la raíz cuadrada de un número.
La raíz cuadrada de un número es aquel número que, cuando se multiplica por sí mismo, produce el número original. Por ejemplo, al llamar sqrt(9)
obtenemos 3, ya que 3 x 3 = 9.
La raíz cuadrada de un número siempre es positiva, por lo que sqrt()
no funciona con números negativos. Por ejemplo sqrt(-9)
no es válido.
Número no negativo para calcular su raíz cuadrada.
"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"raíz cuadrada de un número."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Top-left.\n let d = sqrt(16);\n circle(33, 33, d);\n\n // Bottom-right.\n d = sqrt(1600);\n circle(67, 67, d);\n\n describe('Two white circles. The circle at the top-left is small. The circle at the bottom-right is ten times larger.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots that get higher slowly from left to right.');\n}\n\nfunction draw() {\n // Invert the y-axis.\n scale(1, -1);\n translate(0, -100);\n\n // Calculate the coordinates.\n let x = frameCount;\n let y = 5 * sqrt(x);\n\n // Draw the point.\n point(x, y);\n}\n
\nDevuelve números aleatorios que se pueden ajustar para que parezcan orgánicos.
\n\n\nLos valores devueltos por random() y\n\n\nrandomGaussian() pueden cambiar en \ngrandes\n\n\ncantidades entre llamadas. Por el contrario, los valores devueltos por\nnoise()
con entradas similares \nproducen\n\n\nsalidas similares. noise()
se utiliza para crear texturas, movimiento,\nformas,\n\n\nterrenos, etcétera. Ken Perlin inventó noise()
mientras animaba\nla\n\n\npelícula Tron original de los años 80.
noise()
siempre devuelve valores entre 0 y 1. Además devuelve el\nmismo valor\n\n\npara una entrada determinada mientras se ejecuta un boceto. noise()
produce\nresultados diferentes\n\n\ncada vez que se ejecuta un boceto.\n\n\nLa función noiseSeed() se puede utilizar para\ngenerar\n\n\nla misma secuencia de valores de \"ruido Perlin\" cada vez que se ejecuta un boceto.
El carácter del ruido se puede ajustar de dos maneras. La primera es\n\n\nescalar las entradas. noise()
interpreta sus entradas como coordenadas. La\nsecuencia\n\n\nde valores de ruido serán más suaves cuando las coordenadas de entrada estén más cerca entre sí.\n\n\nLa segunda forma es utilizar la función noiseDetail().
La versión de noise()
con un parámetro calcula valores de ruido en una dimensión.\nEsta dimensión puede interpretarse como espacio, como en\nnoise(t)
.
La versión de noise()
con dos parámetros calcula el ruido\nvalores en dos\ndimensiones. Estas dimensiones pueden considerarse como espacio, como en\nnoise(x, y)
, o espacio y tiempo, como en noise(x,\nt)
.
La versión de noise()
con tres parámetros calcula el ruido\nvalores en\n\ntres dimensiones. Estas dimensiones pueden considerarse como espacio, como en\n\n\nnoise(x, y, z)
, o espacio y tiempo, como en noise(x, y,\nt)
.
coordenada x en el espacio de ruido.
"],"type":[0,"Número"]}],[0,{"name":[0,"y"],"description":[0,"\ncoordenada y en el espacio de ruido.
"],"type":[0,"Número"],"optional":[0,true]}],[0,{"name":[0,"z"],"description":[0,"\ncoordenada z en el espacio de ruido.
"],"type":[0,"Número"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"Valor de ruido Perlin en las coordenadas especificadas."],"type":[0,"Número"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A black dot moves randomly on a gray square.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the coordinates.\n let x = 100 * noise(0.005 * frameCount);\n let y = 100 * noise(0.005 * frameCount + 10000);\n\n // Draw the point.\n strokeWeight(5);\n point(x, y);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A black dot moves randomly on a gray square.');\n}\n\nfunction draw() {\n background(200);\n\n // Set the noise level and scale.\n let noiseLevel = 100;\n let noiseScale = 0.005;\n\n // Scale the input coordinate.\n let nt = noiseScale * frameCount;\n\n // Compute the noise values.\n let x = noiseLevel * noise(nt);\n let y = noiseLevel * noise(nt + 10000);\n\n // Draw the point.\n strokeWeight(5);\n point(x, y);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A hilly terrain drawn in gray against a black sky.');\n}\n\nfunction draw() {\n // Set the noise level and scale.\n let noiseLevel = 100;\n let noiseScale = 0.02;\n\n // Scale the input coordinate.\n let x = frameCount;\n let nx = noiseScale * x;\n\n // Compute the noise value.\n let y = noiseLevel * noise(nx);\n\n // Draw the line.\n line(x, 0, x, y);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A calm sea drawn in gray against a black sky.');\n}\n\nfunction draw() {\n background(200);\n\n // Set the noise level and scale.\n let noiseLevel = 100;\n let noiseScale = 0.002;\n\n // Iterate from left to right.\n for (let x = 0; x < 100; x += 1) {\n // Scale the input coordinates.\n let nx = noiseScale * x;\n let nt = noiseScale * frameCount;\n\n // Compute the noise value.\n let y = noiseLevel * noise(nx, nt);\n\n // Draw the line.\n line(x, 0, x, y);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Set the noise level and scale.\n let noiseLevel = 255;\n let noiseScale = 0.01;\n\n // Iterate from top to bottom.\n for (let y = 0; y < 100; y += 1) {\n // Iterate from left to right.\n for (let x = 0; x < 100; x += 1) {\n // Scale the input coordinates.\n let nx = noiseScale * x;\n let ny = noiseScale * y;\n\n // Compute the noise value.\n let c = noiseLevel * noise(nx, ny);\n\n // Draw the point.\n stroke(c);\n point(x, y);\n }\n }\n\n describe('A gray cloudy pattern.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A gray cloudy pattern that changes.');\n}\n\nfunction draw() {\n // Set the noise level and scale.\n let noiseLevel = 255;\n let noiseScale = 0.009;\n\n // Iterate from top to bottom.\n for (let y = 0; y < 100; y += 1) {\n // Iterate from left to right.\n for (let x = 0; x < width; x += 1) {\n // Scale the input coordinates.\n let nx = noiseScale * x;\n let ny = noiseScale * y;\n let nt = noiseScale * frameCount;\n\n // Compute the noise value.\n let c = noiseLevel * noise(nx, ny, nt);\n\n // Draw the point.\n stroke(c);\n point(x, y);\n }\n }\n}\n
\nAjusta el carácter del ruido producido por la\n\n\nfunción noise().
\n\n\nLos valores de ruido Perlin se crean sumando capas de ruido.\n\n\nLas capas de ruido, llamadas octavas, son similares a los armónicos en la música.\n\n\nLas octavas más bajas contribuyen más a la señal de salida. Estas definen la intensidad\n\n\npromedio del ruido. Las octavas más altas crean detalles más finos.
\n\n\nDe forma predeterminada, los valores de ruido se crean combinando cuatro octavas. Cada octava mas alta\n\n\naporta la mitad (un 50% menos) que su predecesor.\n\n\nnoiseDetail()
cambia el número de octavas y la cantidad de caída. \n\n\nPor ejemplo, llamar noiseDetail(6, 0.25)
garantiza que\n\n\nnoise() utilizará seis octavas. Cada octava mas alta\n\n\naportará el 25% de su predecesor (un 75% menos). Los valores de caída\n\nentre 0 y 1 son válidos. Sin embargo, valores de caída superiores a 0,5\n\n\npodrían resultar en valores de ruido superiores a 1.
número de octavas que utilizará el ruido.
"],"type":[0,"Número"]}],[0,{"name":[0,"falloff"],"description":[0,"\nfactor de caída para cada octava.
"],"type":[0,"Número"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Set the noise level and scale.\n let noiseLevel = 255;\n let noiseScale = 0.02;\n\n // Iterate from top to bottom.\n for (let y = 0; y < 100; y += 1) {\n // Iterate from left to right.\n for (let x = 0; x < 50; x += 1) {\n // Scale the input coordinates.\n let nx = noiseScale * x;\n let ny = noiseScale * y;\n\n // Compute the noise value with six octaves\n // and a low falloff factor.\n noiseDetail(6, 0.25);\n let c = noiseLevel * noise(nx, ny);\n\n // Draw the left side.\n stroke(c);\n point(x, y);\n\n // Compute the noise value with four octaves\n // and a high falloff factor.\n noiseDetail(4, 0.5);\n c = noiseLevel * noise(nx, ny);\n\n // Draw the right side.\n stroke(c);\n point(x + 50, y);\n }\n }\n\n describe('Two gray cloudy patterns. The pattern on the right is cloudier than the pattern on the left.');\n}\n
\nEstablece una semilla aleatoria para la función noise().
\n\n\nDe forma predeterminada, noise() produce diferentes\nresultados cada vez que se ejecuta un boceto. \nLlamar a noiseSeed()
con un argumento constante,\n\n\ncomo noiseSeed(99)
, hace que noise() produzca los\n\n\nmismos resultados cada vez que se ejecuta un boceto.
valor de la semilla aleatoria.
"],"type":[0,"Número"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Set the noise seed for consistent results.\n noiseSeed(99);\n\n describe('A black rectangle that grows randomly, first to the right and then to the left.');\n}\n\nfunction draw() {\n // Set the noise level and scale.\n let noiseLevel = 100;\n let noiseScale = 0.005;\n\n // Scale the input coordinate.\n let nt = noiseScale * frameCount;\n\n // Compute the noise value.\n let x = noiseLevel * noise(nt);\n\n // Draw the line.\n line(x, 0, x, height);\n}\n
\nCalcula el arco coseno de un número.
\n\n\nacos()
es el inverso de cos(). \n\nEspera argumentos en el rango de -1 a 1. Por defecto, acos()
devuelve valores\nen el rango de 0 a π (aproximadamente 3,14). \n\nSi el angleMode() es DEGREES
, devuelve valores en el rango de 0 a 180.
valor cuyo arco coseno se va a calcular.
"],"type":[0,"Número"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"arco coseno del valor dado."],"type":[0,"Número"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate cos() and acos() values.\n let a = PI;\n let c = cos(a);\n let ac = acos(c);\n\n // Display the values.\n text(`${round(a, 3)}`, 35, 25);\n text(`${round(c, 3)}`, 35, 50);\n text(`${round(ac, 3)}`, 35, 75);\n\n describe('The numbers 3.142, -1, and 3.142 written on separate rows.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate cos() and acos() values.\n let a = PI + QUARTER_PI;\n let c = cos(a);\n let ac = acos(c);\n\n // Display the values.\n text(`${round(a, 3)}`, 35, 25);\n text(`${round(c, 3)}`, 35, 50);\n text(`${round(ac, 3)}`, 35, 75);\n\n describe('The numbers 3.927, -0.707, and 2.356 written on separate rows.');\n}\n
\nCambia el sistema de unidades utilizado para medir ángulos.
\n\n\nLos grados y radianes son unidades utilizadas para medir ángulos. Hay 360˚ en\n\n\nuna rotación completa, que equivale a 2 × π (aproximadamente 6,28) radianes.
\n\n\nFunciones como rotate() y\n\n\nsin() esperan ángulos medidos en radianes por\npor defecto.\n\n\nLlamar a angleMode(DEGREES)
cambia la unidad predeterminada a grados. Llamar\n\n\nangleMode(RADIANS)
cambia de vuelta a radianes.
Llamar angleMode()
sin argumentos devuelve el modo de ángulos actual, que\n\n\nes RADIANS
o DEGREES
.
ya sea RADIANS o DEGREES.
"],"type":[0,"Constante"]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Rotate 1/8 turn.\n rotate(QUARTER_PI);\n\n // Draw a line.\n line(0, 0, 80, 0);\n\n describe('A diagonal line radiating from the top-left corner of a square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Rotate 1/8 turn.\n rotate(45);\n\n // Draw a line.\n line(0, 0, 80, 0);\n\n describe('A diagonal line radiating from the top-left corner of a square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Calculate the angle to rotate.\n let angle = TWO_PI / 7;\n\n // Move the origin to the center.\n translate(50, 50);\n\n // Style the flower.\n noStroke();\n fill(255, 50);\n\n // Draw the flower.\n for (let i = 0; i < 7; i += 1) {\n ellipse(0, 0, 80, 20);\n rotate(angle);\n }\n\n describe('A translucent white flower on a dark background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(50);\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Calculate the angle to rotate.\n let angle = 360 / 7;\n\n // Move the origin to the center.\n translate(50, 50);\n\n // Style the flower.\n noStroke();\n fill(255, 50);\n\n // Draw the flower.\n for (let i = 0; i < 7; i += 1) {\n ellipse(0, 0, 80, 20);\n rotate(angle);\n }\n\n describe('A translucent white flower on a dark background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white ball on a string oscillates left and right.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the coordinates.\n let x = 30 * cos(frameCount * 0.05) + 50;\n let y = 50;\n\n // Draw the oscillator.\n line(50, y, x, y);\n circle(x, y, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Use degrees.\n angleMode(DEGREES);\n\n describe('A white ball on a string oscillates left and right.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the coordinates.\n let x = 30 * cos(frameCount * 2.86) + 50;\n let y = 50;\n\n // Draw the oscillator.\n line(50, y, x, y);\n circle(x, y, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw the upper line.\n rotate(PI / 6);\n line(0, 0, 80, 0);\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Draw the lower line.\n rotate(30);\n line(0, 0, 80, 0);\n\n describe('Two diagonal lines radiating from the top-left corner of a square. The lines are oriented 30 degrees from the edges of the square and 30 degrees apart from each other.');\n}\n
\nCalcula el arco seno de un número.
\n\n\nasin()
es el inverso de sin(). \n\nEspera valores de entrada en el rango de -1 a 1. Por defecto, asin()
devuelve valores en el\nrango -π ÷ 2 (aproximadamente -1,57) a π ÷ 2 (aproximadamente 1,57). \n\nSi el angleMode() es DEGREES
, devuelve valores en el rango -90 a 90.
valor cuyo arco seno se va a calcular.
"],"type":[0,"Número"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"arco seno del valor dado."],"type":[0,"Número"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate sin() and asin() values.\n let a = PI / 3;\n let s = sin(a);\n let as = asin(s);\n\n // Display the values.\n text(`${round(a, 3)}`, 35, 25);\n text(`${round(s, 3)}`, 35, 50);\n text(`${round(as, 3)}`, 35, 75);\n\n describe('The numbers 1.047, 0.866, and 1.047 written on separate rows.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate sin() and asin() values.\n let a = PI + PI / 3;\n let s = sin(a);\n let as = asin(s);\n\n // Display the values.\n text(`${round(a, 3)}`, 35, 25);\n text(`${round(s, 3)}`, 35, 50);\n text(`${round(as, 3)}`, 35, 75);\n\n describe('The numbers 4.189, -0.866, and -1.047 written on separate rows.');\n}\n
\nCalcula el arco tangente de un número.
\n\n\natan()
es el inverso de tan(). \n\nEspera valores de entrada en el rango de -Infinito a Infinito. Por defecto, atan()
\ndevuelve\nvalores en el rango -π ÷ 2 (aproximadamente -1,57) a π ÷ 2 (alrededor de 1,57). \n\nSi angleMode() es\n
valor cuyo arco tangente se va a calcular.
"],"type":[0,"Número"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"arco tangente del valor dado."],"type":[0,"Número"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate tan() and atan() values.\n let a = PI / 3;\n let t = tan(a);\n let at = atan(t);\n\n // Display the values.\n text(`${round(a, 3)}`, 35, 25);\n text(`${round(t, 3)}`, 35, 50);\n text(`${round(at, 3)}`, 35, 75);\n\n describe('The numbers 1.047, 1.732, and 1.047 written on separate rows.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate tan() and atan() values.\n let a = PI + PI / 3;\n let t = tan(a);\n let at = atan(t);\n\n // Display the values.\n text(`${round(a, 3)}`, 35, 25);\n text(`${round(t, 3)}`, 35, 50);\n text(`${round(at, 3)}`, 35, 75);\n\n describe('The numbers 4.189, 1.732, and 1.047 written on separate rows.');\n}\n
\nCalcula el ángulo formado por un punto, el origen y el eje x positivo.
\n\n\natan2()
se utiliza con mayor frecuencia para orientar la geometría a la posición del ratón,\n\n\ncomo en atan2(mouseY, mouseX)
. El primer parámetro es la\ncoordenada y del punto, mientras el segundo parámetro es su coordenada x.
Por defecto, atan2()
devuelve valores en el rango de\n-π (aproximadamente -3,14) a π (3,14). \n\nSi el angleMode() es DEGREES
, devuelve valores en el rango -180 a 180.
coordenada y del punto.
"],"type":[0,"Número"]}],[0,{"name":[0,"x"],"description":[0,"\ncoordenada x del punto.
"],"type":[0,"Número"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"arco tangente del punto dado."],"type":[0,"Número"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A rectangle at the top-left of the canvas rotates with mouse movements.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the angle between the mouse\n // and the origin.\n let a = atan2(mouseY, mouseX);\n\n // Rotate.\n rotate(a);\n\n // Draw the shape.\n rect(0, 0, 60, 10);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A rectangle at the center of the canvas rotates with mouse movements.');\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Get the mouse's coordinates relative to the origin.\n let x = mouseX - 50;\n let y = mouseY - 50;\n\n // Calculate the angle between the mouse and the origin.\n let a = atan2(y, x);\n\n // Rotate.\n rotate(a);\n\n // Draw the shape.\n rect(-30, -5, 60, 10);\n}\n
\nCalcula el coseno de un ángulo.
\n\n\ncos()
es útil para muchas tareas geométricas en programación creativa.\nLos valores devueltos oscilan entre -1 y 1 a medida que aumenta el ángulo de entrada.\n
el ángulo.
"],"type":[0,"Número"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"coseno del ángulo."],"type":[0,"Número"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white ball on a string oscillates left and right.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the coordinates.\n let x = 30 * cos(frameCount * 0.05) + 50;\n let y = 50;\n\n // Draw the oscillator.\n line(50, y, x, y);\n circle(x, y, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots form a wave pattern.');\n}\n\nfunction draw() {\n // Calculate the coordinates.\n let x = frameCount;\n let y = 30 * cos(x * 0.1) + 50;\n\n // Draw the point.\n point(x, y);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots form an infinity symbol.');\n}\n\nfunction draw() {\n // Calculate the coordinates.\n let x = 30 * cos(frameCount * 0.1) + 50;\n let y = 10 * sin(frameCount * 0.2) + 50;\n\n // Draw the point.\n point(x, y);\n}\n
\nConvierte un ángulo medido en radianes a su valor en grados.
\n\nLos grados y radianes son unidades utilizadas para medir ángulos. Hay 360˚ en una rotación completa, que equivale a 2 × π (aproximadamente 6,28) radianes.
\n\nEl mismo ángulo se puede expresar con cualquier unidad. Por ejemplo, 90° es un cuarto de rotación completa. En radianes este mismo ángulo es 2 × π ÷ 4\n\n(aproximadamente 1,57) .
"],"line":[0,479],"params":[1,[[0,{"name":[0,"radians"],"description":[0,"\nvalor en radianes para convertir a grados.
"],"type":[0,"Número"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"ángulo convertido."],"type":[0,"Número"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Calculate the angle conversion.\n let rad = QUARTER_PI;\n let deg = degrees(rad);\n\n // Display the conversion.\n text(`${round(rad, 2)} rad = ${deg}˚`, 10, 50);\n\n describe('The text \"0.79 rad = 45˚\".');\n}\n
\nConvierte un ángulo medido en grados a su valor en radianes.
\n\nLos grados y radianes son unidades utilizados para medir ángulos. Hay 360˚ en una rotación completa, que equivale a 2 × π (aproximadamente 6,28) radianes.
\n\nEl mismo ángulo se puede expresar con cualquier unidad. Por ejemplo, 90° es un\n\ncuarto de rotación completa. En radianes este mismo ángulo es 2 × π ÷ 4\n\n(aproximadamente 1,57).
"],"line":[0,515],"params":[1,[[0,{"name":[0,"degrees"],"description":[0,"\nvalor en grados para convertir a radianes.
"],"type":[0,"Número"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"ángulo convertido."],"type":[0,"Número"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Caclulate the angle conversion.\n let deg = 45;\n let rad = radians(deg);\n\n // Display the angle conversion.\n text(`${deg}˚ = ${round(rad, 3)} rad`, 10, 50);\n\n describe('The text \"45˚ = 0.785 rad\".');\n}\n
\nCalcula el seno de un ángulo.
\n\n\nsin()
es útil para muchas tareas geométricas en codificación creativa.\nLos valores devueltos oscilan entre -1 y 1 a medida que aumenta el ángulo de entrada.\n
el ángulo.
"],"type":[0,"Número"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"seno del ángulo."],"type":[0,"Número"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white ball on a string oscillates up and down.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the coordinates.\n let x = 50;\n let y = 30 * sin(frameCount * 0.05) + 50;\n\n // Draw the oscillator.\n line(50, y, x, y);\n circle(x, y, 20);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots form a wave pattern.');\n}\n\nfunction draw() {\n // Calculate the coordinates.\n let x = frameCount;\n let y = 30 * sin(x * 0.1) + 50;\n\n // Draw the point.\n point(x, y);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of black dots form an infinity symbol.');\n}\n\nfunction draw() {\n // Calculate the coordinates.\n let x = 30 * cos(frameCount * 0.1) + 50;\n let y = 10 * sin(frameCount * 0.2) + 50;\n\n // Draw the point.\n point(x, y);\n}\n
\nCalcula la tangente de un ángulo.
\n\n\ntan()
es útil para muchas tareas geométricas en codificación creativa.\nDevuelve valores en el rango de -Infinito a Infinito y se repite periódicamente con el aumento\n\ndel ángulo de entrada.\n\ntan()
tiene en cuenta el valor actual de\n\n\nangleMode().
el ángulo.
"],"type":[0,"Número"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"tangente del ángulo."],"type":[0,"Número"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe('A series of identical curves drawn with black dots. Each curve starts from the top of the canvas, continues down at a slight angle, flattens out at the middle of the canvas, then continues to the bottom.');\n}\n\nfunction draw() {\n // Calculate the coordinates.\n let x = frameCount;\n let y = 5 * tan(x * 0.1) + 50;\n\n // Draw the point.\n point(x, y);\n}\n
\nCrea un nuevo objeto p5.Vector.
\nExisten varias maneras de pensar sobre los vectores. Una es como\nflechas en el espacio, caracterizadas por su magnitud (longitud)\ny dirección. Este punto de vista es útil para programar movimiento.
\n Las componentes de un vector determinan su magnitud y dirección.\nPor ejemplo, llamar createVector(3, 4)
crea un nuevo\np5.Vector con una componente x de 3\ny una componente y de 4. Desde el origen, la punta de este vector se\nencuentra 3 unidades a la derecha y 4 unidades hacia arriba.
Los objetos p5.Vector se usan\nhabitualmente para programar movimiento debido a que simplifican algunos\ncálculos matemáticos. Por ejemplo, una pelota en movimiento tiene una posición\ny una velocidad. La posición describe la ubicación de la pelota en el espacio.\nEl vector de posición de la pelota se extiende desde el origen al centro de la\npelota. La velocidad describe la rapidez y dirección de su movimiento.\nSi la pelota se mueve en línea recta hacia arriba, su vector de velocidad\napunta hacia arriba y su magnitud es proporcional a la rapidez del movimiento.\nSumar el vector de velocidad al vector de posición lo mueve, como en\npos.add(vel)
. Las operaciones matemáticas con vectores dependen\nde los métodos en la clase p5.Vector.
componente x del vector.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"y"],"description":[0,"componente y del vector.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"z"],"description":[0,"componente z del vector.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"un nuevo objeto p5.Vector."],"type":[0,"p5.Vector"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create p5.Vector objects.\n let p1 = createVector(25, 25);\n let p2 = createVector(50, 50);\n let p3 = createVector(75, 75);\n\n // Draw the dots.\n strokeWeight(5);\n point(p1);\n point(p2);\n point(p3);\n\n describe('Three black dots form a diagonal line from top left to bottom right.');\n}\n
\n\nlet pos;\nlet vel;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create p5.Vector objects.\n pos = createVector(50, 100);\n vel = createVector(0, -1);\n\n describe('A black dot moves from bottom to top on a gray square. The dot reappears at the bottom when it reaches the top.');\n}\n\nfunction draw() {\n background(200);\n\n // Add velocity to position.\n pos.add(vel);\n\n // If the dot reaches the top of the canvas,\n // restart from the bottom.\n if (pos.y < 0) {\n pos.y = 100;\n }\n\n // Draw the dot.\n strokeWeight(5);\n point(pos);\n}\n
\nMethod for executing an HTTP request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text.
\nFor more advanced use, you may also pass in the path as the first argument\nand a object as the second argument, the signature follows the one specified\nin the Fetch API specification.\nThis method is suitable for fetching files up to size of 64MB when \"GET\" is used.
name of the file or url to load
\n"],"type":[0,"String"]}],[0,{"name":[0,"method"],"description":[0,"either \"GET\", \"POST\", or \"PUT\",\n defaults to \"GET\"
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"datatype"],"description":[0,"\"json\", \"jsonp\", \"xml\", or \"text\"
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"data"],"description":[0,"param data passed sent with request
\n"],"type":[0,"Object"],"optional":[0,true]}],[0,{"name":[0,"callback"],"description":[0,"function to be executed after\n httpGet() completes, data is passed in\n as first argument
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,"function to be executed if\n there is an error, response is passed\n in as first argument
\n"],"type":[0,"Function"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"path"],"description":[0,""],"type":[0,"String"]}],[0,{"name":[0,"options"],"description":[0,"Request object options as documented in the\n \"fetch\" API\nreference
\n"],"type":[0,"Object"]}],[0,{"name":[0,"callback"],"description":[0,""],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,""],"type":[0,"Function"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"A promise that resolves with the data when the operation\n completes successfully or rejects with the error after\n one occurs."],"type":[0,"Promise"]}],"example":[1,[[0,"\n\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\n\n// displays an animation of all USGS earthquakes\nlet earthquakes;\nlet eqFeatureIndex = 0;\n\nfunction preload() {\n let url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson';\n httpDo(\n url,\n {\n method: 'GET',\n // Other Request options, like special headers for apis\n headers: { authorization: 'Bearer secretKey' }\n },\n function(res) {\n earthquakes = res;\n }\n );\n}\n\nfunction draw() {\n // wait until the data is loaded\n if (!earthquakes || !earthquakes.features[eqFeatureIndex]) {\n return;\n }\n clear();\n\n let feature = earthquakes.features[eqFeatureIndex];\n let mag = feature.properties.mag;\n let rad = mag / 11 * ((width + height) / 2);\n fill(255, 0, 0, 100);\n ellipse(width / 2 + random(-2, 2), height / 2 + random(-2, 2), rad, rad);\n\n if (eqFeatureIndex >= earthquakes.features.length) {\n eqFeatureIndex = 0;\n } else {\n eqFeatureIndex += 1;\n }\n}\n
\nMethod for executing an HTTP GET request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text. This is equivalent to\ncalling httpDo(path, 'GET')
. The 'binary' datatype will return\na Blob object, and the 'arrayBuffer' datatype will return an ArrayBuffer\nwhich can be used to initialize typed arrays (such as Uint8Array).
name of the file or url to load
\n"],"type":[0,"String"]}],[0,{"name":[0,"datatype"],"description":[0,"\"json\", \"jsonp\", \"binary\", \"arrayBuffer\",\n \"xml\", or \"text\"
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"data"],"description":[0,"param data passed sent with request
\n"],"type":[0,"Object|Boolean"],"optional":[0,true]}],[0,{"name":[0,"callback"],"description":[0,"function to be executed after\n httpGet() completes, data is passed in\n as first argument
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,"function to be executed if\n there is an error, response is passed\n in as first argument
\n"],"type":[0,"Function"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"path"],"description":[0,""],"type":[0,"String"]}],[0,{"name":[0,"data"],"description":[0,""],"type":[0,"Object|Boolean"]}],[0,{"name":[0,"callback"],"description":[0,""],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,""],"type":[0,"Function"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"path"],"description":[0,""],"type":[0,"String"]}],[0,{"name":[0,"callback"],"description":[0,""],"type":[0,"Function"]}],[0,{"name":[0,"errorCallback"],"description":[0,""],"type":[0,"Function"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"A promise that resolves with the data when the operation\n completes successfully or rejects with the error after\n one occurs."],"type":[0,"Promise"]}],"example":[1,[[0,"\n\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nlet earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n let url =\n 'https://earthquake.usgs.gov/fdsnws/event/1/query?' +\n 'format=geojson&limit=1&orderby=time';\n httpGet(url, 'jsonp', false, function(response) {\n // when the HTTP request completes, populate the variable that holds the\n // earthquake data used in the visualization.\n earthquakes = response;\n });\n}\n\nfunction draw() {\n if (!earthquakes) {\n // Wait until the earthquake data has loaded before drawing.\n return;\n }\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n let earthquakeMag = earthquakes.features[0].properties.mag;\n let earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n noLoop();\n}\n
Method for executing an HTTP POST request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text. This is equivalent to\ncalling httpDo(path, 'POST')
.
name of the file or url to load
\n"],"type":[0,"String"]}],[0,{"name":[0,"datatype"],"description":[0,"\"json\", \"jsonp\", \"xml\", or \"text\".\n If omitted, httpPost() will guess.
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"data"],"description":[0,"param data passed sent with request
\n"],"type":[0,"Object|Boolean"],"optional":[0,true]}],[0,{"name":[0,"callback"],"description":[0,"function to be executed after\n httpPost() completes, data is passed in\n as first argument
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,"function to be executed if\n there is an error, response is passed\n in as first argument
\n"],"type":[0,"Function"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"path"],"description":[0,""],"type":[0,"String"]}],[0,{"name":[0,"data"],"description":[0,""],"type":[0,"Object|Boolean"]}],[0,{"name":[0,"callback"],"description":[0,""],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,""],"type":[0,"Function"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"path"],"description":[0,""],"type":[0,"String"]}],[0,{"name":[0,"callback"],"description":[0,""],"type":[0,"Function"]}],[0,{"name":[0,"errorCallback"],"description":[0,""],"type":[0,"Function"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"A promise that resolves with the data when the operation\n completes successfully or rejects with the error after\n one occurs."],"type":[0,"Promise"]}],"example":[1,[[0,"\n\n// Examples use jsonplaceholder.typicode.com for a Mock Data API\n\nlet url = 'https://jsonplaceholder.typicode.com/posts';\nlet postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is very cool.' };\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n}\n\nfunction mousePressed() {\n httpPost(url, 'json', postData, function(result) {\n strokeWeight(2);\n text(result.body, mouseX, mouseY);\n });\n}\n
\n\nlet url = 'ttps://invalidURL'; // A bad URL that will cause errors\nlet postData = { title: 'p5 Clicked!', body: 'p5.js is very cool.' };\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n}\n\nfunction mousePressed() {\n httpPost(\n url,\n 'json',\n postData,\n function(result) {\n // ... won't be called\n },\n function(error) {\n strokeWeight(2);\n text(error.toString(), mouseX, mouseY);\n }\n );\n}\n
This method is suitable for fetching files up to size of 64MB.
\n"],"line":[0,986],"params":[1,[[0,{"name":[0,"file"],"description":[0,"name of the file or URL to load
\n"],"type":[0,"String"]}],[0,{"name":[0,"callback"],"description":[0,"function to be executed after loadBytes()\n completes
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,"function to be executed if there\n is an error
\n"],"type":[0,"Function"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"an object whose 'bytes' property will be the loaded buffer"],"type":[0,"Object"]}],"example":[1,[[0,"\n\nlet data;\n\nfunction preload() {\n data = loadBytes('/assets/mammals.xml');\n}\n\nfunction setup() {\n for (let i = 0; i < 5; i++) {\n console.log(data.bytes[i].toString(16));\n }\n describe('no image displayed');\n}\n
Loads a JSON file to create an Object
.
JavaScript Object Notation\n(JSON)\nis a standard format for sending data between applications. The format is\nbased on JavaScript objects which have keys and values. JSON files store\ndata in an object with strings as keys. Values can be strings, numbers,\nBooleans, arrays, null
, or other objects.
The first parameter, path
, is always a string with the path to the file.\nPaths to local files should be relative, as in\nloadJSON('/assets/data.json')
. URLs such as\n'https://example.com/data.json'
may be blocked due to browser security.
The second parameter, successCallback
, is optional. If a function is\npassed, as in loadJSON('/assets/data.json', handleData)
, then the\nhandleData()
function will be called once the data loads. The object\ncreated from the JSON data will be passed to handleData()
as its only argument.
The third parameter, failureCallback
, is also optional. If a function is\npassed, as in loadJSON('/assets/data.json', handleData, handleFailure)
,\nthen the handleFailure()
function will be called if an error occurs while\nloading. The Error
object will be passed to handleFailure()
as its only\nargument.
Note: Data can take time to load. Calling loadJSON()
within\npreload() ensures data loads before it's used in\nsetup() or draw().
path of the JSON file to be loaded.
\n"],"type":[0,"String"]}],[0,{"name":[0,"successCallback"],"description":[0,"function to call once the data is loaded. Will be passed the object.
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,"function to call if the data fails to load. Will be passed an Error
event object.
\nlet myData;\n\n// Load the JSON and create an object.\nfunction preload() {\n myData = loadJSON('/assets/data.json');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the circle.\n fill(myData.color);\n noStroke();\n\n // Draw the circle.\n circle(myData.x, myData.y, myData.d);\n\n describe('A pink circle on a gray background.');\n}\n
\n\nlet myData;\n\n// Load the JSON and create an object.\nfunction preload() {\n myData = loadJSON('/assets/data.json');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object and make it transparent.\n let c = color(myData.color);\n c.setAlpha(80);\n\n // Style the circles.\n fill(c);\n noStroke();\n\n // Iterate over the myData.bubbles array.\n for (let b of myData.bubbles) {\n // Draw a circle for each bubble.\n circle(b.x, b.y, b.d);\n }\n\n describe('Several pink bubbles floating in a blue sky.');\n}\n
\n\nlet myData;\n\n// Load the GeoJSON and create an object.\nfunction preload() {\n myData = loadJSON('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get data about the most recent earthquake.\n let quake = myData.features[0].properties;\n\n // Draw a circle based on the earthquake's magnitude.\n circle(50, 50, quake.mag * 10);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(11);\n\n // Display the earthquake's location.\n text(quake.place, 5, 80, 100);\n\n describe(`A white circle on a gray background. The text \"${quake.place}\" is written beneath the circle.`);\n}\n
\n\nlet bigQuake;\n\n// Load the GeoJSON and preprocess it.\nfunction preload() {\n loadJSON(\n 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson',\n handleData\n );\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw a circle based on the earthquake's magnitude.\n circle(50, 50, bigQuake.mag * 10);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(11);\n\n // Display the earthquake's location.\n text(bigQuake.place, 5, 80, 100);\n\n describe(`A white circle on a gray background. The text \"${bigQuake.place}\" is written beneath the circle.`);\n}\n\n// Find the biggest recent earthquake.\nfunction handleData(data) {\n let maxMag = 0;\n // Iterate over the earthquakes array.\n for (let quake of data.features) {\n // Reassign bigQuake if a larger\n // magnitude quake is found.\n if (quake.properties.mag > maxMag) {\n bigQuake = quake.properties;\n }\n }\n}\n
\n\nlet bigQuake;\n\n// Load the GeoJSON and preprocess it.\nfunction preload() {\n loadJSON(\n 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson',\n handleData,\n handleError\n );\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw a circle based on the earthquake's magnitude.\n circle(50, 50, bigQuake.mag * 10);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(11);\n\n // Display the earthquake's location.\n text(bigQuake.place, 5, 80, 100);\n\n describe(`A white circle on a gray background. The text \"${bigQuake.place}\" is written beneath the circle.`);\n}\n\n// Find the biggest recent earthquake.\nfunction handleData(data) {\n let maxMag = 0;\n // Iterate over the earthquakes array.\n for (let quake of data.features) {\n // Reassign bigQuake if a larger\n // magnitude quake is found.\n if (quake.properties.mag > maxMag) {\n bigQuake = quake.properties;\n }\n }\n}\n\n// Log any errors to the console.\nfunction handleError(error) {\n console.log('Oops!', error);\n}\n
\nLoads a text file to create an Array
.
The first parameter, path
, is always a string with the path to the file.\nPaths to local files should be relative, as in\nloadStrings('/assets/data.txt')
. URLs such as\n'https://example.com/data.txt'
may be blocked due to browser security.
The second parameter, successCallback
, is optional. If a function is\npassed, as in loadStrings('/assets/data.txt', handleData)
, then the\nhandleData()
function will be called once the data loads. The array\ncreated from the text data will be passed to handleData()
as its only\nargument.
The third parameter, failureCallback
, is also optional. If a function is\npassed, as in loadStrings('/assets/data.txt', handleData, handleFailure)
,\nthen the handleFailure()
function will be called if an error occurs while\nloading. The Error
object will be passed to handleFailure()
as its only\nargument.
Note: Data can take time to load. Calling loadStrings()
within\npreload() ensures data loads before it's used in\nsetup() or draw().
path of the text file to be loaded.
\n"],"type":[0,"String"]}],[0,{"name":[0,"successCallback"],"description":[0,"function to call once the data is\n loaded. Will be passed the array.
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,"function to call if the data fails to\n load. Will be passed an Error
event\n object.
\nlet myData;\n\n// Load the text and create an array.\nfunction preload() {\n myData = loadStrings('/assets/test.txt');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Select a random line from the text.\n let phrase = random(myData);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display the text.\n text(phrase, 10, 50, 90);\n\n describe(`The text \"${phrase}\" written in black on a gray background.`);\n}\n
\n\nlet lastLine;\n\n// Load the text and preprocess it.\nfunction preload() {\n loadStrings('/assets/test.txt', handleData);\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display the text.\n text(lastLine, 10, 50, 90);\n\n describe('The text \"I talk like an orange\" written in black on a gray background.');\n}\n\n// Select the last line from the text.\nfunction handleData(data) {\n lastLine = data[data.length - 1];\n}\n
\n\nlet lastLine;\n\n// Load the text and preprocess it.\nfunction preload() {\n loadStrings('/assets/test.txt', handleData, handleError);\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display the text.\n text(lastLine, 10, 50, 90);\n\n describe('The text \"I talk like an orange\" written in black on a gray background.');\n}\n\n// Select the last line from the text.\nfunction handleData(data) {\n lastLine = data[data.length - 1];\n}\n\n// Log any errors to the console.\nfunction handleError(error) {\n console.error('Oops!', error);\n}\n
\nReads the contents of a file or URL and creates a p5.Table object with\nits values. If a file is specified, it must be located in the sketch's\n\"data\" folder. The filename parameter can also be a URL to a file found\nonline. By default, the file is assumed to be comma-separated (in CSV\nformat). Table only looks for a header row if the 'header' option is\nincluded.
\nThis method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. Calling loadTable() inside preload()\nguarantees to complete the operation before setup() and draw() are called.\nOutside of preload(), you may supply a callback function to handle the\nobject:
\nAll files loaded and saved use UTF-8 encoding. This method is suitable for fetching files up to size of 64MB.
\n"],"line":[0,505],"params":[1,[[0,{"name":[0,"filename"],"description":[0,"name of the file or URL to load
\n"],"type":[0,"String"]}],[0,{"name":[0,"extension"],"description":[0,"parse the table by comma-separated values \"csv\", semicolon-separated\n values \"ssv\", or tab-separated values \"tsv\"
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"header"],"description":[0,"\"header\" to indicate table has header row
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"callback"],"description":[0,"function to be executed after\n loadTable() completes. On success, the\n Table object is passed in as the\n first argument.
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,"function to be executed if\n there is an error, response is passed\n in as first argument
\n"],"type":[0,"Function"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"Table object containing data"],"type":[0,"Object"]}],"example":[1,[[0,"\n\n// Given the following CSV file called \"mammals.csv\"\n// located in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n //the file can be remote\n //table = loadTable(\"https://p5js.org/reference//assets/mammals.csv\",\n // \"csv\", \"header\");\n}\n\nfunction setup() {\n //count the columns\n print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n\n print(table.getColumn('name'));\n //[\"Goat\", \"Leopard\", \"Zebra\"]\n\n //cycle through the table\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++) {\n print(table.getString(r, c));\n }\n describe(`randomly generated text from a file,\n for example \"i smell like butter\"`);\n}\n
\nLoads an XML file to create a p5.XML object.
\nExtensible Markup Language\n(XML)\nis a standard format for sending data between applications. Like HTML, the\nXML format is based on tags and attributes, as in\n.
The first parameter, path
, is always a string with the path to the file.\nPaths to local files should be relative, as in\nloadXML('/assets/data.xml')
. URLs such as 'https://example.com/data.xml'
\nmay be blocked due to browser security.
The second parameter, successCallback
, is optional. If a function is\npassed, as in loadXML('/assets/data.xml', handleData)
, then the\nhandleData()
function will be called once the data loads. The\np5.XML object created from the data will be passed\nto handleData()
as its only argument.
The third parameter, failureCallback
, is also optional. If a function is\npassed, as in loadXML('/assets/data.xml', handleData, handleFailure)
, then\nthe handleFailure()
function will be called if an error occurs while\nloading. The Error
object will be passed to handleFailure()
as its only\nargument.
Note: Data can take time to load. Calling loadXML()
within\npreload() ensures data loads before it's used in\nsetup() or draw().
path of the XML file to be loaded.
\n"],"type":[0,"String"]}],[0,{"name":[0,"successCallback"],"description":[0,"function to call once the data is\n loaded. Will be passed the\n p5.XML object.
\n"],"type":[0,"Function"],"optional":[0,true]}],[0,{"name":[0,"errorCallback"],"description":[0,"function to call if the data fails to\n load. Will be passed an Error
event\n object.
\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get an array with all mammal tags.\n let mammals = myXML.getChildren('mammal');\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Iterate over the mammals array.\n for (let i = 0; i < mammals.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Get the mammal's common name.\n let name = mammals[i].getContent();\n\n // Display the mammal's name.\n text(name, 20, y);\n }\n\n describe(\n 'The words \"Goat\", \"Leopard\", and \"Zebra\" written on three separate lines. The text is black on a gray background.'\n );\n}\n
\n\nlet lastMammal;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n loadXML('/assets/animals.xml', handleData);\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(16);\n\n // Display the content of the last mammal element.\n text(lastMammal, 50, 50);\n\n describe('The word \"Zebra\" written in black on a gray background.');\n}\n\n// Get the content of the last mammal element.\nfunction handleData(data) {\n // Get an array with all mammal elements.\n let mammals = data.getChildren('mammal');\n\n // Get the content of the last mammal.\n lastMammal = mammals[mammals.length - 1].getContent();\n}\n
\n\nlet lastMammal;\n\n// Load the XML and preprocess it.\nfunction preload() {\n loadXML('/assets/animals.xml', handleData, handleError);\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(16);\n\n // Display the content of the last mammal element.\n text(lastMammal, 50, 50);\n\n describe('The word \"Zebra\" written in black on a gray background.');\n}\n\n// Get the content of the last mammal element.\nfunction handleData(data) {\n // Get an array with all mammal elements.\n let mammals = data.getChildren('mammal');\n\n // Get the content of the last mammal.\n lastMammal = mammals[mammals.length - 1].getContent();\n}\n\n// Log any errors to the console.\nfunction handleError(error) {\n console.error('Oops!', error);\n}\n
\nCreates a new p5.PrintWriter object.
\np5.PrintWriter objects provide a way to\nsave a sequence of text data, called the print stream, to the user's\ncomputer. They're low-level objects that enable precise control of text\noutput. Functions such as\nsaveStrings() and\nsaveJSON() are easier to use for simple file\nsaving.
\nThe first parameter, filename
, is the name of the file to be written. If\na string is passed, as in createWriter('words.txt')
, a new\np5.PrintWriter object will be created that\nwrites to a file named words.txt
.
The second parameter, extension
, is optional. If a string is passed, as\nin createWriter('words', 'csv')
, the first parameter will be interpreted\nas the file name and the second parameter as the extension.
name of the file to create.
\n"],"type":[0,"String"]}],[0,{"name":[0,"extension"],"description":[0,"format to use for the file.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"stream for writing data."],"type":[0,"p5.PrintWriter"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display instructions.\n text('Double-click to save', 5, 50, 90);\n\n describe('The text \"Double-click to save\" written in black on a gray background.');\n}\n\n// Save the file when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n // Create a p5.PrintWriter object.\n let myWriter = createWriter('xo.txt');\n\n // Add some lines to the print stream.\n myWriter.print('XOO');\n myWriter.print('OXO');\n myWriter.print('OOX');\n\n // Save the file and close the print stream.\n myWriter.close();\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display instructions.\n text('Double-click to save', 5, 50, 90);\n\n describe('The text \"Double-click to save\" written in black on a gray background.');\n}\n\n// Save the file when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n // Create a p5.PrintWriter object.\n // Use the file format .csv.\n let myWriter = createWriter('mauna_loa_co2', 'csv');\n\n // Add some lines to the print stream.\n myWriter.print('date,ppm_co2');\n myWriter.print('1960-01-01,316.43');\n myWriter.print('1970-01-01,325.06');\n myWriter.print('1980-01-01,337.9');\n myWriter.print('1990-01-01,353.86');\n myWriter.print('2000-01-01,369.45');\n myWriter.print('2020-01-01,413.61');\n\n // Save the file and close the print stream.\n myWriter.close();\n }\n}\n
\nA class to describe a print stream.
\nEach p5.PrintWriter
object provides a way to save a sequence of text\ndata, called the print stream, to the user's computer. It's a low-level\nobject that enables precise control of text output. Functions such as\nsaveStrings() and\nsaveJSON() are easier to use for simple file\nsaving.
Note: createWriter() is the recommended way\nto make an instance of this class.
\n"],"line":[0,1565],"path":[0,"p5/p5.PrintWriter"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/save.mdx"],"slug":[0,"en/p5/save"],"body":[0,"\n\n# save\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"save()"],"module":[0,"IO"],"submodule":[0,"Output"],"file":[0,"src/io/files.js"],"description":[0,"Saves a given element(image, text, json, csv, wav, or html) to the client's\ncomputer. The first parameter can be a pointer to element we want to save.\nThe element can be one of p5.Element,an Array of\nStrings, an Array of JSON, a JSON object, a p5.Table\n, a p5.Image, or a p5.SoundFile (requires\np5.sound). The second parameter is a filename (including extension).The\nthird parameter is for options specific to this type of object. This method\nwill save a file that fits the given parameters.\nIf it is called without specifying an element, by default it will save the\nwhole canvas as an image file. You can optionally specify a filename as\nthe first parameter in such a case.\nNote that it is not recommended to\ncall this method within draw, as it will open a new save dialog on every\nrender.
\n"],"line":[0,1835],"params":[1,[[0,{"name":[0,"objectOrFilename"],"description":[0,"If filename is provided, will\n save canvas as an image with\n either png or jpg extension\n depending on the filename.\n If object is provided, will\n save depending on the object\n and filename (see examples\n above).
\n"],"type":[0,"Object|String"],"optional":[0,true]}],[0,{"name":[0,"filename"],"description":[0,"If an object is provided as the first\n parameter, then the second parameter\n indicates the filename,\n and should include an appropriate\n file extension (see examples above).
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"options"],"description":[0,"Additional options depend on\n filetype. For example, when saving JSON,\n true
indicates that the\n output will be optimized for filesize,\n rather than readability.
\n // Saves the canvas as an image\n cnv = createCanvas(300, 300);\n save(cnv, 'myCanvas.jpg');\n\n // Saves the canvas as an image by default\n save('myCanvas.jpg');\n describe('An example for saving a canvas as an image.');\n
\n // Saves p5.Image as an image\n img = createImage(10, 10);\n save(img, 'myImage.png');\n describe('An example for saving a p5.Image element as an image.');\n
\n // Saves p5.Renderer object as an image\n obj = createGraphics(100, 100);\n save(obj, 'myObject.png');\n describe('An example for saving a p5.Renderer element.');\n
\n let myTable = new p5.Table();\n // Saves table as html file\n save(myTable, 'myTable.html');\n\n // Comma Separated Values\n save(myTable, 'myTable.csv');\n\n // Tab Separated Values\n save(myTable, 'myTable.tsv');\n\n describe(`An example showing how to save a table in formats of\n HTML, CSV and TSV.`);\n
\n let myJSON = { a: 1, b: true };\n\n // Saves pretty JSON\n save(myJSON, 'my.json');\n\n // Optimizes JSON filesize\n save(myJSON, 'my.json', true);\n\n describe('An example for saving JSON to a txt file with some extra arguments.');\n
\n // Saves array of strings to text file with line breaks after each item\n let arrayOfStrings = ['a', 'b'];\n save(arrayOfStrings, 'my.txt');\n describe(`An example for saving an array of strings to text file\n with line breaks.`);\n
Saves an Object
or Array
to a JSON file.
JavaScript Object Notation\n(JSON)\nis a standard format for sending data between applications. The format is\nbased on JavaScript objects which have keys and values. JSON files store\ndata in an object with strings as keys. Values can be strings, numbers,\nBooleans, arrays, null
, or other objects.
The first parameter, json
, is the data to save. The data can be an array,\nas in [1, 2, 3]
, or an object, as in\n{ x: 50, y: 50, color: 'deeppink' }
.
The second parameter, filename
, is a string that sets the file's name.\nFor example, calling saveJSON([1, 2, 3], 'data.json')
saves the array\n[1, 2, 3]
to a file called data.json
on the user's computer.
The third parameter, optimize
, is optional. If true
is passed, as in\nsaveJSON([1, 2, 3], 'data.json', true)
, then all unneeded whitespace will\nbe removed to reduce the file size.
Note: The browser will either save the file immediately or prompt the user\nwith a dialogue window.
\n"],"line":[0,1979],"params":[1,[[0,{"name":[0,"json"],"description":[0,"data to save.
\n"],"type":[0,"Array|Object"]}],[0,{"name":[0,"filename"],"description":[0,"name of the file to be saved.
\n"],"type":[0,"String"]}],[0,{"name":[0,"optimize"],"description":[0,"whether to trim unneeded whitespace. Defaults\n to true
.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display instructions.\n text('Double-click to save', 5, 50, 90);\n\n describe('The text \"Double-click to save\" written in black on a gray background.');\n}\n\n// Save the file when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n // Create an array.\n let data = [1, 2, 3];\n\n // Save the JSON file.\n saveJSON(data, 'numbers.json');\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display instructions.\n text('Double-click to save', 5, 50, 90);\n\n describe('The text \"Double-click to save\" written in black on a gray background.');\n}\n\n// Save the file when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n // Create an object.\n let data = { x: mouseX, y: mouseY };\n\n // Save the JSON file.\n saveJSON(data, 'state.json');\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display instructions.\n text('Double-click to save', 5, 50, 90);\n\n describe('The text \"Double-click to save\" written in black on a gray background.');\n}\n\n// Save the file when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n // Create an object.\n let data = { x: mouseX, y: mouseY };\n\n // Save the JSON file and reduce its size.\n saveJSON(data, 'state.json', true);\n }\n}\n
\nSaves an Array
of String
s to a file, one per line.
The first parameter, list
, is an array with the strings to save.
The second parameter, filename
, is a string that sets the file's name.\nFor example, calling saveStrings(['0', '01', '011'], 'data.txt')
saves\nthe array ['0', '01', '011']
to a file called data.txt
on the user's\ncomputer.
The third parameter, extension
, is optional. If a string is passed, as in\nsaveStrings(['0', '01', '0
1'], 'data', 'txt')`, the second parameter will\nbe interpreted as the file name and the third parameter as the extension.
The fourth parameter, isCRLF
, is also optional, If true
is passed, as\nin saveStrings(['0', '01', '011'], 'data', 'txt', true)
, then two\ncharacters, \\r\\n
, will be added to the end of each string to create new\nlines in the saved file. \\r
is a carriage return (CR) and \\n
is a line\nfeed (LF). By default, only \\n
(line feed) is added to each string in\norder to create new lines.
Note: The browser will either save the file immediately or prompt the user\nwith a dialogue window.
\n"],"line":[0,2118],"params":[1,[[0,{"name":[0,"list"],"description":[0,"data to save.
\n"],"type":[0,"String[]"]}],[0,{"name":[0,"filename"],"description":[0,"name of file to be saved.
\n"],"type":[0,"String"]}],[0,{"name":[0,"extension"],"description":[0,"format to use for the file.
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"isCRLF"],"description":[0,"whether to add \\r\\n
to the end of each\n string. Defaults to false
.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display instructions.\n text('Double-click to save', 5, 50, 90);\n\n describe('The text \"Double-click to save\" written in black on a gray background.');\n}\n\n// Save the file when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n // Create an array.\n let data = ['0', '01', '011'];\n\n // Save the text file.\n saveStrings(data, 'data.txt');\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display instructions.\n text('Double-click to save', 5, 50, 90);\n\n describe('The text \"Double-click to save\" written in black on a gray background.');\n}\n\n// Save the file when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n // Create an array.\n // ASCII art courtesy Wikipedia:\n // https://en.wikipedia.org/wiki/ASCII_art\n let data = [' (\\\\_/) ', \"(='.'=)\", '(\")_(\")'];\n\n // Save the text file.\n saveStrings(data, 'cat', 'txt');\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display instructions.\n text('Double-click to save', 5, 50, 90);\n\n describe('The text \"Double-click to save\" written in black on a gray background.');\n}\n\n// Save the file when the user double-clicks.\nfunction doubleClicked() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n // Create an array.\n // +--+\n // / /|\n // +--+ +\n // | |/\n // +--+\n let data = [' +--+', ' / /|', '+--+ +', '| |/', '+--+'];\n\n // Save the text file.\n // Use CRLF for line endings.\n saveStrings(data, 'box', 'txt', true);\n }\n}\n
\nWrites the contents of a Table object to a file. Defaults to a\ntext file with comma-separated-values ('csv') but can also\nuse tab separation ('tsv'), or generate an HTML table ('html').\nThe file saving process and location of the saved file will\nvary between web browsers.
\n"],"line":[0,2275],"params":[1,[[0,{"name":[0,"Table"],"description":[0,"the Table object to save to a file
\n"],"type":[0,"p5.Table"]}],[0,{"name":[0,"filename"],"description":[0,"the filename to which the Table should be saved
\n"],"type":[0,"String"]}],[0,{"name":[0,"options"],"description":[0,"can be one of \"tsv\", \"csv\", or \"html\"
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n let table;\n\n function setup() {\n table = new p5.Table();\n\n table.addColumn('id');\n table.addColumn('species');\n table.addColumn('name');\n\n let newRow = table.addRow();\n newRow.setNum('id', table.getRowCount() - 1);\n newRow.setString('species', 'Panthera leo');\n newRow.setString('name', 'Lion');\n\n // To save, un-comment next line then click 'run'\n // saveTable(table, 'new.csv');\n\n describe('no image displayed');\n }\n\n // Saves the following to a file called 'new.csv':\n // id,species,name\n // 0,Panthera leo,Lion\n
Returns the current day as a number from 1–31.
\n"],"line":[0,10],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"current day between 1 and 31."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the current day.\n let d = day();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(12);\n textFont('Courier New');\n\n // Display the day.\n text(`Current day: ${d}`, 20, 50, 60);\n\n describe(`The text 'Current day: ${d}' written in black on a gray background.`);\n}\n
\nReturns the current hour as a number from 0–23.
\n"],"line":[0,44],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"current hour between 0 and 23."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the current hour.\n let h = hour();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(12);\n textFont('Courier New');\n\n // Display the hour.\n text(`Current hour: ${h}`, 20, 50, 60);\n\n describe(`The text 'Current hour: ${h}' written in black on a gray background.`);\n}\n
\nReturns the number of milliseconds since a sketch started running.
\nmillis()
keeps track of how long a sketch has been running in\nmilliseconds (thousandths of a second). This information is often\nhelpful for timing events and animations.
If a sketch has a\nsetup() function, then millis()
begins tracking\ntime before the code in setup() runs. If a\nsketch includes a preload() function, then\nmillis()
begins tracking time as soon as the code in\npreload() starts running.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the number of milliseconds the sketch has run.\n let ms = millis();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(10);\n textFont('Courier New');\n\n // Display how long it took setup() to be called.\n text(`Startup time: ${round(ms, 2)} ms`, 5, 50, 90);\n\n describe(\n `The text 'Startup time: ${round(ms, 2)} ms' written in black on a gray background.`\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('The text \"Running time: S sec\" written in black on a gray background. The number S increases as the sketch runs.');\n}\n\nfunction draw() {\n background(200);\n\n // Get the number of seconds the sketch has run.\n let s = millis() / 1000;\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(10);\n textFont('Courier New');\n\n // Display how long the sketch has run.\n text(`Running time: ${nf(s, 1, 1)} sec`, 5, 50, 90);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle oscillates left and right on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Get the number of seconds the sketch has run.\n let s = millis() / 1000;\n\n // Calculate an x-coordinate.\n let x = 30 * sin(s) + 50;\n\n // Draw the circle.\n circle(x, 50, 30);\n}\n
\n\n// Load the GeoJSON.\nfunction preload() {\n loadJSON('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the number of milliseconds the sketch has run.\n let ms = millis();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(11);\n\n // Display how long it took to load the data.\n text(`It took ${round(ms, 2)} ms to load the data`, 5, 50, 100);\n\n describe(\n `The text \"It took ${round(ms, 2)} ms to load the data\" written in black on a gray background.`\n );\n}\n
\nReturns the current minute as a number from 0–59.
\n"],"line":[0,78],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"current minute between 0 and 59."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the current minute.\n let m = minute();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(12);\n textFont('Courier New');\n\n // Display the minute.\n text(`Current minute: ${m}`, 10, 50, 80);\n\n describe(`The text 'Current minute: ${m}' written in black on a gray background.`);\n}\n
\nReturns the current month as a number from 1–12.
\n"],"line":[0,242],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"current month between 1 and 12."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the current month.\n let m = month();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(12);\n textFont('Courier New');\n\n // Display the month.\n text(`Current month: ${m}`, 10, 50, 80);\n\n describe(`The text 'Current month: ${m}' written in black on a gray background.`);\n}\n
\nReturns the current second as a number from 0–59.
\n"],"line":[0,277],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"current second between 0 and 59."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the current second.\n let s = second();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(12);\n textFont('Courier New');\n\n // Display the second.\n text(`Current second: ${s}`, 10, 50, 80);\n\n describe(`The text 'Current second: ${s}' written in black on a gray background.`);\n}\n
\nReturns the current year as a number such as 1999.
\n"],"line":[0,311],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"current year."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the current year.\n let y = year();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(12);\n textFont('Courier New');\n\n // Display the year.\n text(`Current year: ${y}`, 10, 50, 80);\n\n describe(`The text 'Current year: ${y}' written in black on a gray background.`);\n}\n
\nTable objects store data with multiple rows and columns, much\nlike in a traditional spreadsheet. Tables can be generated from\nscratch, dynamically, or using data from an existing file.
\n"],"line":[0,33],"params":[1,[[0,{"name":[0,"rows"],"description":[0,"An array of p5.TableRow objects
\n"],"type":[0,"p5.TableRow[]"],"optional":[0,true]}]]],"chainable":[0,false],"methods":[0,{"addRow":[0,{"description":[0,"Use addRow() to add a new row of data to a p5.Table object. By default,\nan empty row is created. Typically, you would store a reference to\nthe new row in a TableRow object (see newRow in the example above),\nand then set individual values using set().
\nIf a p5.TableRow object is included as a parameter, then that row is\nduplicated and added to the table.
\n"],"path":[0,"p5.Table/addRow"]}],"removeRow":[0,{"description":[0,"Removes a row from the table object.
\n"],"path":[0,"p5.Table/removeRow"]}],"getRow":[0,{"description":[0,"Returns a reference to the specified p5.TableRow. The reference\ncan then be used to get and set values of the selected row.
\n"],"path":[0,"p5.Table/getRow"]}],"getRows":[0,{"description":[0,"Gets all rows from the table. Returns an array of p5.TableRows.
\n"],"path":[0,"p5.Table/getRows"]}],"findRow":[0,{"description":[0,"Finds the first row in the Table that contains the value\nprovided, and returns a reference to that row. Even if\nmultiple rows are possible matches, only the first matching\nrow is returned. The column to search may be specified by\neither its ID or title.
\n"],"path":[0,"p5.Table/findRow"]}],"findRows":[0,{"description":[0,"Finds the rows in the Table that contain the value\nprovided, and returns references to those rows. Returns an\nArray, so for must be used to iterate through all the rows,\nas shown in the example above. The column to search may be\nspecified by either its ID or title.
\n"],"path":[0,"p5.Table/findRows"]}],"matchRow":[0,{"description":[0,"Finds the first row in the Table that matches the regular\nexpression provided, and returns a reference to that row.\nEven if multiple rows are possible matches, only the first\nmatching row is returned. The column to search may be\nspecified by either its ID or title.
\n"],"path":[0,"p5.Table/matchRow"]}],"matchRows":[0,{"description":[0,"Finds the rows in the Table that match the regular expression provided,\nand returns references to those rows. Returns an array, so for must be\nused to iterate through all the rows, as shown in the example. The\ncolumn to search may be specified by either its ID or title.
\n"],"path":[0,"p5.Table/matchRows"]}],"getColumn":[0,{"description":[0,"Retrieves all values in the specified column, and returns them\nas an array. The column may be specified by either its ID or title.
\n"],"path":[0,"p5.Table/getColumn"]}],"clearRows":[0,{"description":[0,"Removes all rows from a Table. While all rows are removed,\ncolumns and column titles are maintained.
\n"],"path":[0,"p5.Table/clearRows"]}],"addColumn":[0,{"description":[0,"Use addColumn() to add a new column to a Table object.\nTypically, you will want to specify a title, so the column\nmay be easily referenced later by name. (If no title is\nspecified, the new column's title will be null.)
\n"],"path":[0,"p5.Table/addColumn"]}],"getColumnCount":[0,{"description":[0,"Returns the total number of columns in a Table.
\n"],"path":[0,"p5.Table/getColumnCount"]}],"getRowCount":[0,{"description":[0,"Returns the total number of rows in a Table.
\n"],"path":[0,"p5.Table/getRowCount"]}],"removeTokens":[0,{"description":[0,"Removes any of the specified characters (or \"tokens\").
\nIf no column is specified, then the values in all columns and\nrows are processed. A specific column may be referenced by\neither its ID or title.
\n"],"path":[0,"p5.Table/removeTokens"]}],"trim":[0,{"description":[0,"Trims leading and trailing whitespace, such as spaces and tabs,\nfrom String table values. If no column is specified, then the\nvalues in all columns and rows are trimmed. A specific column\nmay be referenced by either its ID or title.
\n"],"path":[0,"p5.Table/trim"]}],"removeColumn":[0,{"description":[0,"Use removeColumn() to remove an existing column from a Table\nobject. The column to be removed may be identified by either\nits title (a String) or its index value (an int).\nremoveColumn(0) would remove the first column, removeColumn(1)\nwould remove the second column, and so on.
\n"],"path":[0,"p5.Table/removeColumn"]}],"set":[0,{"description":[0,"Stores a value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n"],"path":[0,"p5.Table/set"]}],"setNum":[0,{"description":[0,"Stores a Float value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n"],"path":[0,"p5.Table/setNum"]}],"setString":[0,{"description":[0,"Stores a String value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n"],"path":[0,"p5.Table/setString"]}],"get":[0,{"description":[0,"Retrieves a value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n"],"path":[0,"p5.Table/get"]}],"getNum":[0,{"description":[0,"Retrieves a Float value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n"],"path":[0,"p5.Table/getNum"]}],"getString":[0,{"description":[0,"Retrieves a String value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n"],"path":[0,"p5.Table/getString"]}],"getObject":[0,{"description":[0,"Retrieves all table data and returns as an object. If a column name is\npassed in, each row object will be stored with that attribute as its\ntitle.
\n"],"path":[0,"p5.Table/getObject"]}],"getArray":[0,{"description":[0,"Retrieves all table data and returns it as a multidimensional array.
\n"],"path":[0,"p5.Table/getArray"]}]}],"properties":[0,{"columns":[0,{"description":[0,"An array containing the names of the columns in the table, if the \"header\" the table is\nloaded with the \"header\" parameter.
\n"],"path":[0,"p5.Table/columns"]}],"rows":[0,{"description":[0,"An array containing the p5.TableRow objects that make up the\nrows of the table. The same result as calling getRows()
\n"],"path":[0,"p5.Table/rows"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.Table"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.Table/addColumn.mdx"],"slug":[0,"en/p5table/addcolumn"],"body":[0,"\n\n# addColumn\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"addColumn()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Use addColumn() to add a new column to a Table object.\nTypically, you will want to specify a title, so the column\nmay be easily referenced later by name. (If no title is\nspecified, the new column's title will be null.)
\n"],"line":[0,631],"params":[1,[[0,{"name":[0,"title"],"description":[0,"title of the given column
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"example":[1,[[0,"\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.addColumn('carnivore');\n table.set(0, 'carnivore', 'no');\n table.set(1, 'carnivore', 'yes');\n table.set(2, 'carnivore', 'no');\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n\n describe('no image displayed');\n }\n
\n Use addRow() to add a new row of data to a p5.Table object. By default,\nan empty row is created. Typically, you would store a reference to\nthe new row in a TableRow object (see newRow in the example above),\nand then set individual values using set().
\nIf a p5.TableRow object is included as a parameter, then that row is\nduplicated and added to the table.
\n"],"line":[0,90],"params":[1,[[0,{"name":[0,"row"],"description":[0,"row to be added to the table
\n"],"type":[0,"p5.TableRow"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,"the row that was added"],"type":[0,"p5.TableRow"]}],"example":[1,[[0,"\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //add a row\n let newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Canis Lupus');\n newRow.setString('name', 'Wolf');\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n\n describe('no image displayed');\n }\n
\n Removes all rows from a Table. While all rows are removed,\ncolumns and column titles are maintained.
\n"],"line":[0,592],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"example":[1,[[0,"\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.clearRows();\n print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n describe('no image displayed');\n }\n
\n An array containing the names of the columns in the table, if the \"header\" the table is\nloaded with the \"header\" parameter.
\n"],"line":[0,43],"itemtype":[0,"property"],"class":[0,"p5.Table"],"example":[1,[[0,"\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //print the column names\n for (let c = 0; c < table.getColumnCount(); c++) {\n print('column ' + c + ' is named ' + table.columns[c]);\n }\n}\n
\nFinds the first row in the Table that contains the value\nprovided, and returns a reference to that row. Even if\nmultiple rows are possible matches, only the first matching\nrow is returned. The column to search may be specified by\neither its ID or title.
\n"],"line":[0,289],"params":[1,[[0,{"name":[0,"value"],"description":[0,"The value to match
\n"],"type":[0,"String"]}],[0,{"name":[0,"column"],"description":[0,"ID number or title of the\n column to search
\n"],"type":[0,"Integer|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"p5.TableRow"]}],"example":[1,[[0,"\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //find the animal named zebra\n let row = table.findRow('Zebra', 'name');\n //find the corresponding species\n print(row.getString('species'));\n describe('no image displayed');\n }\n
\n Finds the rows in the Table that contain the value\nprovided, and returns references to those rows. Returns an\nArray, so for must be used to iterate through all the rows,\nas shown in the example above. The column to search may be\nspecified by either its ID or title.
\n"],"line":[0,351],"params":[1,[[0,{"name":[0,"value"],"description":[0,"The value to match
\n"],"type":[0,"String"]}],[0,{"name":[0,"column"],"description":[0,"ID number or title of the\n column to search
\n"],"type":[0,"Integer|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,"An Array of TableRow objects"],"type":[0,"p5.TableRow[]"]}],"example":[1,[[0,"\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //add another goat\n let newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Scape Goat');\n newRow.setString('name', 'Goat');\n\n //find the rows containing animals named Goat\n let rows = table.findRows('Goat', 'name');\n print(rows.length + ' Goats found');\n describe('no image displayed');\n }\n
\n Retrieves a value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n"],"line":[0,1087],"params":[1,[[0,{"name":[0,"row"],"description":[0,"row ID
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"column"],"description":[0,"columnName (string) or\n ID (number)
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"String|Number"]}],"example":[1,[[0,"\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.get(0, 1));\n //Capra hircus\n print(table.get(0, 'species'));\n //Capra hircus\n describe('no image displayed');\n}\n
\nRetrieves all table data and returns it as a multidimensional array.
\n"],"line":[0,1285],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"Array"]}],"example":[1,[[0,"\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leoperd\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n // table is comma separated value \"CSV\"\n // and has specifiying header for column labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n let tableArray = table.getArray();\n for (let i = 0; i < tableArray.length; i++) {\n print(tableArray[i]);\n }\n describe('no image displayed');\n}\n
\nRetrieves all values in the specified column, and returns them\nas an array. The column may be specified by either its ID or title.
\n"],"line":[0,542],"params":[1,[[0,{"name":[0,"column"],"description":[0,"String or Number of the column to return
\n"],"type":[0,"String|Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,"Array of column values"],"type":[0,"Array"]}],"example":[1,[[0,"\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //getColumn returns an array that can be printed directly\n print(table.getColumn('species'));\n //outputs [\"Capra hircus\", \"Panthera pardus\", \"Equus zebra\"]\n describe('no image displayed');\n }\n
\n Returns the total number of columns in a Table.
\n"],"line":[0,680],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,"Number of columns in this table"],"type":[0,"Integer"]}],"example":[1,[[0,"\n\n // given the cvs file \"blobs.csv\" in /assets directory\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n let table;\n\n function preload() {\n table = loadTable('/assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n let numOfColumn = table.getColumnCount();\n text('There are ' + numOfColumn + ' columns in the table.', 100, 50);\n }\n
\n Retrieves a Float value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n"],"line":[0,1131],"params":[1,[[0,{"name":[0,"row"],"description":[0,"row ID
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"column"],"description":[0,"columnName (string) or\n ID (number)
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"Number"]}],"example":[1,[[0,"\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.getNum(1, 0) + 100);\n //id 1 + 100 = 101\n describe('no image displayed');\n}\n
\nRetrieves all table data and returns as an object. If a column name is\npassed in, each row object will be stored with that attribute as its\ntitle.
\n"],"line":[0,1223],"params":[1,[[0,{"name":[0,"headerColumn"],"description":[0,"Name of the column which should be used to\n title each row object (optional)
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"Object"]}],"example":[1,[[0,"\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n let tableObject = table.getObject();\n\n print(tableObject);\n //outputs an object\n\n describe('no image displayed');\n}\n
\nReturns a reference to the specified p5.TableRow. The reference\ncan then be used to get and set values of the selected row.
\n"],"line":[0,198],"params":[1,[[0,{"name":[0,"rowID"],"description":[0,"ID number of the row to get
\n"],"type":[0,"Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,"p5.TableRow object"],"type":[0,"p5.TableRow"]}],"example":[1,[[0,"\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n let row = table.getRow(1);\n //print it column by column\n //note: a row is an object, not an array\n for (let c = 0; c < table.getColumnCount(); c++) {\n print(row.getString(c));\n }\n\n describe('no image displayed');\n}\n
\nReturns the total number of rows in a Table.
\n"],"line":[0,716],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,"Number of rows in this table"],"type":[0,"Integer"]}],"example":[1,[[0,"\n\n // given the cvs file \"blobs.csv\" in /assets directory\n //\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n let table;\n\n function preload() {\n table = loadTable('/assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n text('There are ' + table.getRowCount() + ' rows in the table.', 100, 50);\n }\n
\n Gets all rows from the table. Returns an array of p5.TableRows.
\n"],"line":[0,242],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,"Array of p5.TableRows"],"type":[0,"p5.TableRow[]"]}],"example":[1,[[0,"\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n\n //warning: rows is an array of objects\n for (let r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n\n describe('no image displayed');\n }\n
\n Retrieves a String value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n"],"line":[0,1173],"params":[1,[[0,{"name":[0,"row"],"description":[0,"row ID
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"column"],"description":[0,"columnName (string) or\n ID (number)
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"String"]}],"example":[1,[[0,"\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n // table is comma separated value \"CSV\"\n // and has specifiying header for column labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.getString(0, 0)); // 0\n print(table.getString(0, 1)); // Capra hircus\n print(table.getString(0, 2)); // Goat\n print(table.getString(1, 0)); // 1\n print(table.getString(1, 1)); // Panthera pardus\n print(table.getString(1, 2)); // Leopard\n print(table.getString(2, 0)); // 2\n print(table.getString(2, 1)); // Equus zebra\n print(table.getString(2, 2)); // Zebra\n describe('no image displayed');\n}\n
\nFinds the first row in the Table that matches the regular\nexpression provided, and returns a reference to that row.\nEven if multiple rows are possible matches, only the first\nmatching row is returned. The column to search may be\nspecified by either its ID or title.
\n"],"line":[0,417],"params":[1,[[0,{"name":[0,"regexp"],"description":[0,"The regular expression to match
\n"],"type":[0,"String|RegExp"]}],[0,{"name":[0,"column"],"description":[0,"The column ID (number) or\n title (string)
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,"TableRow object"],"type":[0,"p5.TableRow"]}],"example":[1,[[0,"\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //Search using specified regex on a given column, return TableRow object\n let mammal = table.matchRow(new RegExp('ant'), 1);\n print(mammal.getString(1));\n //Output \"Panthera pardus\"\n}\n
\nFinds the rows in the Table that match the regular expression provided,\nand returns references to those rows. Returns an array, so for must be\nused to iterate through all the rows, as shown in the example. The\ncolumn to search may be specified by either its ID or title.
\n"],"line":[0,475],"params":[1,[[0,{"name":[0,"regexp"],"description":[0,"The regular expression to match
\n"],"type":[0,"String"]}],[0,{"name":[0,"column"],"description":[0,"The column ID (number) or\n title (string)
\n"],"type":[0,"String|Integer"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"return":[0,{"description":[0,"An Array of TableRow objects"],"type":[0,"p5.TableRow[]"]}],"example":[1,[[0,"\n\nlet table;\n\nfunction setup() {\n table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n let newRow = table.addRow();\n newRow.setString('name', 'Lion');\n newRow.setString('type', 'Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', 'Snake');\n newRow.setString('type', 'Reptile');\n\n newRow = table.addRow();\n newRow.setString('name', 'Mosquito');\n newRow.setString('type', 'Insect');\n\n newRow = table.addRow();\n newRow.setString('name', 'Lizard');\n newRow.setString('type', 'Reptile');\n\n let rows = table.matchRows('R.*', 'type');\n for (let i = 0; i < rows.length; i++) {\n print(rows[i].getString('name') + ': ' + rows[i].getString('type'));\n }\n}\n// Sketch prints:\n// Snake: Reptile\n// Lizard: Reptile\n
\nUse removeColumn() to remove an existing column from a Table\nobject. The column to be removed may be identified by either\nits title (a String) or its index value (an int).\nremoveColumn(0) would remove the first column, removeColumn(1)\nwould remove the second column, and so on.
\n"],"line":[0,888],"params":[1,[[0,{"name":[0,"column"],"description":[0,"columnName (string) or ID (number)
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"example":[1,[[0,"\n\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.removeColumn('id');\n print(table.getColumnCount());\n describe('no image displayed');\n }\n
\n Removes a row from the table object.
\n"],"line":[0,152],"params":[1,[[0,{"name":[0,"id"],"description":[0,"ID number of the row to remove
\n"],"type":[0,"Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"example":[1,[[0,"\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //remove the first row\n table.removeRow(0);\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n\n describe('no image displayed');\n}\n
\nRemoves any of the specified characters (or \"tokens\").
\nIf no column is specified, then the values in all columns and\nrows are processed. A specific column may be referenced by\neither its ID or title.
\n"],"line":[0,752],"params":[1,[[0,{"name":[0,"chars"],"description":[0,"String listing characters to be removed
\n"],"type":[0,"String"]}],[0,{"name":[0,"column"],"description":[0,"Column ID (number)\n or name (string)
\n"],"type":[0,"String|Integer"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"example":[1,[[0,"\n\n function setup() {\n let table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n let newRow = table.addRow();\n newRow.setString('name', ' $Lion ,');\n newRow.setString('type', ',,,Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', '$Snake ');\n newRow.setString('type', ',,,Reptile');\n\n table.removeTokens(',$ ');\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n
An array containing the p5.TableRow objects that make up the\nrows of the table. The same result as calling getRows()
\n"],"line":[0,80],"itemtype":[0,"property"],"class":[0,"p5.Table"],"isConstructor":[0,false],"path":[0,"p5.Table/rows"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Table/set.mdx"],"slug":[0,"en/p5table/set"],"body":[0,"\n\n# set\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"set()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.Table.js"],"description":[0,"Stores a value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n"],"line":[0,950],"params":[1,[[0,{"name":[0,"row"],"description":[0,"row ID
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"column"],"description":[0,"column ID (Number)\n or title (String)
\n"],"type":[0,"String|Integer"]}],[0,{"name":[0,"value"],"description":[0,"value to assign
\n"],"type":[0,"String|Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"example":[1,[[0,"\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n table.set(0, 'species', 'Canis Lupus');\n table.set(0, 'name', 'Wolf');\n\n //print the results\n for (let r = 0; r < table.getRowCount(); r++)\n for (let c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n\n describe('no image displayed');\n}\n
\nStores a Float value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n"],"line":[0,998],"params":[1,[[0,{"name":[0,"row"],"description":[0,"row ID
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"column"],"description":[0,"column ID (Number)\n or title (String)
\n"],"type":[0,"String|Integer"]}],[0,{"name":[0,"value"],"description":[0,"value to assign
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"example":[1,[[0,"\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n table.setNum(1, 'id', 1);\n\n print(table.getColumn(0));\n //[\"0\", 1, \"2\"]\n\n describe('no image displayed');\n}\n
\nStores a String value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n"],"line":[0,1043],"params":[1,[[0,{"name":[0,"row"],"description":[0,"row ID
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"column"],"description":[0,"column ID (Number)\n or title (String)
\n"],"type":[0,"String|Integer"]}],[0,{"name":[0,"value"],"description":[0,"value to assign
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"example":[1,[[0,"\n\n// Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nlet table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //add a row\n let newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Canis Lupus');\n newRow.setString('name', 'Wolf');\n\n print(table.getArray());\n\n describe('no image displayed');\n}\n
Trims leading and trailing whitespace, such as spaces and tabs,\nfrom String table values. If no column is specified, then the\nvalues in all columns and rows are trimmed. A specific column\nmay be referenced by either its ID or title.
\n"],"line":[0,824],"params":[1,[[0,{"name":[0,"column"],"description":[0,"Column ID (number)\n or name (string)
\n"],"type":[0,"String|Integer"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Table"],"chainable":[0,false],"example":[1,[[0,"\n\n function setup() {\n let table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n let newRow = table.addRow();\n newRow.setString('name', ' Lion ,');\n newRow.setString('type', ' Mammal ');\n\n newRow = table.addRow();\n newRow.setString('name', ' Snake ');\n newRow.setString('type', ' Reptile ');\n\n table.trim();\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n
A TableRow object represents a single row of data values,\nstored in columns, from a table.
\nA Table Row contains both an ordered array, and an unordered\nJSON object.
\n"],"line":[0,9],"params":[1,[[0,{"name":[0,"str"],"description":[0,"optional: populate the row with a\n string of values, separated by the\n separator
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"separator"],"description":[0,"comma separated values (csv) by default
\n"],"type":[0,"String"],"optional":[0,true]}]]],"chainable":[0,false],"methods":[0,{"set":[0,{"description":[0,"Stores a value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n"],"path":[0,"p5.TableRow/set"]}],"setNum":[0,{"description":[0,"Stores a Float value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n"],"path":[0,"p5.TableRow/setNum"]}],"setString":[0,{"description":[0,"Stores a String value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n"],"path":[0,"p5.TableRow/setString"]}],"get":[0,{"description":[0,"Retrieves a value from the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n"],"path":[0,"p5.TableRow/get"]}],"getNum":[0,{"description":[0,"Retrieves a Float value from the TableRow's specified\ncolumn. The column may be specified by either its ID or\ntitle.
\n"],"path":[0,"p5.TableRow/getNum"]}],"getString":[0,{"description":[0,"Retrieves an String value from the TableRow's specified\ncolumn. The column may be specified by either its ID or\ntitle.
\n"],"path":[0,"p5.TableRow/getString"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.TableRow"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.TableRow/get.mdx"],"slug":[0,"en/p5tablerow/get"],"body":[0,"\n\n# get\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"get()"],"module":[0,"IO"],"submodule":[0,"Table"],"file":[0,"src/io/p5.TableRow.js"],"description":[0,"Retrieves a value from the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n"],"line":[0,184],"params":[1,[[0,{"name":[0,"column"],"description":[0,"columnName (string) or\n ID (number)
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TableRow"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"String|Number"]}],"example":[1,[[0,"\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let names = [];\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n names.push(rows[r].get('name'));\n }\n\n print(names);\n\n describe('no image displayed');\n }\n
Retrieves a Float value from the TableRow's specified\ncolumn. The column may be specified by either its ID or\ntitle.
\n"],"line":[0,231],"params":[1,[[0,{"name":[0,"column"],"description":[0,"columnName (string) or\n ID (number)
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TableRow"],"chainable":[0,false],"return":[0,{"description":[0,"Float Floating point number"],"type":[0,"Number"]}],"example":[1,[[0,"\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n let minId = Infinity;\n let maxId = -Infinity;\n for (let r = 0; r < rows.length; r++) {\n let id = rows[r].getNum('id');\n minId = min(minId, id);\n maxId = min(maxId, id);\n }\n print('minimum id = ' + minId + ', maximum id = ' + maxId);\n describe('no image displayed');\n }\n
Retrieves an String value from the TableRow's specified\ncolumn. The column may be specified by either its ID or\ntitle.
\n"],"line":[0,285],"params":[1,[[0,{"name":[0,"column"],"description":[0,"columnName (string) or\n ID (number)
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TableRow"],"chainable":[0,false],"return":[0,{"description":[0,"String"],"type":[0,"String"]}],"example":[1,[[0,"\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n let longest = '';\n for (let r = 0; r < rows.length; r++) {\n let species = rows[r].getString('species');\n if (longest.length < species.length) {\n longest = species;\n }\n }\n\n print('longest: ' + longest);\n\n describe('no image displayed');\n }\n
Stores a value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n"],"line":[0,36],"params":[1,[[0,{"name":[0,"column"],"description":[0,"Column ID (Number)\n or Title (String)
\n"],"type":[0,"String|Integer"]}],[0,{"name":[0,"value"],"description":[0,"The value to be stored
\n"],"type":[0,"String|Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TableRow"],"chainable":[0,false],"example":[1,[[0,"\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n print(table.getArray());\n\n describe('no image displayed');\n }\n
Stores a Float value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n"],"line":[0,97],"params":[1,[[0,{"name":[0,"column"],"description":[0,"Column ID (Number)\n or Title (String)
\n"],"type":[0,"String|Integer"]}],[0,{"name":[0,"value"],"description":[0,"The value to be stored\n as a Float
\n"],"type":[0,"Number|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TableRow"],"chainable":[0,false],"example":[1,[[0,"\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n rows[r].setNum('id', r + 10);\n }\n\n print(table.getArray());\n\n describe('no image displayed');\n }\n
Stores a String value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n"],"line":[0,140],"params":[1,[[0,{"name":[0,"column"],"description":[0,"Column ID (Number)\n or Title (String)
\n"],"type":[0,"String|Integer"]}],[0,{"name":[0,"value"],"description":[0,"The value to be stored\n as a String
\n"],"type":[0,"String|Number|Boolean|Object"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TableRow"],"chainable":[0,false],"example":[1,[[0,"\n\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n let table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('/assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n let rows = table.getRows();\n for (let r = 0; r < rows.length; r++) {\n let name = rows[r].getString('name');\n rows[r].setString('name', 'A ' + name + ' named George');\n }\n\n print(table.getArray());\n\n describe('no image displayed');\n }\n
A class to describe an XML object.
\nEach p5.XML
object provides an easy way to interact with XML data.\nExtensible Markup Language\n(XML)\nis a standard format for sending data between applications. Like HTML, the\nXML format is based on tags and attributes, as in\n.
Note: Use loadXML() to load external XML files.
\n"],"line":[0,9],"chainable":[0,false],"example":[1,[[0,"\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get an array with all mammal tags.\n let mammals = myXML.getChildren('mammal');\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Iterate over the mammals array.\n for (let i = 0; i < mammals.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Get the mammal's common name.\n let name = mammals[i].getContent();\n\n // Display the mammal's name.\n text(name, 20, y);\n }\n\n describe(\n 'The words \"Goat\", \"Leopard\", and \"Zebra\" written on three separate lines. The text is black on a gray background.'\n );\n}\n
\nReturns the element's parent element as a new p5.XML\nobject.
\n"],"path":[0,"p5.XML/getParent"]}],"getName":[0,{"description":[0,"Returns the element's name as a String
.
An XML element's name is given by its tag. For example, the element\n
has the name language
.
Sets the element's tag name.
\nAn XML element's name is given by its tag. For example, the element\n
has the name language
.
The parameter, name
, is the element's new name as a string. For example,\ncalling myXML.setName('planet')
will make the element's new tag name\n
.
Returns true
if the element has child elements and false
if not.
Returns an array with the names of the element's child elements as\nString
s.
Returns an array with the element's child elements as new\np5.XML objects.
\nThe parameter, name
, is optional. If a string is passed, as in\nmyXML.getChildren('cat')
, then the method will only return child elements\nwith the tag
.
Returns the first matching child element as a new\np5.XML object.
\nThe parameter, name
, is optional. If a string is passed, as in\nmyXML.getChild('cat')
, then the first child element with the tag\n
will be returned. If a number is passed, as in\nmyXML.getChild(1)
, then the child element at that index will be returned.
Adds a new child element and returns a reference to it.
\nThe parameter, child
, is the p5.XML object to add\nas a child element. For example, calling myXML.addChild(otherXML)
inserts\notherXML
as a child element of myXML
.
Removes the first matching child element.
\nThe parameter, name
, is the child element to remove. If a string is\npassed, as in myXML.removeChild('cat')
, then the first child element\nwith the tag
will be removed. If a number is passed, as in\nmyXML.removeChild(1)
, then the child element at that index will be\nremoved.
Returns the number of attributes the element has.
\n"],"path":[0,"p5.XML/getAttributeCount"]}],"listAttributes":[0,{"description":[0,"Returns an Array
with the names of the element's attributes.
Note: Use\nmyXML.getString() or\nmyXML.getNum() to return an attribute's value.
\n"],"path":[0,"p5.XML/listAttributes"]}],"hasAttribute":[0,{"description":[0,"Returns true
if the element has a given attribute and false
if not.
The parameter, name
, is a string with the name of the attribute being\nchecked.
Note: Use\nmyXML.getString() or\nmyXML.getNum() to return an attribute's value.
\n"],"path":[0,"p5.XML/hasAttribute"]}],"getNum":[0,{"description":[0,"Return an attribute's value as a Number
.
The first parameter, name
, is a string with the name of the attribute\nbeing checked. For example, calling myXML.getNum('id')
returns the\nelement's id
attribute as a number.
The second parameter, defaultValue
, is optional. If a number is passed,\nas in myXML.getNum('id', -1)
, it will be returned if the attribute\ndoesn't exist or can't be converted to a number.
Note: Use\nmyXML.getString() or\nmyXML.getNum() to return an attribute's value.
\n"],"path":[0,"p5.XML/getNum"]}],"getString":[0,{"description":[0,"Return an attribute's value as a string.
\nThe first parameter, name
, is a string with the name of the attribute\nbeing checked. For example, calling myXML.getString('color')
returns the\nelement's id
attribute as a string.
The second parameter, defaultValue
, is optional. If a string is passed,\nas in myXML.getString('color', 'deeppink')
, it will be returned if the\nattribute doesn't exist.
Note: Use\nmyXML.getString() or\nmyXML.getNum() to return an attribute's value.
\n"],"path":[0,"p5.XML/getString"]}],"setAttribute":[0,{"description":[0,"Sets an attribute to a given value.
\nThe first parameter, name
, is a string with the name of the attribute\nbeing set.
The second parameter, value
, is the attribute's new value. For example,\ncalling myXML.setAttribute('id', 123)
sets the id
attribute to the\nvalue 123.
Returns the element's content as a String
.
The parameter, defaultValue
, is optional. If a string is passed, as in\nmyXML.getContent('???')
, it will be returned if the element has no\ncontent.
Sets the element's content.
\nAn element's content is the text between its tags. For example, the element\n
has the content JavaScript
.
The parameter, content
, is a string with the element's new content.
Returns the element as a String
.
myXML.serialize()
is useful for sending the element over the network or\nsaving it to a file.
Adds a new child element and returns a reference to it.
\nThe parameter, child
, is the p5.XML object to add\nas a child element. For example, calling myXML.addChild(otherXML)
inserts\notherXML
as a child element of myXML
.
child element to add.
\n"],"type":[0,"p5.XML"]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"added child element."],"type":[0,"p5.XML"]}],"example":[1,[[0,"\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a new p5.XML object.\n let newAnimal = new p5.XML();\n\n // Set its properties.\n newAnimal.setName('hydrozoa');\n newAnimal.setAttribute('id', 4);\n newAnimal.setAttribute('species', 'Physalia physalis');\n newAnimal.setContent('Bluebottle');\n\n // Add the child element.\n myXML.addChild(newAnimal);\n\n // Get the first child element that is a hydrozoa.\n let blueBottle = myXML.getChild('hydrozoa');\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Get the child element's content.\n let content = blueBottle.getContent();\n\n // Display the child element's content.\n text(content, 50, 50);\n\n describe('The word \"Bluebottle\" written in black on a gray background.');\n}\n
\nReturns the number of attributes the element has.
\n"],"line":[0,723],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"number of attributes."],"type":[0,"Integer"]}],"example":[1,[[0,"\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first child element.\n let first = myXML.getChild(0);\n\n // Get the number of attributes.\n let numAttributes = first.getAttributeCount();\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the number of attributes.\n text(numAttributes, 50, 50);\n\n describe('The number \"2\" written in black on a gray background.');\n}\n
\nReturns the first matching child element as a new\np5.XML object.
\nThe parameter, name
, is optional. If a string is passed, as in\nmyXML.getChild('cat')
, then the first child element with the tag\n
will be returned. If a number is passed, as in\nmyXML.getChild(1)
, then the child element at that index will be returned.
element name or index.
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"child element."],"type":[0,"p5.XML"]}],"example":[1,[[0,"\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first child element that is a mammal.\n let goat = myXML.getChild('mammal');\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Get the child element's content.\n let content = goat.getContent();\n\n // Display the child element's content.\n text(content, 50, 50);\n\n describe('The word \"Goat\" written in black on a gray background.');\n}\n
\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the child element at index 1.\n let leopard = myXML.getChild(1);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Get the child element's content.\n let content = leopard.getContent();\n\n // Display the child element's content.\n text(content, 50, 50);\n\n describe('The word \"Leopard\" written in black on a gray background.');\n}\n
\nReturns an array with the element's child elements as new\np5.XML objects.
\nThe parameter, name
, is optional. If a string is passed, as in\nmyXML.getChildren('cat')
, then the method will only return child elements\nwith the tag
.
name of the elements to return.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"child elements."],"type":[0,"p5.XML[]"]}],"example":[1,[[0,"\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get an array of the child elements.\n let children = myXML.getChildren();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Iterate over the array.\n for (let i = 0; i < children.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 20;\n\n // Get the child element's content.\n let content = children[i].getContent();\n\n // Display the child element's content.\n text(content, 10, y);\n }\n\n describe(\n 'The words \"Goat\", \"Leopard\", \"Zebra\", and \"Turtle\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get an array of the child elements\n // that are mammals.\n let children = myXML.getChildren('mammal');\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Iterate over the array.\n for (let i = 0; i < children.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 20;\n\n // Get the child element's content.\n let content = children[i].getContent();\n\n // Display the child element's content.\n text(content, 10, y);\n }\n\n describe(\n 'The words \"Goat\", \"Leopard\", and \"Zebra\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\nReturns the element's content as a String
.
The parameter, defaultValue
, is optional. If a string is passed, as in\nmyXML.getContent('???')
, it will be returned if the element has no\ncontent.
value to return if the element has no\n content.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"element's content as a string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first reptile child element.\n let reptile = myXML.getChild('reptile');\n\n // Get the reptile's content.\n let content = reptile.getContent();\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the element's content.\n text(content, 5, 50, 90);\n\n describe(`The text \"${content}\" written in green on a gray background.`);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.XML object.\n let blankSpace = new p5.XML();\n\n // Get the element's content and use a default value.\n let content = blankSpace.getContent('Your name');\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the element's content.\n text(content, 5, 50, 90);\n\n describe(`The text \"${content}\" written in green on a gray background.`);\n}\n
\nReturns the element's name as a String
.
An XML element's name is given by its tag. For example, the element\n
has the name language
.
\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get an array with all mammal elements.\n let mammals = myXML.getChildren('mammal');\n\n // Get the first mammal element.\n let firstMammal = mammals[0];\n\n // Get the mammal element's name.\n let name = firstMammal.getName();\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the element's name.\n text(name, 50, 50);\n\n describe('The word \"mammal\" written in black on a gray background.');\n}\n
\nReturn an attribute's value as a Number
.
The first parameter, name
, is a string with the name of the attribute\nbeing checked. For example, calling myXML.getNum('id')
returns the\nelement's id
attribute as a number.
The second parameter, defaultValue
, is optional. If a number is passed,\nas in myXML.getNum('id', -1)
, it will be returned if the attribute\ndoesn't exist or can't be converted to a number.
Note: Use\nmyXML.getString() or\nmyXML.getNum() to return an attribute's value.
\n"],"line":[0,884],"params":[1,[[0,{"name":[0,"name"],"description":[0,"name of the attribute to be checked.
\n"],"type":[0,"String"]}],[0,{"name":[0,"defaultValue"],"description":[0,"value to return if the attribute doesn't exist.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"attribute value as a number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first reptile child element.\n let reptile = myXML.getChild('reptile');\n\n // Get the reptile's content.\n let content = reptile.getContent();\n\n // Get the reptile's ID.\n let id = reptile.getNum('id');\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the ID attribute.\n text(`${content} is ${id + 1}th`, 5, 50, 90);\n\n describe(`The text \"${content} is ${id + 1}th\" written in black on a gray background.`);\n}\n
\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first reptile child element.\n let reptile = myXML.getChild('reptile');\n\n // Get the reptile's content.\n let content = reptile.getContent();\n\n // Get the reptile's size.\n let weight = reptile.getNum('weight', 135);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the ID attribute.\n text(`${content} is ${weight}kg`, 5, 50, 90);\n\n describe(\n `The text \"${content} is ${weight}kg\" written in black on a gray background.`\n );\n}\n
\nReturns the element's parent element as a new p5.XML\nobject.
\n"],"line":[0,77],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"parent element."],"type":[0,"p5.XML"]}],"example":[1,[[0,"\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get an array with all mammal elements.\n let mammals = myXML.getChildren('mammal');\n\n // Get the first mammal element.\n let firstMammal = mammals[0];\n\n // Get the parent element.\n let parent = firstMammal.getParent();\n\n // Get the parent element's name.\n let name = parent.getName();\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the parent element's name.\n text(name, 50, 50);\n\n describe('The word \"animals\" written in black on a gray background.');\n}\n
\nReturn an attribute's value as a string.
\nThe first parameter, name
, is a string with the name of the attribute\nbeing checked. For example, calling myXML.getString('color')
returns the\nelement's id
attribute as a string.
The second parameter, defaultValue
, is optional. If a string is passed,\nas in myXML.getString('color', 'deeppink')
, it will be returned if the\nattribute doesn't exist.
Note: Use\nmyXML.getString() or\nmyXML.getNum() to return an attribute's value.
\n"],"line":[0,989],"params":[1,[[0,{"name":[0,"name"],"description":[0,"name of the attribute to be checked.
\n"],"type":[0,"String"]}],[0,{"name":[0,"defaultValue"],"description":[0,"value to return if the attribute doesn't exist.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"attribute value as a string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first reptile child element.\n let reptile = myXML.getChild('reptile');\n\n // Get the reptile's content.\n let content = reptile.getContent();\n\n // Get the reptile's species.\n let species = reptile.getString('species');\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the species attribute.\n text(`${content}: ${species}`, 5, 50, 90);\n\n describe(`The text \"${content}: ${species}\" written in black on a gray background.`);\n}\n
\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first reptile child element.\n let reptile = myXML.getChild('reptile');\n\n // Get the reptile's content.\n let content = reptile.getContent();\n\n // Get the reptile's color.\n let attribute = reptile.getString('color', 'green');\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n fill(attribute);\n\n // Display the element's content.\n text(content, 50, 50);\n\n describe(`The text \"${content}\" written in green on a gray background.`);\n}\n
\nReturns true
if the element has a given attribute and false
if not.
The parameter, name
, is a string with the name of the attribute being\nchecked.
Note: Use\nmyXML.getString() or\nmyXML.getNum() to return an attribute's value.
\n"],"line":[0,821],"params":[1,[[0,{"name":[0,"name"],"description":[0,"name of the attribute to be checked.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"whether the element has the attribute."],"type":[0,"Boolean"]}],"example":[1,[[0,"\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first mammal child element.\n let mammal = myXML.getChild('mammal');\n\n // Check whether the element has an\n // species attribute.\n let hasSpecies = mammal.hasAttribute('species');\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display whether the element has a species attribute.\n if (hasSpecies === true) {\n text('Species', 50, 50);\n } else {\n text('No species', 50, 50);\n }\n\n describe('The text \"Species\" written in black on a gray background.');\n}\n
\nReturns true
if the element has child elements and false
if not.
\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Check whether the element has child elements.\n let isParent = myXML.hasChildren();\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Style the text.\n if (isParent === true) {\n text('Parent', 50, 50);\n } else {\n text('Not Parent', 50, 50);\n }\n\n describe('The word \"Parent\" written in black on a gray background.');\n}\n
\nReturns an Array
with the names of the element's attributes.
Note: Use\nmyXML.getString() or\nmyXML.getNum() to return an attribute's value.
\n"],"line":[0,767],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"return":[0,{"description":[0,"attribute names."],"type":[0,"String[]"]}],"example":[1,[[0,"\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first child element.\n let first = myXML.getChild(0);\n\n // Get the number of attributes.\n let attributes = first.listAttributes();\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the element's attributes.\n text(attributes, 50, 50);\n\n describe('The text \"id,species\" written in black on a gray background.');\n}\n
\nReturns an array with the names of the element's child elements as\nString
s.
\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the names of the element's children as an array.\n let children = myXML.listChildren();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Iterate over the array.\n for (let i = 0; i < children.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Display the child element's name.\n text(children[i], 10, y);\n }\n\n describe(\n 'The words \"mammal\", \"mammal\", \"mammal\", and \"reptile\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\nRemoves the first matching child element.
\nThe parameter, name
, is the child element to remove. If a string is\npassed, as in myXML.removeChild('cat')
, then the first child element\nwith the tag
will be removed. If a number is passed, as in\nmyXML.removeChild(1)
, then the child element at that index will be\nremoved.
name or index of the child element to remove.
\n"],"type":[0,"String|Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"example":[1,[[0,"\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Remove the first mammal element.\n myXML.removeChild('mammal');\n\n // Get an array of child elements.\n let children = myXML.getChildren();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Iterate over the array.\n for (let i = 0; i < children.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Get the child element's content.\n let content = children[i].getContent();\n\n // Display the child element's content.\n text(content, 10, y);\n }\n\n describe(\n 'The words \"Leopard\", \"Zebra\", and \"Turtle\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Remove the element at index 2.\n myXML.removeChild(2);\n\n // Get an array of child elements.\n let children = myXML.getChildren();\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Iterate over the array.\n for (let i = 0; i < children.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Get the child element's content.\n let content = children[i].getContent();\n\n // Display the child element's content.\n text(content, 10, y);\n }\n\n describe(\n 'The words \"Goat\", \"Leopard\", and \"Turtle\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\nReturns the element as a String
.
myXML.serialize()
is useful for sending the element over the network or\nsaving it to a file.
\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Display instructions.\n text('Double-click to save', 5, 50, 90);\n\n describe('The text \"Double-click to save\" written in black on a gray background.');\n}\n\n// Save the file when the user double-clicks.\nfunction doubleClicked() {\n // Create a p5.PrintWriter object.\n // Use the file format .xml.\n let myWriter = createWriter('animals', 'xml');\n\n // Serialize the XML data to a string.\n let data = myXML.serialize();\n\n // Write the data to the print stream.\n myWriter.write(data);\n\n // Save the file and close the print stream.\n myWriter.close();\n}\n
\nSets an attribute to a given value.
\nThe first parameter, name
, is a string with the name of the attribute\nbeing set.
The second parameter, value
, is the attribute's new value. For example,\ncalling myXML.setAttribute('id', 123)
sets the id
attribute to the\nvalue 123.
name of the attribute to be set.
\n"],"type":[0,"String"]}],[0,{"name":[0,"value"],"description":[0,"attribute's new value.
\n"],"type":[0,"Number|String|Boolean"]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"example":[1,[[0,"\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first reptile child element.\n let reptile = myXML.getChild('reptile');\n\n // Set the reptile's color.\n reptile.setAttribute('color', 'green');\n\n // Get the reptile's content.\n let content = reptile.getContent();\n\n // Get the reptile's color.\n let attribute = reptile.getString('color');\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the element's content.\n text(`${content} is ${attribute}`, 5, 50, 90);\n\n describe(\n `The text \"${content} is ${attribute}\" written in green on a gray background.`\n );\n}\n
\nSets the element's content.
\nAn element's content is the text between its tags. For example, the element\n
has the content JavaScript
.
The parameter, content
, is a string with the element's new content.
new content for the element.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"example":[1,[[0,"\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the first reptile child element.\n let reptile = myXML.getChild('reptile');\n\n // Get the reptile's original content.\n let oldContent = reptile.getContent();\n\n // Set the reptile's content.\n reptile.setContent('Loggerhead');\n\n // Get the reptile's new content.\n let newContent = reptile.getContent();\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the element's old and new content.\n text(`${oldContent}: ${newContent}`, 5, 50, 90);\n\n describe(\n `The text \"${oldContent}: ${newContent}\" written in green on a gray background.`\n );\n}\n
\nSets the element's tag name.
\nAn XML element's name is given by its tag. For example, the element\n
has the name language
.
The parameter, name
, is the element's new name as a string. For example,\ncalling myXML.setName('planet')
will make the element's new tag name\n
.
new tag name of the element.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.XML"],"chainable":[0,false],"example":[1,[[0,"\n\nlet myXML;\n\n// Load the XML and create a p5.XML object.\nfunction preload() {\n myXML = loadXML('/assets/animals.xml');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Get the element's original name.\n let oldName = myXML.getName();\n\n // Set the element's name.\n myXML.setName('monsters');\n\n // Get the element's new name.\n let newName = myXML.getName();\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(14);\n\n // Display the element's names.\n text(oldName, 50, 33);\n text(newName, 50, 67);\n\n describe(\n 'The words \"animals\" and \"monsters\" written on separate lines. The text is black on a gray background.'\n );\n}\n
The system variable accelerationX always contains the acceleration of the\ndevice along the x axis. Value is represented as meters per second squared.
\n"],"line":[0,23],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// Move a touchscreen device to register\n// acceleration changes.\nfunction draw() {\n background(220, 50);\n fill('magenta');\n ellipse(width / 2, height / 2, accelerationX);\n describe('Magnitude of device acceleration is displayed as ellipse size.');\n}\n
\nThe system variable accelerationY always contains the acceleration of the\ndevice along the y axis. Value is represented as meters per second squared.
\n"],"line":[0,45],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// Move a touchscreen device to register\n// acceleration changes.\nfunction draw() {\n background(220, 50);\n fill('magenta');\n ellipse(width / 2, height / 2, accelerationY);\n describe('Magnitude of device acceleration is displayed as ellipse size');\n}\n
\nThe system variable accelerationZ always contains the acceleration of the\ndevice along the z axis. Value is represented as meters per second squared.
\n"],"line":[0,67],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// Move a touchscreen device to register\n// acceleration changes.\nfunction draw() {\n background(220, 50);\n fill('magenta');\n ellipse(width / 2, height / 2, accelerationZ);\n describe('Magnitude of device acceleration is displayed as ellipse size');\n}\n
\nThe deviceMoved() function is called when the device is moved by more than\nthe threshold value along X, Y or Z axis. The default threshold is set to 0.5.\nThe threshold value can be changed using setMoveThreshold().
\n"],"line":[0,501],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Run this example on a mobile device\n// Move the device around\n// to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when device moves`);\n}\nfunction deviceMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
\nThe system variable deviceOrientation always contains the orientation of\nthe device. The value of this variable will either be set 'landscape'\nor 'portrait'. If no data is available it will be set to 'undefined'.\neither LANDSCAPE or PORTRAIT.
\n"],"line":[0,11],"itemtype":[0,"property"],"class":[0,"p5"],"isConstructor":[0,false],"path":[0,"p5/deviceOrientation"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/deviceShaken.mdx"],"slug":[0,"en/p5/deviceshaken"],"body":[0,"\n\n# deviceShaken\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"deviceShaken()"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The deviceShaken() function is called when the device total acceleration\nchanges of accelerationX and accelerationY values is more than\nthe threshold value. The default threshold is set to 30.\nThe threshold value can be changed using setShakeThreshold().
\n"],"line":[0,589],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Run this example on a mobile device\n// Shake the device to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when device shakes`);\n}\nfunction deviceShaken() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n
\nThe deviceTurned() function is called when the device rotates by\nmore than 90 degrees continuously.
\nThe axis that triggers the deviceTurned() method is stored in the turnAxis\nvariable. The deviceTurned() method can be locked to trigger on any axis:\nX, Y or Z by comparing the turnAxis variable to 'X', 'Y' or 'Z'.
\n"],"line":[0,531],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees\n// to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when device turns`);\n}\nfunction deviceTurned() {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n}\n
\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees in the\n// X-axis to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when x-axis turns`);\n}\nfunction deviceTurned() {\n if (turnAxis === 'X') {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n }\n}\n
\nThe system variable pAccelerationX always contains the acceleration of the\ndevice along the x axis in the frame previous to the current frame. Value\nis represented as meters per second squared.
\n"],"line":[0,90],"itemtype":[0,"property"],"class":[0,"p5"],"isConstructor":[0,false],"path":[0,"p5/pAccelerationX"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/pAccelerationY.mdx"],"slug":[0,"en/p5/paccelerationy"],"body":[0,"\n\n# pAccelerationY\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"pAccelerationY"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The system variable pAccelerationY always contains the acceleration of the\ndevice along the y axis in the frame previous to the current frame. Value\nis represented as meters per second squared.
\n"],"line":[0,100],"itemtype":[0,"property"],"class":[0,"p5"],"isConstructor":[0,false],"path":[0,"p5/pAccelerationY"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/pAccelerationZ.mdx"],"slug":[0,"en/p5/paccelerationz"],"body":[0,"\n\n# pAccelerationZ\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"pAccelerationZ"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The system variable pAccelerationZ always contains the acceleration of the\ndevice along the z axis in the frame previous to the current frame. Value\nis represented as meters per second squared.
\n"],"line":[0,110],"itemtype":[0,"property"],"class":[0,"p5"],"isConstructor":[0,false],"path":[0,"p5/pAccelerationZ"]}],"render":[0,null]}],[0,{"id":[0,"en/p5/pRotationX.mdx"],"slug":[0,"en/p5/protationx"],"body":[0,"\n\n# pRotationX\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"pRotationX"],"module":[0,"Events"],"submodule":[0,"Acceleration"],"file":[0,"src/events/acceleration.js"],"description":[0,"The system variable pRotationX always contains the rotation of the\ndevice along the x axis in the frame previous to the current frame.\nIf the sketch angleMode() is set to DEGREES,\nthe value will be -180 to 180. If it is set to RADIANS, the value will\nbe -PI to PI.
\npRotationX can also be used with rotationX to determine the rotate\ndirection of the device along the X-axis.
\n"],"line":[0,234],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// A simple if statement looking at whether\n// rotationX - pRotationX < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nlet rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely necessary but the logic\n// will be different in that case.\n\nlet rX = rotationX + 180;\nlet pRX = pRotationX + 180;\n\nif ((rX - pRX > 0 && rX - pRX < 270) || rX - pRX < -270) {\n rotateDirection = 'clockwise';\n} else if (rX - pRX < 0 || rX - pRX > 270) {\n rotateDirection = 'counter-clockwise';\n}\n\nprint(rotateDirection);\ndescribe('no image to display.');\n
\nThe system variable pRotationY always contains the rotation of the\ndevice along the y axis in the frame previous to the current frame.\nIf the sketch angleMode() is set to DEGREES,\nthe value will be -90 to 90. If it is set to RADIANS, the value will\nbe -PI/2 to PI/2.
\npRotationY can also be used with rotationY to determine the rotate\ndirection of the device along the Y-axis.
\n"],"line":[0,278],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// A simple if statement looking at whether\n// rotationY - pRotationY < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nlet rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely necessary but the logic\n// will be different in that case.\n\nlet rY = rotationY + 180;\nlet pRY = pRotationY + 180;\n\nif ((rY - pRY > 0 && rY - pRY < 270) || rY - pRY < -270) {\n rotateDirection = 'clockwise';\n} else if (rY - pRY < 0 || rY - pRY > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\ndescribe('no image to display.');\n
\nThe system variable pRotationZ always contains the rotation of the\ndevice along the z axis in the frame previous to the current frame.\nIf the sketch angleMode() is set to DEGREES,\nthe value will be 0 to 360. If it is set to RADIANS, the value will\nbe 0 to 2*PI.
\npRotationZ can also be used with rotationZ to determine the rotate\ndirection of the device along the Z-axis.
\n"],"line":[0,321],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// A simple if statement looking at whether\n// rotationZ - pRotationZ < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nlet rotateDirection = 'clockwise';\n\nif (\n (rotationZ - pRotationZ > 0 && rotationZ - pRotationZ < 270) ||\n rotationZ - pRotationZ < -270\n) {\n rotateDirection = 'clockwise';\n} else if (rotationZ - pRotationZ < 0 || rotationZ - pRotationZ > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\ndescribe('no image to display.');\n
\nThe system variable rotationX always contains the rotation of the\ndevice along the x axis. If the sketch \nangleMode() is set to DEGREES, the value will be -180 to 180. If\nit is set to RADIANS, the value will be -PI to PI.
\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.
\n"],"line":[0,131],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n //rotateZ(radians(rotationZ));\n rotateX(radians(rotationX));\n //rotateY(radians(rotationY));\n box(200, 200, 200);\n describe(`red horizontal line right, green vertical line bottom.\n black background.`);\n}\n
\nThe system variable rotationY always contains the rotation of the\ndevice along the y axis. If the sketch \nangleMode() is set to DEGREES, the value will be -90 to 90. If\nit is set to RADIANS, the value will be -PI/2 to PI/2.
\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.
\n"],"line":[0,164],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n //rotateZ(radians(rotationZ));\n //rotateX(radians(rotationX));\n rotateY(radians(rotationY));\n box(200, 200, 200);\n describe(`red horizontal line right, green vertical line bottom.\n black background.`);\n}\n
\nThe system variable rotationZ always contains the rotation of the\ndevice along the z axis. If the sketch \nangleMode() is set to DEGREES, the value will be 0 to 360. If\nit is set to RADIANS, the value will be 0 to 2*PI.
\nUnlike rotationX and rotationY, this variable is available for devices\nwith a built-in compass only.
\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.
\n"],"line":[0,197],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateZ(radians(rotationZ));\n //rotateX(radians(rotationX));\n //rotateY(radians(rotationY));\n box(200, 200, 200);\n describe(`red horizontal line right, green vertical line bottom.\n black background.`);\n}\n
\nThe setMoveThreshold() function is used to set the movement threshold for\nthe deviceMoved() function. The default threshold is set to 0.5.
\n"],"line":[0,417],"params":[1,[[0,{"name":[0,"value"],"description":[0,"The threshold value
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Run this example on a mobile device\n// You will need to move the device incrementally further\n// the closer the square's color gets to white in order to change the value.\n\nlet value = 0;\nlet threshold = 0.5;\nfunction setup() {\n setMoveThreshold(threshold);\n}\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when device moves`);\n}\nfunction deviceMoved() {\n value = value + 5;\n threshold = threshold + 0.1;\n if (value > 255) {\n value = 0;\n threshold = 30;\n }\n setMoveThreshold(threshold);\n}\n
\nThe setShakeThreshold() function is used to set the movement threshold for\nthe deviceShaken() function. The default threshold is set to 30.
\n"],"line":[0,459],"params":[1,[[0,{"name":[0,"value"],"description":[0,"The threshold value
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Run this example on a mobile device\n// You will need to shake the device more firmly\n// the closer the box's fill gets to white in order to change the value.\n\nlet value = 0;\nlet threshold = 30;\nfunction setup() {\n setShakeThreshold(threshold);\n}\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when device is being shaked`);\n}\nfunction deviceMoved() {\n value = value + 5;\n threshold = threshold + 5;\n if (value > 255) {\n value = 0;\n threshold = 30;\n }\n setShakeThreshold(threshold);\n}\n
\nWhen a device is rotated, the axis that triggers the deviceTurned()\nmethod is stored in the turnAxis variable. The turnAxis variable is only defined within\nthe scope of deviceTurned().
\n"],"line":[0,378],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees in the\n// X-axis to change the value.\n\nlet value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when device turns`);\n describe(`50-by-50 black rect in center of canvas.\n turns white on mobile when x-axis turns`);\n}\nfunction deviceTurned() {\n if (turnAxis === 'X') {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n }\n}\n
\nUna variable del sistema String
que contiene el valor de la última tecla pulsada.
La variable key
es útil para comprobar si se ha pulsado una\ntecla ASCII\nen particular. Por ejemplo, la expresión key === \"a\"
resulta en\ntrue
si se ha pulsado la tecla a
y false
en caso contrario. key
no se actualiza\npara teclas especiales como LEFT_ARROW
y ENTER
. Utiliza keyCode
en su lugar para\nlas teclas especiales. La función keyIsDown() debe\nutilizarse para comprobar la presión de múltiples teclas al mismo tiempo.
\n// Click on the canvas to begin detecting key presses.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. The last key pressed is displayed at the center.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the last key pressed.\n text(key, 50, 50);\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nlet x = 50;\nlet y = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe(\n 'A gray square with a black circle at its center. The circle moves when the user presses the keys \"w\", \"a\", \"s\", or \"d\". It leaves a trail as it moves.'\n );\n}\n\nfunction draw() {\n // Update x and y if a key is pressed.\n if (keyIsPressed === true) {\n if (key === 'w') {\n y -= 1;\n } else if (key === 's') {\n y += 1;\n } else if (key === 'a') {\n x -= 1;\n } else if (key === 'd') {\n x += 1;\n }\n }\n\n // Style the circle.\n fill(0);\n\n // Draw the circle at (x, y).\n circle(x, y, 5);\n}\n
\nUna variable de sistema Number
que contiene el código de la última tecla presionada.
Todas las teclas tienen un keyCode
. Por ejemplo, la tecla a
tiene el keyCode
65.\nLa variable keyCode
es útil para comprobar si una tecla especial ha sido presionada. Por ejemplo, el siguiente condicional comprueba si se ha pulsado la tecla enter:
\nif (keyCode === 13) {\n // Code to run if the enter key was pressed.\n}\n
\n\nEl mismo código se puede escribir de forma más clara utilizando la variable de sistema ENTER
\nque tiene un valor de 13:
\nif (keyCode === ENTER) {\n // Code to run if the enter key was pressed.\n}\n
\n\nLas variables de sistema BACKSPACE
, DELETE
, ENTER
, RETURN
, TAB
,\nESCAPE
, SHIFT
, CONTROL
, OPTION
, ALT
, UP_ARROW
, DOWN_ARROW
,\nLEFT_ARROW
y RIGHT_ARROW
son alias convenientes para los códigos de teclas especiales. Los códigos de teclas se pueden encontrar en sitios web como keycode.info.
\n// Click on the canvas to begin detecting key presses.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. The last key pressed and its code are displayed at the center.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the last key pressed and its code.\n text(`${key} : ${keyCode}`, 50, 50);\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nlet x = 50;\nlet y = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe(\n 'A gray square with a black circle at its center. The circle moves when the user presses an arrow key. It leaves a trail as it moves.'\n );\n}\n\nfunction draw() {\n // Update x and y if an arrow key is pressed.\n if (keyIsPressed === true) {\n if (keyCode === UP_ARROW) {\n y -= 1;\n } else if (keyCode === DOWN_ARROW) {\n y += 1;\n } else if (keyCode === LEFT_ARROW) {\n x -= 1;\n } else if (keyCode === RIGHT_ARROW) {\n x += 1;\n }\n }\n\n // Style the circle.\n fill(0);\n\n // Draw the circle at (x, y).\n circle(x, y, 5);\n}\n
\nDevuelve true
si la tecla que se está comprobando está presionada y false
si no lo está.
keyIsDown()
es útil para comprobar si se están presionando varias teclas diferentes.\nPor ejemplo, keyIsDown()
se puede usar para comprobar si se presionan tanto la tecla LEFT_ARROW
como la tecla UP_ARROW
:
\nif (keyIsDown(LEFT_ARROW) && keyIsDown(UP_ARROW)) {\n // Move diagonally.\n}\n
\n\nkeyIsDown()
también puede comprobar la presión de teclas mediante\nlos valores keyCode. Por ejemplo, keyIsDown(37)
o keyIsDown(LEFT_ARROW)
. Los valores de keyCode se pueden encontrar en sitios web como\nkeycode.info.
key to check.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"whether the key is down or not."],"type":[0,"Boolean"]}],"example":[1,[[0,"\n\n// Click on the canvas to begin detecting key presses.\n\nlet x = 50;\nlet y = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe(\n 'A gray square with a black circle at its center. The circle moves when the user presses an arrow key. It leaves a trail as it moves.'\n );\n}\n\nfunction draw() {\n // Update x and y if an arrow key is pressed.\n if (keyIsDown(LEFT_ARROW) === true) {\n x -= 1;\n }\n\n if (keyIsDown(RIGHT_ARROW) === true) {\n x += 1;\n }\n\n if (keyIsDown(UP_ARROW) === true) {\n y -= 1;\n }\n\n if (keyIsDown(DOWN_ARROW) === true) {\n y += 1;\n }\n\n // Style the circle.\n fill(0);\n\n // Draw the circle.\n circle(x, y, 5);\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nlet x = 50;\nlet y = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe(\n 'A gray square with a black circle at its center. The circle moves when the user presses an arrow key. It leaves a trail as it moves.'\n );\n}\n\nfunction draw() {\n // Update x and y if an arrow key is pressed.\n if (keyIsDown(37) === true) {\n x -= 1;\n }\n\n if (keyIsDown(39) === true) {\n x += 1;\n }\n\n if (keyIsDown(38) === true) {\n y -= 1;\n }\n\n if (keyIsDown(40) === true) {\n y += 1;\n }\n\n // Style the circle.\n fill(0);\n\n // Draw the circle.\n circle(x, y, 5);\n}\n
\nUna variable de sistema Boolean
que es true
si se está presionando alguna tecla\ny false
si no se está presionando ninguna tecla.
\n// Click on the canvas to begin detecting key presses.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a white square at its center. The white square turns black when the user presses a key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n if (keyIsPressed === true) {\n fill(0);\n } else {\n fill(255);\n }\n\n // Draw the square.\n square(25, 25, 50);\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with the word \"false\" at its center. The word switches to \"true\" when the user presses a key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the value of keyIsPressed.\n text(keyIsPressed, 50, 50);\n}\n
\nUna función que se ejecuta una vez cuando se presiona cualquier tecla.
\nDeclarar la función keyPressed()
establece un bloque de código para\nejecutarse automáticamente cuando el usuario presiona cualquier tecla:
\nfunction keyPressed() {\n // Code to run.\n}\n
\n\nLas variables key y keyCode\nse actualizarán con el valor más reciente que se ha digitado cuando\nkeyPressed()
es llamada por p5.js:
\nfunction keyPressed() {\n if (key === 'c') {\n // Code to run.\n }\n\n if (keyCode === ENTER) {\n // Code to run.\n }\n}\n
\nEl parámetro, event
, es opcional. keyPressed()
siempre se le pasa un objeto\nKeyboardEvent\ncon propiedades que describen el evento de presión de tecla:
\nfunction keyPressed(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n\nLos navegadores pueden tener comportamientos predeterminados asociados a\ndiferentes eventos de teclado. Por ejemplo, algunos navegadores pueden saltar al final de una página web cuando se presiona la tecla SPACE
. Para evitar cualquier comportamiento predeterminado para este evento, añada return false;
al final de la función.
Argumento opcional KeyboardEvent
del callback.
\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square changes color when the user presses a key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle the background color when the user presses a key.\nfunction keyPressed() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a white square at its center. The inner square turns black when the user presses the \"b\" key. It turns white when the user presses the \"a\" key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Reassign value when the user presses the 'a' or 'b' key.\nfunction keyPressed() {\n if (key === 'a') {\n value = 255;\n } else if (key === 'b') {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square turns white when the user presses the left arrow key. It turns black when the user presses the right arrow key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle the background color when the user presses an arrow key.\nfunction keyPressed() {\n if (keyCode === LEFT_ARROW) {\n value = 255;\n } else if (keyCode === RIGHT_ARROW) {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\nUna función que se ejecuta una vez cuando se libera cualquier tecla.
\nDeclarar la función keyReleased()
establece un bloque de código para ejecutarse\nautomáticamente cuando el usuario libera cualquier tecla:
\nfunction keyReleased() {\n // Code to run.\n}\n
\n\nLas variables key y keyCode\nse actualizarán con el valor liberado más recientemente cuando\nkeyReleased()
sea llamado por p5.js:
\nfunction keyReleased() {\n if (key === 'c') {\n // Code to run.\n }\n\n if (keyCode === ENTER) {\n // Code to run.\n }\n}\n
\nEl parámetro, event
, es opcional. keyReleased()
siempre se le pasa un\nobjeto KeyboardEvent\ncon propiedades que describen el evento de tecla:
\nfunction keyReleased(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n\nLos navegadores pueden tener comportamientos predeterminados asociados a\nciertos eventos de tecla. Para evitar cualquier comportamiento predeterminado para este evento, agregue return false;
al final\nde la función.
Argumento opcional KeyboardEvent
del callback.
\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square changes color when the user releases a key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle value when the user releases a key.\nfunction keyReleased() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square becomes white when the user releases the \"w\" key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Set value to 255 the user releases the 'w' key.\nfunction keyReleased() {\n if (key === 'w') {\n value = 255;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square turns white when the user presses and releases the left arrow key. It turns black when the user presses and releases the right arrow key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle the background color when the user releases an arrow key.\nfunction keyReleased() {\n if (keyCode === LEFT_ARROW) {\n value = 255;\n } else if (keyCode === RIGHT_ARROW) {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\nUna función que se ejecuta una vez cuando se presiona una tecla con un caracter imprimible.
\nDeclarar la función keyTyped()
establece un bloque de código a ejecutarse\nautomáticamente cuando el usuario presiona cualquier tecla con un caracter\nimprimible como a
o 1. Las teclas de modificador como SHIFT
,\nCONTROL
y las flechas\nserán ignoradas:
\nfunction keyTyped() {\n // Code to run.\n}\n
\n\nLa variable key y keyCode\nse actualizarán con el valor más reciente que se ha liberado cuando\nkeyTyped()
es llamada por p5.js:
\nfunction keyTyped() {\n // Check for the \"c\" character using key.\n if (key === 'c') {\n // Code to run.\n }\n\n // Check for \"c\" using keyCode.\n if (keyCode === 67) {\n // Code to run.\n }\n}\n
\nEl parámetro, event
, es opcional. keyTyped()
siempre se le paso un objeto\nKeyboardEvent\ncon propiedades que describen el evento de presión de tecla:
\nfunction keyReleased(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n\nNota: Use la función keyPressed() y\nkeyCode para responder a las teclas de\nmodificador como ALT
.
Los navegadores pueden tener comportamientos predeterminados asociados a\nciertos eventos de tecla. Para evitar cualquier comportamiento predeterminado\npara este evento, agregue return false;
al final de la función.
optional KeyboardEvent
callback argument.
\n// Click on the canvas to begin detecting key presses.\n// Note: Pressing special keys such as SPACE have no effect.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a white square at its center. The inner square changes color when the user presses a key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle the square's color when the user types a printable key.\nfunction keyTyped() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a white square at its center. The inner square turns black when the user types the \"b\" key. It turns white when the user types the \"a\" key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Reassign value when the user types the 'a' or 'b' key.\nfunction keyTyped() {\n if (key === 'a') {\n value = 255;\n } else if (key === 'b') {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\nUna función que se ejecuta una vez cuando el botón del mouse se hace doble click rápidamente.
\nDeclarar la función doubleClicked()
establece un bloque de código para ejecutarse\nautomáticamente cuando el usuario presiona y suelta el botón del mouse dos\nveces rápidamente:
\nfunction doubleClicked() {\n // Code to run.\n}\n
\n\nLas variables de sistema del ratón, como mouseX y\nmouseY, se actualizarán con su valor más\nreciente cuando doubleClicked()
se ejecute automáticamente por p5.js:
\nfunction doubleClicked() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\nEl parámetro, event
, es opcional. doubleClicked()
se le pasa siempre un\nMouseEvent\nobjeto con propiedades que describen el evento de doble click:
\nfunction doubleClicked(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n\nEn dispositivos táctiles, el código colocado en doubleClicked()
se ejecutará después de dos\npulsaciones táctiles que ocurran en un breve lapso de tiempo.
Los navegadores pueden tener comportamientos predeterminados asociados a eventos de ratón. Por ejemplo, algunos navegadores resaltan texto cuando el usuario se mueve el ratón mientras presiona un botón del ratón. Para evitar cualquier comportamiento predeterminado para este evento, agrega return false;
al final de la función.
Argumento opcional MouseEvent
.
\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square changes color when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle the square's color when the user double-clicks.\nfunction doubleClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black circle at its center. When the user double-clicks on the circle, it changes color to white.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the circle.\n fill(value);\n\n // Draw the circle.\n circle(50, 50, 80);\n}\n\n// Reassign value to 255 when the user double-clicks on the circle.\nfunction doubleClicked() {\n if (dist(50, 50, mouseX, mouseY) < 40) {\n value = 255;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\nSale de un bloqueo de puntero iniciado con\nrequestPointerLock.
\nLlamar a requestPointerLock()
bloquea los valores de\nmouseX, mouseY,\npmouseX, y pmouseY.\nLlamar a exitPointerLock()
hace que se vuelva a actualizar el sistema de coordenadas del mouse.
Nota: La mayoría de los navegadores requieren una entrada, como un clic, antes de llamar\na requestPointerLock()
. Se recomienda llamar a requestPointerLock()
en\nuna función de evento como doubleClicked().
\nlet isLocked = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a word at its center. The word changes between \"Unlocked\" and \"Locked\" when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Tell the user whether the pointer is locked.\n if (isLocked === true) {\n text('Locked', 50, 50);\n } else {\n text('Unlocked', 50, 50);\n }\n}\n\n// Toggle the pointer lock when the user double-clicks.\nfunction doubleClicked() {\n if (isLocked === true) {\n exitPointerLock();\n isLocked = false;\n } else {\n requestPointerLock();\n isLocked = true;\n }\n}\n
\nUna variable de tipo String del sistema que contiene el valor del último botón\ndel mouse presionado.
\nLa variable mouseButton
es LEFT
, RIGHT
o CENTER
,\ndependiendo del botón que fue presionado por última vez.
Tenga en cuenta que los diferentes navegadores pueden rastrear mouseButton
de manera diferente. Consulte\nMDN\npara más información.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with black text at its center. The text changes from 0 to either \"left\" or \"right\" when the user clicks a mouse button.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the mouse button.\n text(mouseButton, 50, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n \"A gray square. Different shapes appear at its center depending on the mouse button that's clicked.\"\n );\n}\n\nfunction draw() {\n background(200);\n\n if (mouseIsPressed === true) {\n if (mouseButton === LEFT) {\n circle(50, 50, 50);\n }\n if (mouseButton === RIGHT) {\n square(25, 25, 50);\n }\n if (mouseButton === CENTER) {\n triangle(23, 75, 50, 20, 78, 75);\n }\n }\n}\n
\nUna función que se ejecuta una vez después de que se presiona y se suelta un botón del mouse.
\nDeclarar la función mouseClicked()
establece un bloque de código para ejecutarse automáticamente cuando el usuario suelta un botón del mouse después de haberlo presionado:
\nfunction mouseClicked() {\n // Code to run.\n}\n
\n\nLas variables del sistema del mouse, como mouseX y\nmouseY, se actualizarán con su valor más\nreciente cuando mouseClicked()
sea llamado por p5.js:
\nfunction mouseClicked() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\nEl parámetro, event
, es opcional. mouseClicked()
siempre\nse le pasa un objeto MouseEvent con propiedades que describen el evento de clic del mouse:
\nfunction mouseClicked(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n\nEn dispositivos táctiles, mouseClicked()
se ejecutará cuando un usuario\nsuelta su toque si touchEnded() no está\ndeclarado. Si touchEnded() es declarado, entonces\ntouchEnded() se ejecutará cuando un usuario suelta su toque y mouseClicked()
no se ejecutará.
Los navegadores pueden tener comportamientos predeterminados asociados a\ndiferentes eventos del mouse. Por ejemplo, algunos navegadores resaltan texto cuando el usuario mueve el mouse mientras mantiene un botón presionado. Para\nevitar cualquier comportamiento predeterminado para este evento, agrega return false;
al final de la función.
Nota: mousePressed(),\nmouseReleased() y\nmouseClicked()
están relacionados.\nmousePressed() se ejecuta justo después de que\nel usuario presiona el mouse. mouseReleased() se ejecuta justo después de que el usuario suelta el clic del mouse. mouseClicked()
se ejecuta inmediatamente después de mouseReleased().
Argumento opcional MouseEvent
.
\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square changes color when the user presses and releases a mouse button.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle the square's color when the user clicks.\nfunction mouseClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Style the circle.\n fill('orange');\n stroke('royalblue');\n strokeWeight(10);\n\n describe(\n 'An orange circle with a thick, blue border drawn on a gray background. When the user presses and holds the mouse, the border becomes thin and pink. When the user releases the mouse, the border becomes thicker and changes color to blue.'\n );\n}\n\nfunction draw() {\n background(220);\n\n // Draw the circle.\n circle(50, 50, 20);\n}\n\n// Set the stroke color and weight as soon as the user clicks.\nfunction mousePressed() {\n stroke('deeppink');\n strokeWeight(3);\n}\n\n// Set the stroke and fill colors as soon as the user releases\n// the mouse.\nfunction mouseReleased() {\n stroke('royalblue');\n\n // This is never visible because fill() is called\n // in mouseClicked() which runs immediately after\n // mouseReleased();\n fill('limegreen');\n}\n\n// Set the fill color and stroke weight after\n// mousePressed() and mouseReleased() are called.\nfunction mouseClicked() {\n fill('orange');\n strokeWeight(10);\n}\n
\nUna función que se llama cuando el mouse se mueve mientras se mantiene pulsado un botón.
\nDeclarar la función mouseDragged()
establece un bloque de código para ejecutarse\nautomáticamente cuando el usuario hace clic y arrastra el mouse:
\nfunction mouseDragged() {\n // Code to run.\n}\n
\n\nLas variables del sistema del mouse, como mouseX y\nmouseY, se actualizarán con su valor más reciente\ncuando mouseDragged()
sea llamado por p5.js:
\nfunction mouseDragged() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\nEl parámetro event
es opcional. mouseDragged()
siempre se le pasa un\nMouseEvent\nobjeto con propiedades que describen el evento de arrastre del mouse:
\nfunction mouseDragged(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n\nEn dispositivos táctiles, mouseDragged()
se ejecutará cuando el usuario mueve un punto de\ntacto si touchMoved() no está declarado. Si\ntouchMoved() está declarado, entonces\ntouchMoved() se ejecutará cuando el usuario mueve un punto de tacto y mouseDragged()
no se ejecutará.
Los navegadores pueden tener comportamientos predeterminados asociados a eventos del mouse. Por ejemplo, algunos navegadores resaltan texto cuando el usuario mueve el mouse mientras mantiene pulsado un botón. Para evitar cualquier comportamiento predeterminado para este evento, agregue return false;
al final de la función.
Argumento opcional MouseEvent
.
\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square becomes lighter as the user drags the mouse.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\nfunction mouseDragged() {\n // Update the grayscale value.\n value += 5;\n\n // Reset the grayscale value.\n if (value > 255) {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\nUna variable del sistema Boolean
que es true
si el mouse está presionado y false
si no lo está.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with the word \"false\" at its center. The word changes to \"true\" when the user presses a mouse button.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the mouseIsPressed variable.\n text(mouseIsPressed, 25, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a white square at its center. The inner square turns black when the user presses the mouse.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n if (mouseIsPressed === true) {\n fill(0);\n } else {\n fill(255);\n }\n\n // Draw the square.\n square(25, 25, 50);\n}\n
\nUna función que se ejecuta cuando el usuario mueve el ratón.
\nDeclarar la función mouseMoved()
establece un bloque de código que se ejecutará\nautomáticamente cuando el usuario mueva el ratón sin tener presionado ningún botón:
\nfunction mouseMoved() {\n // Code to run.\n}\n
\n\nLas variables del sistema del ratón, como mouseX y\nmouseY, se actualizarán con su valor más reciente\ncuando mouseMoved()
sea ejecutada por p5.js:
\nfunction mouseMoved() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\nEl parámetro, event
, es opcional. mouseMoved()
siempre se le pasa un\nobjeto MouseEvent con propiedades que describen el evento de movimiento del ratón:
\nfunction mouseMoved(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n\nLos navegadores pueden tener comportamientos predeterminados asociados a ciertos eventos del ratón. Por ejemplo, algunos navegadores resaltan texto cuando el usuario mueve el ratón mientras presiona un botón. Para evitar cualquier comportamiento predeterminado para este evento,\nagrega return false;
al final de la función.
Argumento opcional MouseEvent
.
\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square becomes lighter as the mouse moves.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\nfunction mouseMoved() {\n // Update the grayscale value.\n value += 5;\n\n // Reset the grayscale value.\n if (value > 255) {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\nUna función que se llama una vez cuando se presiona un botón del mouse.
\nDeclarar la función mousePressed()
establece un bloque de código para ejecutarse\nautomáticamente cuando el usuario presiona un botón del mouse:
\nfunction mousePressed() {\n // Code to run.\n}\n
\n\nLas variables del sistema del mouse, como mouseX y\nmouseY, se actualizarán con su valor más reciente\ncuando mousePressed()
sea llamado por p5.js:
\nfunction mousePressed() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\nEl parámetro event
es opcional. mousePressed()
siempre se le pasa un\nMouseEvent\nobjeto con propiedades que describen el evento de presión del mouse:
\nfunction mousePressed(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n\nEn dispositivos táctiles, mousePressed()
se ejecutará cuando el usuario\ntoca la pantalla si touchStarted() no está declarado. Si\ntouchStarted() está declarado, entonces\ntouchStarted() se ejecutará cuando el usuario toca la pantalla y mousePressed()
no se ejecutará.
Los navegadores pueden tener comportamientos predeterminados asociados a eventos de mouse. Por ejemplo, algunos navegadores resaltan texto cuando el usuario mueve el mouse mientras mantiene presionado un botón del mouse. Para evitar cualquier comportamiento predeterminado para este evento, añada return false;
al final de la función.
Nota: mousePressed()
, mouseReleased(),\ny mouseClicked() estan todos relacionados.\nmousePressed()
se ejecuta inmediatamente cuando el usuario presiona el mouse.\nmouseReleased() se ejecuta inmediatamente después de que el usuario suelte el mouse. mouseClicked() se ejecuta inmediatamente después de mouseReleased().
Argumento opcional MouseEvent
.
\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square becomes lighter when the user presses a mouse button.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\nfunction mousePressed() {\n // Update the grayscale value.\n value += 5;\n\n // Reset the grayscale value.\n if (value > 255) {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Style the circle.\n fill('orange');\n stroke('royalblue');\n strokeWeight(10);\n\n describe(\n 'An orange circle with a thick, blue border drawn on a gray background. When the user presses and holds the mouse, the border becomes thin and pink. When the user releases the mouse, the border becomes thicker and changes color to blue.'\n );\n}\n\nfunction draw() {\n background(220);\n\n // Draw the circle.\n circle(50, 50, 20);\n}\n\n// Set the stroke color and weight as soon as the user clicks.\nfunction mousePressed() {\n stroke('deeppink');\n strokeWeight(3);\n}\n\n// Set the stroke and fill colors as soon as the user releases\n// the mouse.\nfunction mouseReleased() {\n stroke('royalblue');\n\n // This is never visible because fill() is called\n // in mouseClicked() which runs immediately after\n // mouseReleased();\n fill('limegreen');\n}\n\n// Set the fill color and stroke weight after\n// mousePressed() and mouseReleased() are called.\nfunction mouseClicked() {\n fill('orange');\n strokeWeight(10);\n}\n
\nUna función que se ejecuta una vez cuando se libera un botón del mouse.
\nDeclarar la función mouseReleased()
establece un bloque de código para ejecutarse automáticamente cuando el usuario libera un botón del mouse después de haberlo presionado:
\nfunction mouseReleased() {\n // Code to run.\n}\n
\n\nLas variables del sistema del mouse, como mouseX y\nmouseY, se actualizarán con su valor más\nreciente cuando mouseReleased()
sea llamado por p5.js:
\nfunction mouseReleased() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Código a ejecutar si el mouse está cerca del final.\n }\n}\n
\nEl parámetro, event
, es opcional. mouseReleased()
siempre\nse le pasa un objeto MouseEvent con propiedades que describen el evento de liberación del mouse:
\nfunction mouseReleased(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n\nEn dispositivos táctiles, mouseReleased()
se ejecutará cuando el usuario termina de tocar la pantalla si touchEnded() no está declarado. Si touchEnded() está declarado, entonces\ntouchEnded() se ejecutará cuando el usuario termina de tocar la pantalla y mouseReleased()
no se ejecutará.
Los navegadores pueden tener comportamientos predeterminados asociados a eventos del mouse. Por ejemplo, algunos navegadores resaltan texto cuando el usuario mueve el mouse mientras presiona un botón del mouse. Para evitar cualquier comportamiento predeterminado para este evento, agregue return false;
al final de la función.
Nota: mousePressed(), mouseReleased()
,\ny mouseClicked() estan todos relacionados.\nmousePressed() se ejecuta justo después de que el usuario presiona el mouse. mouseReleased()
se ejecuta justo después de que el usuario libera el botón del mouse. mouseClicked()\nse ejecuta justo después de que mouseReleased()
se ejecute.
Argumento opcional MouseEvent
.
\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square becomes lighter when the user presses and releases a mouse button.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\nfunction mouseReleased() {\n // Update the grayscale value.\n value += 5;\n\n // Reset the grayscale value.\n if (value > 255) {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Style the circle.\n fill('orange');\n stroke('royalblue');\n strokeWeight(10);\n\n describe(\n 'An orange circle with a thick, blue border drawn on a gray background. When the user presses and holds the mouse, the border becomes thin and pink. When the user releases the mouse, the border becomes thicker and changes color to blue.'\n );\n}\n\nfunction draw() {\n background(220);\n\n // Draw the circle.\n circle(50, 50, 20);\n}\n\n// Set the stroke color and weight as soon as the user clicks.\nfunction mousePressed() {\n stroke('deeppink');\n strokeWeight(3);\n}\n\n// Set the stroke and fill colors as soon as the user releases\n// the mouse.\nfunction mouseReleased() {\n stroke('royalblue');\n\n // This is never visible because fill() is called\n // in mouseClicked() which runs immediately after\n // mouseReleased();\n fill('limegreen');\n}\n\n// Set the fill color and stroke weight after\n// mousePressed() and mouseReleased() are called.\nfunction mouseClicked() {\n fill('orange');\n strokeWeight(10);\n}\n
\nUna función que se ejecuta una vez cuando el rueda del ratón se mueve.
\nDeclarar la función mouseWheel()
establece un bloque de código\npara ejecutarse automáticamente cuando el usuario hace scroll con el ratón:
\nfunction mouseWheel() {\n // Code to run.\n}\n
\n\nLas variables del sistema del ratón, como mouseX y\nmouseY, se actualizarán con su valor más reciente\ncuando mouseWheel()
sea llamada por p5.js:
\nfunction mouseWheel() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\nEl parámetro, event
, es opcional. mouseWheel()
siempre se le pasa un\nMouseEvent\nobjeto con propiedades que describen el evento de desplazamiento del ratón:
\nfunction mouseWheel(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n\nEl objeto event
tiene muchas propiedades incluyendo delta
, un Number
\nque contiene la distancia que el usuario ha hecho scroll. Por ejemplo, event.delta
\npodría tener el valor 5 cuando el usuario hace scroll hacia arriba. event.delta
es positivo\nsi el usuario hace scroll hacia arriba y negativo si hace scroll hacia abajo. Los signos son\nopuestos en macOS con \"natural\" scrolling habilitado.
Los navegadores pueden tener comportamientos predeterminados asociados a\neventos de ratón. Por ejemplo, algunos navegadores resaltan texto cuando el usuario mueve el ratón mientras mantiene un botón presionado. Para evitar cualquier comportamiento predeterminado para este evento, agregue return false;
\nal final de la función.
Nota: En Safari, mouseWheel()
podría no funcionar de manera\nesperada si no se agrega return false;
al final de la función.
Argumento opcional WheelEvent
.
\nlet circleSize = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. A white circle at its center grows up when the user scrolls the mouse wheel.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw the circle\n circle(circleSize, 50, 50);\n}\n\n// Increment circleSize when the user scrolls the mouse wheel.\nfunction mouseWheel() {\n circleSize += 1;\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\nlet direction = '';\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. An arrow at its center points up when the user scrolls up. The arrow points down when the user scrolls down.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Draw an arrow that points where\n // the mouse last scrolled.\n text(direction, 50, 50);\n}\n\n// Change direction when the user scrolls the mouse wheel.\nfunction mouseWheel(event) {\n if (event.delta > 0) {\n direction = '▲';\n } else {\n direction = '▼';\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\nUna variable de sistema Number
que sigue la posición horizontal del ratón.
En modo 2D, mouseX
rastrea la posición del ratón relativa al\nborde superior izquierdo del lienzo. Por ejemplo, si el ratón está a 50 pixeles\ndel borde izquierdo del lienzo, entonces mouseX
valdrá 50.
En modo WebGL, mouseX
rastrea la posición del ratón relativa al\ncentro del lienzo. Por ejemplo, si el ratón está a 50 pixels a la derecha del\ncentro del lienzo, entonces mouseX
valdrá 50.
Si se usa el dedo en lugar del ratón, entonces mouseX
contendrá la\ncoordenada x del punto de toque más reciente.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A vertical black line moves left and right following the mouse's x-position.\");\n}\n\nfunction draw() {\n background(200);\n\n // Draw a vertical line that follows the mouse's x-coordinate.\n line(mouseX, 0, mouseX, 100);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse.\");\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the mouse's coordinates.\n text(`x: ${mouseX} y: ${mouseY}`, 50, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\"A vertical black line moves left and right following the mouse's x-position.\");\n}\n\nfunction draw() {\n background(200);\n\n // Adjust coordinates for WebGL mode.\n // The origin (0, 0) is at the center of the canvas.\n let mx = mouseX - 50;\n\n // Draw the line.\n line(mx, -50, mx, 50);\n}\n
\n\nlet font;\n\n// Load a font for WebGL mode.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n \"A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse.\"\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Display the mouse's coordinates.\n text(`x: ${mouseX} y: ${mouseY}`, 0, 0);\n}\n
\nUna variable del sistema Number
que sigue la posición vertical del mouse.
En modo 2D, mouseY
sigue la posición del mouse relativa a la\nesquina superior izquierda del lienzo. Por ejemplo, si el mouse está a 50 pixeles de la parte superior del lienzo, entonces mouseY
será 50.
En modo WebGL, mouseY
sigue la posición del mouse relativa al centro\ndel lienzo. Por ejemplo, si el mouse está a 50 pixels por debajo del centro del lienzo, entonces mouseY
será 50.
Si se usa el touch en lugar del mouse, entonces mouseY
contendrá la coordenada y del punto de contacto más reciente.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A horizontal black line moves up and down following the mouse's y-position.\");\n}\n\nfunction draw() {\n background(200);\n\n // Draw a horizontal line that follows the mouse's y-coordinate.\n line(0, mouseY, 0, mouseY);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse.\");\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the mouse's coordinates.\n text(`x: ${mouseX} y: ${mouseY}`, 50, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\"A horizontal black line moves up and down following the mouse's y-position.\");\n}\n\nfunction draw() {\n background(200);\n\n // Adjust coordinates for WebGL mode.\n // The origin (0, 0) is at the center of the canvas.\n let my = mouseY - 50;\n\n // Draw the line.\n line(-50, my, 50, my);\n}\n
\n\nlet font;\n\n// Load a font for WebGL mode.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n \"A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse.\"\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Display the mouse's coordinates.\n text(`x: ${mouseX} y: ${mouseY}`, 0, 0);\n}\n
\nUna variable de sistema Number
que sigue el movimiento horizontal del ratón.
movedX
rastrea el número de píxeles que el ratón se mueve hacia la derecha o hacia la izquierda entre fotogramas. movedX
tendrá un valor negativo si el ratón se mueve hacia la izquierda entre fotogramas y un valor positivo si se mueve hacia la derecha.
movedX
puede ser calculado como mouseX - pmouseX
.
Nota: movedX
sigue actualizándose incluso cuando requestPointerLock() está activo.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. The text \">>\" appears when the user moves the mouse to the right. The text \"<<\" appears when the user moves the mouse to the left.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display >> when movedX is positive and\n // << when it's negative.\n if (movedX > 0) {\n text('>>', 50, 50);\n } else if (movedX < 0) {\n text('<<', 50, 50);\n }\n}\n
\nUna variable de sistema Number
que sigue el movimiento vertical del ratón.
movedY
rastrea el número de píxeles que el ratón se mueve hacia arriba o hacia abajo entre fotogramas. movedY
tendrá un valor negativo si el ratón se mueve hacia arriba entre fotogramas y un valor positivo si se mueve hacia abajo.
movedY
puede ser calculado como mouseY - pmouseY
.
Nota: movedY
sigue actualizándose incluso cuando requestPointerLock() está activo.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. The text \"▲\" appears when the user moves the mouse upward. The text \"▼\" appears when the user moves the mouse downward.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display ▼ when movedY is positive and\n // ▲ when it's negative.\n if (movedY > 0) {\n text('▼', 50, 50);\n } else if (movedY < 0) {\n text('▲', 50, 50);\n }\n}\n
\nUna variable del sistema Number
que sigue la posición horizontal anterior\ndel mouse.
En modo 2D, pmouseX
sigue la posición del mouse relativa a la\nesquina superior izquierda del lienzo. Su valor es\nmouseX del último fotograma. Por ejemplo, si\nel mouse estaba a 50 pixeles de la parte izquierda del lienzo en el último fotograma, entonces pmouseX
será 50.
En modo WebGL, pmouseX
sigue la posición del mouse relativa al centro\ndel lienzo. Por ejemplo, si el mouse estaba a 50 pixeles a la derecha del centro del lienzo en el último fotograma, entonces pmouseX
será 50.
Si se usa el touch en lugar del mouse, entonces pmouseX
contendrá la coordenada x del punto de contacto más reciente.
Nota: pmouseX
se resetea a la mouseX actual al inicio de cada evento de touch.
\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(10);\n\n describe('A line follows the mouse as it moves. The line grows longer with faster movements.');\n}\n\nfunction draw() {\n background(200);\n\n line(pmouseX, pmouseY, mouseX, mouseY);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A line follows the mouse as it moves. The line grows longer with faster movements.');\n}\n\nfunction draw() {\n background(200);\n\n // Adjust coordinates for WebGL mode.\n // The origin (0, 0) is at the center of the canvas.\n let pmx = pmouseX - 50;\n let pmy = pmouseY - 50;\n let mx = mouseX - 50;\n let my = mouseY - 50;\n\n // Draw the line.\n line(pmx, pmy, mx, my);\n}\n
\nUna variable de sistema Number
que sigue la posición vertical del\nratón.
En modo 2D, pmouseY
mantiene un registro de la posición del ratón relativa a la\nesquina superior izquierda del lienzo. Su valor es\nmouseY en el fotograma anterior. Por ejemplo, si\nel ratón estaba a 50 píxeles del borde superior del lienzo durante el fotograma anterior, entonces pmouseY
será 50.
En modo WebGL, pmouseY
mantiene un registro de la posición del ratón relativa al\ncentro del lienzo. Por ejemplo, si el ratón estaba a 50 píxeles debajo del centro del lienzo durante el\nfotograma anterior, entonces pmouseY
será 50.
Si se utiliza en lugar del ratón el touch, entonces pmouseY
mantendrá la\ncoordenada y del último punto de contacto.
Nota: pmouseY
se restablece al valor actual de mouseY\nal inicio de cada evento de touch.
\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(10);\n\n describe('A line follows the mouse as it moves. The line grows longer with faster movements.');\n}\n\nfunction draw() {\n background(200);\n\n line(pmouseX, pmouseY, mouseX, mouseY);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A line follows the mouse as it moves. The line grows longer with faster movements.');\n}\n\nfunction draw() {\n background(200);\n\n // Adjust coordinates for WebGL mode.\n // The origin (0, 0) is at the center of the canvas.\n let pmx = pmouseX - 50;\n let pmy = pmouseY - 50;\n let mx = mouseX - 50;\n let my = mouseY - 50;\n\n // Draw the line.\n line(pmx, pmy, mx, my);\n}\n
\nUna variable de tipo Number
que sigue la posición horizontal anterior\ndel ratón\nen el navegador.
pwinMouseX
sigue la posición del ratón relativa a la esquina superior izquierda\nde la ventana del navegador. Su valor es\nwinMouseX desde el fotograma anterior. Por ejemplo, si el ratón estaba a 50 píxeles desde el borde izquierdo del navegador durante el fotograma anterior, entonces pwinMouseX
tomará el valor 50.
En un dispositivo táctil, pwinMouseX
guardará la coordenada x del punto de toque más reciente. pwinMouseX
se reiniciará al valor actual de winMouseX al inicio de cada evento táctil.
Nota: Utilice pmouseX para rastrear la posición anterior del ratón en relación con el lienzo.
\n"],"line":[0,551],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(10);\n\n describe('A gray square. A white circle at its center grows larger when the mouse moves horizontally.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the circle's diameter.\n let d = winMouseX - pwinMouseX;\n\n // Draw the circle.\n circle(50, 50, d);\n}\n
\n\nfunction setup() {\n // Create the canvas and set its position.\n let cnv = createCanvas(100, 100);\n cnv.position(20, 20);\n\n describe('A gray square with a number at its center. The number changes as the user moves the mouse vertically.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display pwinMouseX.\n text(pwinMouseX, 50, 50);\n}\n
\nUna variable de tipo Number
que sigue la posición vertical anterior\ndel mouse en el navegador.
pwinMouseY
se encarga de rastrear la posición del mouse relativa al\nborde superior izquierdo de la ventana del navegador. Su valor será\nwinMouseY del frame anterior. Por ejemplo, si el mouse estaba a 50 píxeles desde el borde superior del navegador durante el frame anterior, entonces pwinMouseY
será 50.
En un dispositivo táctil, pwinMouseY
almacenará la coordenada y del último punto de contacto con el dispositivo. pwinMouseY
se resetea al valor actual de\nwinMouseY al inicio de cada evento de toque.
Nota: Utiliza pmouseY para rastrear la posición y del mouse dentro del canvas.
\n"],"line":[0,622],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(10);\n\n describe('A gray square. A white circle at its center grows larger when the mouse moves vertically.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the circle's diameter.\n let d = winMouseY - pwinMouseY;\n\n // Draw the circle.\n circle(50, 50, d);\n}\n
\n\nfunction setup() {\n // Create the canvas and set its position.\n let cnv = createCanvas(100, 100);\n cnv.position(20, 20);\n\n describe('A gray square with a number at its center. The number changes as the user moves the mouse vertically.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display pwinMouseY.\n text(pwinMouseY, 50, 50);\n}\n
\nBloquea el puntero del ratón en su posición actual y lo hace invisible.
\nrequestPointerLock()
permite que el ratón se mueva para siempre sin salir de la\npantalla. Llamar a requestPointerLock()
bloquea los valores de\nmouseX, mouseY,\npmouseX, y pmouseY.\nmovedX y movedY\nse continúan actualizando y pueden ser utilizados para obtener la distancia que el ratón se movió desde la última vez que se dibujó un fotograma. Llamar a exitPointerLock() retoma la actualización de las\nvariables de sistema del ratón.
Nota: La mayoría de los navegadores requieren una entrada, como un clic, antes de llamar a requestPointerLock()
. Se recomienda llamar a requestPointerLock()
en una función de evento como doubleClicked().
\nlet score = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with the text \"Score: X\" at its center. The score increases when the user moves the mouse upward. It decreases when the user moves the mouse downward.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Update the score.\n score -= movedY;\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the score.\n text(`Score: ${score}`, 50, 50);\n}\n\n// Lock the pointer when the user double-clicks.\nfunction doubleClicked() {\n requestPointerLock();\n}\n
\nUna variable de sistema Number
que sigue la posición horizontal del ratón\ndentro del navegador.
winMouseX
mantiene un registro de la posición del ratón relativa a la\nesquina superior izquierda de la ventana del navegador. Por ejemplo, si el ratón está a 50 pixeles del borde izquierdo del navegador, entonces winMouseX
será 50.
En un dispositivo táctil, winMouseX
mantendrá la coordenada x del punto de contacto más reciente.
Nota: Utilice mouseX para seguir la posición horizontal del ratón relativa al lienzo.
\n"],"line":[0,469],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse.\");\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the mouse's coordinates within the browser window.\n text(`x: ${winMouseX} y: ${winMouseY}`, 50, 50);\n}\n
\nUna variable de tipo Number
que sigue la posición vertical del\nratón dentro del\nnavegador.
winMouseY
se encarga de rastrear la posición del ratón relativa a la\nesquina superior izquierda de la ventana del navegador. Por ejemplo, si el ratón está a 50 píxeles\ndel borde superior de la ventana del navegador, entonces winMouseY
tomará el valor 50.
En un dispositivo táctil, winMouseY
guardará la coordenada y del\npunto de toque más reciente.
Nota: Utilice mouseY para rastrear la\nposición del ratón en\nrelación con el canvas.
\n"],"line":[0,510],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse.\");\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the mouse's coordinates within the browser window.\n text(`x: ${winMouseX} y: ${winMouseY}`, 50, 50);\n}\n
\nUna función que se ejecuta una vez por cada toque en la pantalla que termina.
\nDeclarar una función llamada touchEnded()
establece un bloque de código para ejecutarse automáticamente cuando el usuario deja de tocar una pantalla táctil:
\nfunction touchEnded() {\n // Code to run.\n}\n
\n\nLa matriz touches se actualizará con los puntos táctiles más recientes cuando touchEnded()
es llamada por p5.js:
\nfunction touchEnded() {\n // Paint over the background.\n background(200);\n\n // Mark each remaining touch point when the user stops\n // a touch.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n
\nEl parámetro, event, es opcional. touchEnded()
se le pasará un objeto TouchEvent con propiedades que describen el evento táctil:
\nfunction touchEnded(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n\nEn dispositivos táctiles, mouseReleased()\nse ejecutará cuando el usuario deja de tocar su pantalla si touchEnded()
no está declarado. Si\ntouchEnded()
está declarado, entonces touchEnded()
se ejecutará cuando el usuario deja un toque y mouseReleased() no se ejecutará.
Nota: touchStarted(),\ntouchEnded()
, y touchMoved() estan todos\nrelacionados. touchStarted() se ejecuta inmediatamente cuando el usuario toca una pantalla táctil. touchEnded()
se ejecuta inmediatamente cuando el usuario deja un toque. touchMoved() se ejecuta repetidamente mientras el usuario mueve cualquier punto táctil.
Argumento opcional TouchEvent
.
\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square switches color between black and white each time the user stops touching the screen.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle colors when a touch ends.\nfunction touchEnded() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nlet bgColor = 50;\nlet fillColor = 255;\nlet borderWidth = 0.5;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with the number 0 at the top-center. The number tracks the number of places the user is touching the screen. Circles appear at each touch point and change style in response to events.'\n );\n}\n\nfunction draw() {\n background(bgColor);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n fill(0);\n noStroke();\n\n // Display the number of touch points.\n text(touches.length, 50, 20);\n\n // Style the touch points.\n fill(fillColor);\n stroke(0);\n strokeWeight(borderWidth);\n\n // Display the touch points as circles.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n\n// Set the background color to a random grayscale value.\nfunction touchStarted() {\n bgColor = random(80, 255);\n}\n\n// Set the fill color to a random grayscale value.\nfunction touchEnded() {\n fillColor = random(0, 255);\n}\n\n// Set the stroke weight.\nfunction touchMoved() {\n // Increment the border width.\n borderWidth += 0.1;\n\n // Reset the border width once it's too thick.\n if (borderWidth > 20) {\n borderWidth = 0.5;\n }\n}\n
\nUna función que se ejecuta cada vez que el usuario toca la pantalla y se mueve.
\nDeclarar una función llamada touchMoved()
establece un bloque de código para ejecutarse automáticamente cuando el usuario toca un dispositivo táctil y se mueve:
\nfunction touchMoved() {\n // Code to run.\n}\n
\n\nLa matriz touches se actualizará con los puntos táctiles más recientes cuando touchMoved()
es llamado por p5.js:
\nfunction touchMoved() {\n // Paint over the background.\n background(200);\n\n // Mark each touch point while the user moves.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n
\nEl parámetro, event, es opcional. touchMoved()
se le pasará un objeto TouchEvent con propiedades que describen el evento táctil:
\nfunction touchMoved(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n\nEn dispositivos táctiles, mouseDragged() se ejecutará cuando el usuario mueve su puntero sobre la pantalla si touchMoved()
no está declarado. Si touchMoved()
está declarado, entonces touchMoved()
se ejecutará cuando el usuario mueve sus puntos táctiles y mouseDragged() no se ejecutará.
Tenga en cuenta que touchStarted(), touchEnded() y touchMoved()
estan todos relacionados. touchStarted() se ejecuta cuando el usuario toca un dispositivo táctil, touchEnded() se ejecuta cuando el usuario termina de tocar y touchMoved()
se ejecuta repetidamente mientras el usuario mueve cualquier punto táctil.
Argumento opcional TouchEvent.
\n"],"type":[0,"TouchEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square becomes lighter when the user touches the screen and moves.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\nfunction touchMoved() {\n // Update the grayscale value.\n value += 5;\n\n // Reset the grayscale value.\n if (value > 255) {\n value = 0;\n }\n}\n
\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nlet bgColor = 50;\nlet fillColor = 255;\nlet borderWidth = 0.5;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with the number 0 at the top-center. The number tracks the number of places the user is touching the screen. Circles appear at each touch point and change style in response to events.'\n );\n}\n\nfunction draw() {\n background(bgColor);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n fill(0);\n noStroke();\n\n // Display the number of touch points.\n text(touches.length, 50, 20);\n\n // Style the touch points.\n fill(fillColor);\n stroke(0);\n strokeWeight(borderWidth);\n\n // Display the touch points as circles.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n\n// Set the background color to a random grayscale value.\nfunction touchStarted() {\n bgColor = random(80, 255);\n}\n\n// Set the fill color to a random grayscale value.\nfunction touchEnded() {\n fillColor = random(0, 255);\n}\n\n// Set the stroke weight.\nfunction touchMoved() {\n // Increment the border width.\n borderWidth += 0.1;\n\n // Reset the border width once it's too thick.\n if (borderWidth > 20) {\n borderWidth = 0.5;\n }\n}\n
\nUna función que se ejecuta una vez por cada vez que el usuario toca la pantalla.
\nDeclarar una función llamada touchStarted()
establece un bloque de código para ejecutarse\nautomáticamente cada vez que el usuario comienza a tocar un dispositivo táctil:
\nfunction touchStarted() {\n // Code to run.\n}\n
\n\nLa matriz touches se actualizará con los puntos táctiles más\nrecientes cuando touchStarted()
es llamado por p5.js:
\nfunction touchStarted() {\n // Paint over the background.\n background(200);\n\n // Mark each touch point once with a circle.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n
\nEl parámetro, event, es opcional. touchStarted()
se le pasará a un objeto TouchEvent\ncon propiedades que describen el evento táctil:
\nfunction touchStarted(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n\nEn dispositivos táctiles, mousePressed() se ejecutará cuando un usuario comienza a\ntocar la pantalla si touchStarted()
no está declarado. Si touchStarted()
está declarado, entonces touchStarted()
se ejecutará cuando un usuario comienza a tocar un dispositivo táctil y mousePressed() no se ejecutará.
Nota: touchStarted()
, touchEnded() y\ntouchMoved() estan todos relacionados.\ntouchStarted()
se ejecuta inmediatamente cuando el usuario comienza a tocar un dispositivo táctil.\ntouchEnded() se ejecuta inmediatamente cuando el usuario termina un\ntoque. touchMoved() se ejecuta repetidamente mientras el\nusuario mueve cualquier punto táctil.
Argumento opcional TouchEvent
.
\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square switches color between black and white each time the user touches the screen.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle colors with each touch.\nfunction touchStarted() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nlet bgColor = 50;\nlet fillColor = 255;\nlet borderWidth = 0.5;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with the number 0 at the top-center. The number tracks the number of places the user is touching the screen. Circles appear at each touch point and change style in response to events.'\n );\n}\n\nfunction draw() {\n background(bgColor);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n fill(0);\n noStroke();\n\n // Display the number of touch points.\n text(touches.length, 50, 20);\n\n // Style the touch points.\n fill(fillColor);\n stroke(0);\n strokeWeight(borderWidth);\n\n // Display the touch points as circles.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n\n// Set the background color to a random grayscale value.\nfunction touchStarted() {\n bgColor = random(80, 255);\n}\n\n// Set the fill color to a random grayscale value.\nfunction touchEnded() {\n fillColor = random(0, 255);\n}\n\n// Set the stroke weight.\nfunction touchMoved() {\n // Increment the border width.\n borderWidth += 0.1;\n\n // Reset the border width once it's too thick.\n if (borderWidth > 20) {\n borderWidth = 0.5;\n }\n}\n
\nUn Array
de todos los puntos táctiles actuales en un dispositivo táctil.
La matriz touches
está vacía de forma predeterminada. Cuando el usuario toca su pantalla, se crea y agrega un nuevo punto táctil a la matriz. Los puntos táctiles son Objets
con las siguientes propiedades:
\n// Iterate over the touches array.\nfor (let touch of touches) {\n // x-coordinate relative to the top-left\n // corner of the canvas.\n console.log(touch.x);\n\n // y-coordinate relative to the top-left\n // corner of the canvas.\n console.log(touch.y);
\n // x-coordinate relative to the top-left\n // corner of the browser.\n console.log(touch.winX);
\n // y-coordinate relative to the top-left\n // corner of the browser.\n console.log(touch.winY);
\n // ID number\n console.log(touch.id);\n}\n
\n"],"line":[0,10],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. White circles appear where the user touches the square.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw a circle at each touch point.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n
\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. Labels appear where the user touches the square, displaying the coordinates.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw a label above each touch point.\n for (let touch of touches) {\n text(`${touch.x}, ${touch.y}`, touch.x, touch.y - 40);\n }\n}\n
\nLlama a una función cuando el elemento cambia.
\nLlamar a myElement.changed(false)
deshabilita la función.
función para llamar cuando cambia el elemento.\n false
deshabilita la función.
\n let dropdown;\n\n function setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a dropdown menu and add a few color options.\n dropdown = createSelect();\n dropdown.position(0, 0);\n dropdown.option('red');\n dropdown.option('green');\n dropdown.option('blue');\n\n // Call paintBackground() when the color option changes.\n dropdown.changed(paintBackground);\n\n describe('A gray square with a dropdown menu at the top. The square changes color when an option is selected.');\n }\n\n // Paint the background with the selected color.\n function paintBackground() {\n let c = dropdown.value();\n background(c);\n }\n
\n \n let checkbox;\n\n function setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a checkbox and place it beneath the canvas.\n checkbox = createCheckbox(' circle');\n checkbox.position(0, 100);\n\n // Call repaint() when the checkbox changes.\n checkbox.changed(repaint);\n\n describe('A gray square with a checkbox underneath it that says \"circle\". A white circle appears when the box is checked and disappears otherwise.');\n }\n\n // Paint the background gray and determine whether to draw a circle.\n function repaint() {\n background(200);\n if (checkbox.checked() === true) {\n circle(50, 50, 30);\n }\n }\n
\n Crea un elemento que enlaza a otra página web.
El primer parámetro, href
, es una cadena que establece la URL de la página \nenlazada.
El segundo parámetro, html
, es una cadena que establece el HTML interno del \nenlace. Es común usar texto, imágenes o botones como enlaces.
El tercer parámetro, target
, es opcional. Es una cadena que indica al \nnavegador web dónde abrir el enlace. Por defecto, los enlaces se abren en la pestaña \nactual del navegador. Pasar '_blank'
hará que el enlace se abra en una nueva pestaña \ndel navegador. MDN describe algunas \notras opciones.
URL de la página enlazada.
\n"],"type":[0,"String"]}],[0,{"name":[0,"html"],"description":[0,"HTML interno del elemento de enlace para mostrar.
\n"],"type":[0,"String"]}],[0,{"name":[0,"target"],"description":[0,"destino donde debería abrirse el \n nuevo enlace, ya sea '_blank'
, '_self'
, '_parent'
o '_top'
.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an anchor element that links to p5js.org.\n let a = createA('https://p5js.org/', 'p5*js');\n a.position(25, 35);\n\n describe('The text \"p5*js\" written at the center of a gray square.');\n}\n
\n\nfunction setup() {\n background(200);\n\n // Create an anchor tag that links to p5js.org.\n // Open the link in a new tab.\n let a = createA('https://p5js.org/', 'p5*js', '_blank');\n a.position(25, 35);\n\n describe('The text \"p5*js\" written at the center of a gray square.');\n}\n
\nCrea un elemento oculto para reproducción de audio simple.
createAudio()
devuelve un nuevo objeto\np5.MediaElement.
El primer parámetro, src
, es la ruta del video. Si se pasa una sola cadena, como \nen '/assets/video.mp4'
, se carga un solo video. Se puede usar un arreglo\nde cadenas para cargar el mismo video en diferentes formatos. Por \nejemplo, ['/assets/video.mp4', '/assets/video.ogv', '/assets/video.webm']
.\nEsto es útil para asegurar que el video pueda reproducirse en diferentes\nnavegadores con diferentes capacidades. Consulta\nMDN\npara obtener más información sobre los formatos admitidos.
El segundo parámetro, callback
, es opcional. Es una función para llamar una vez que\nel audio está listo para reproducirse.
ruta de un archivo de audio, o un arreglo de rutas\n para admitir diferentes navegadores.
\n"],"type":[0,"String|String[]"],"optional":[0,true]}],[0,{"name":[0,"callback"],"description":[0,"función para llamar una vez que el audio esté listo para reproducirse.
\n"],"type":[0,"Function"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"nuevo objeto p5.MediaElement."],"type":[0,"p5.MediaElement"]}],"example":[1,[[0,"\n\nfunction setup() {\n noCanvas();\n\n // Load the audio.\n let beat = createAudio('/assets/beat.mp3');\n\n // Show the default audio controls.\n beat.showControls();\n\n describe('An audio beat plays when the user double-clicks the square.');\n}\n
\nCrea un elemento .
El primer parámetro, label
, es una cadena que establece la etiqueta mostrada en \nel botón.
El segundo parámetro, value
, es opcional. Es una cadena que establece el \nvalor del botón. Consulta la documentación de \nMDN\npara más detalles.
etiqueta mostrada en el botón.
\n"],"type":[0,"String"]}],[0,{"name":[0,"value"],"description":[0,"valor del botón.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"nuevo objeto p5.Element."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a button and place it beneath the canvas.\n let button = createButton('click me');\n button.position(0, 100);\n\n // Call repaint() when the button is pressed.\n button.mousePressed(repaint);\n\n describe('A gray square with a button that says \"click me\" beneath it. The square changes color when the button is clicked.');\n}\n\n// Change the background color.\nfunction repaint() {\n let g = random(255);\n background(g);\n}\n
\n\nlet button;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a button and set its value to 0.\n // Place the button beneath the canvas.\n button = createButton('click me', 'red');\n button.position(0, 100);\n\n // Call randomColor() when the button is pressed.\n button.mousePressed(randomColor);\n\n describe('A red square with a button that says \"click me\" beneath it. The square changes color when the button is clicked.');\n}\n\nfunction draw() {\n // Use the button's value to set the background color.\n let c = button.value();\n background(c);\n}\n\n// Set the button's value to a random color.\nfunction randomColor() {\n let c = random(['red', 'green', 'blue', 'yellow']);\n button.value(c);\n}\n
\nCrea un elemento que \"captura\" el flujo de audio/video desde la \ncámara web y el micrófono.
createCapture()
devuelve un nuevo objeto \np5.MediaElement. Los videos se muestran de forma \npredeterminada. Se pueden ocultar llamando a capture.hide()
y dibujar en el \nlienzo usando image().
El primer parámetro, type
, es opcional. Establece el tipo de captura a \nutilizar. Por defecto, createCapture()
captura tanto audio como video. Si se pasa VIDEO
, \ncomo en createCapture(VIDEO)
, se capturará solo video. \nSi se pasa AUDIO
, como en createCapture(AUDIO)
, se capturará solo \naudio. También se puede pasar un objeto de restricciones para personalizar el flujo. \nConsulta la \ndocumentación del W3C para ver las propiedades posibles. Diferentes navegadores admiten diferentes \npropiedades.
La propiedad 'flipped' es opcional y puede establecerse en {flipped:true}
\npara reflejar la salida del video. Si es verdadero, significa que el video se reflejará \no volteará y si no se menciona nada, por defecto será false
.
El segundo parámetro, callback
, es opcional. Es una función que se llama una vez \nque la captura está lista para usarse. La función de devolución de llamada debe tener un \nparámetro, stream
, que es un objeto \nMediaStream.
Nota: createCapture()
solo funciona al ejecutar un sketch localmente o usando HTTPS. Obtén más información \naquí \ny aquí.
tipo de captura, ya sea AUDIO o VIDEO,\n o un objeto de restricciones. Por defecto se \n capturan ambos flujos de audio y video.
\n"],"type":[0,"String|Constant|Object"],"optional":[0,true]}],[0,{"name":[0,"flipped"],"description":[0,"voltea el video capturado y refleja la salida con {flipped:true}
. Por\n defecto es false.
función para llamar una vez que el flujo\n se ha cargado.
\n"],"type":[0,"Function"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"nuevo objeto p5.MediaElement."],"type":[0,"p5.MediaElement"]}],"example":[1,[[0,"\n\nfunction setup() {\n noCanvas();\n\n // Create the video capture.\n createCapture(VIDEO);\n\n describe('A video stream from the webcam.');\n}\n
\n\nlet capture;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create the video capture and hide the element.\n capture = createCapture(VIDEO);\n capture.hide();\n\n describe('A video stream from the webcam with inverted colors.');\n}\n\nfunction draw() {\n // Draw the video capture within the canvas.\n image(capture, 0, 0, width, width * capture.height / capture.width);\n\n // Invert the colors in the stream.\n filter(INVERT);\n}\n
\n\nlet capture;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create the video capture with mirrored output.\n capture = createCapture(VIDEO,{ flipped:true });\n capture.size(100,100);\n\n describe('A video stream from the webcam with flipped or mirrored output.');\n}\n\n
\n\nfunction setup() {\n createCanvas(480, 120);\n\n // Create a constraints object.\n let constraints = {\n video: {\n mandatory: {\n minWidth: 1280,\n minHeight: 720\n },\n optional: [{ maxFrameRate: 10 }]\n },\n audio: false\n };\n\n // Create the video capture.\n createCapture(constraints);\n\n describe('A video stream from the webcam.');\n}\n
\nCrea un elemento de casilla de verificación .
Las casillas de verificación extienden la clase p5.Element con un método \nchecked()
. Llamar a myBox.checked()
devuelve true
si la casilla está \nmarcada y false
si no lo está.
El primer parámetro, label
, es opcional. Es una cadena que establece la etiqueta \na mostrar junto a la casilla de verificación.
El segundo parámetro, value
, también es opcional. Es un booleano que establece el \nvalor de la casilla de verificación.
etiqueta mostrada después de la casilla de verificación.
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"value"],"description":[0,"valor de la casilla de verificación. Marcado es true
y desmarcado es false
.
\nlet checkbox;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a checkbox and place it beneath the canvas.\n checkbox = createCheckbox();\n checkbox.position(0, 100);\n\n describe('A black square with a checkbox beneath it. The square turns white when the box is checked.');\n}\n\nfunction draw() {\n // Use the checkbox to set the background color.\n if (checkbox.checked()) {\n background(255);\n } else {\n background(0);\n }\n}\n
\n\nlet checkbox;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a checkbox and place it beneath the canvas.\n // Label the checkbox \"white\".\n checkbox = createCheckbox(' white');\n checkbox.position(0, 100);\n\n describe('A black square with a checkbox labeled \"white\" beneath it. The square turns white when the box is checked.');\n}\n\nfunction draw() {\n // Use the checkbox to set the background color.\n if (checkbox.checked()) {\n background(255);\n } else {\n background(0);\n }\n}\n
\n\nlet checkbox;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a checkbox and place it beneath the canvas.\n // Label the checkbox \"white\" and set its value to true.\n checkbox = createCheckbox(' white', true);\n checkbox.position(0, 100);\n\n describe('A white square with a checkbox labeled \"white\" beneath it. The square turns black when the box is unchecked.');\n}\n\nfunction draw() {\n // Use the checkbox to set the background color.\n if (checkbox.checked()) {\n background(255);\n } else {\n background(0);\n }\n}\n
\nCrea un elemento de selector de color.
\nEl parámetro, value
, es opcional. Si se pasa una cadena de color o\nun objeto p5.Color, se establecerá el color \npredeterminado.
Los selectores de color extienden la clase p5.Element con un par de \nmétodos útiles para gestionar colores:
\nmySelector.value()
devuelve el color actual como una cadena hexadecimal en el formato '#rrggbb'
.mySelector.color()
devuelve el color actual como un objeto p5.Color.color predeterminado como una cadena de color CSS.
\n"],"type":[0,"String|p5.Color"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"nuevo objeto p5.Element."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\nlet myPicker;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a color picker and set its position.\n myPicker = createColorPicker('deeppink');\n myPicker.position(0, 100);\n\n describe('A pink square with a color picker beneath it. The square changes color when the user picks a new color.');\n}\n\nfunction draw() {\n // Use the color picker to paint the background.\n let c = myPicker.color();\n background(c);\n}\n
\n\nlet myPicker;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a color picker and set its position.\n myPicker = createColorPicker('deeppink');\n myPicker.position(0, 100);\n\n describe('A number with the format \"#rrggbb\" is displayed on a pink canvas. The background color and number change when the user picks a new color.');\n}\n\nfunction draw() {\n // Use the color picker to paint the background.\n let c = myPicker.value();\n background(c);\n\n // Display the current color as a hex string.\n text(c, 25, 55);\n}\n
\nCrea un elemento.
Los elementos se usan comúnmente como contenedores para\notros elementos.
El parámetro html
es opcional. Acepta una cadena (string) que establece el\nHTML interno del nuevo .
HTML interno para el nuevo elemento <div></div>
.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a div element and set its position.\n let div = createDiv('p5*js');\n div.position(25, 35);\n\n describe('A gray square with the text \"p5*js\" written in its center.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an h3 element within the div.\n let div = createDiv('p5*js
');\n div.position(20, 5);\n\n describe('A gray square with the text \"p5*js\" written in its center.');\n}\n
\nCrea un nuevo objeto p5.Element.
\nEl primer parámetro, tag
, es una cadena que representa una etiqueta HTML, como 'h5'
.
El segundo parámetro, content
, es opcional. Es una cadena que establece el \ncontenido HTML que se insertará en el nuevo elemento. Los nuevos elementos no tienen contenido \npor defecto.
etiqueta para el nuevo elemento.
\n"],"type":[0,"String"]}],[0,{"name":[0,"content"],"description":[0,"contenido HTML para insertar en el elemento.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"nuevo objeto p5.Element."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an h5 element with nothing in it.\n createElement('h5');\n\n describe('A gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an h5 element with the content \"p5*js\".\n let h5 = createElement('h5', 'p5*js');\n\n // Set the element's style and position.\n h5.style('color', 'deeppink');\n h5.position(30, 15);\n\n describe('The text \"p5*js\" written in pink in the middle of a gray square.');\n}\n
\nCrea un elemento de tipo
'file'
.
createFileInput()
permite a los usuarios seleccionar archivos locales para usar en un sketch.\nDevuelve un objeto p5.File.
El primer parámetro, callback
, es una función que se llama cuando el archivo\nse carga. La función de devolución de llamada debe tener un parámetro, file
, que es un\nobjeto p5.File.
El segundo parámetro, multiple
, es opcional. Es un valor booleano que\npermite cargar varios archivos si se establece en true
. Si true
, callback
\nse llamará una vez por archivo.
función que se llama una vez que el archivo se carga.
\n"],"type":[0,"Function"]}],[0,{"name":[0,"multiple"],"description":[0,"permite seleccionar varios archivos.
\n"],"type":[0,"Boolean"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"nuevo objeto p5.File."],"type":[0,"p5.File"]}],"example":[1,[[0,"\n\n// Use the file input to select an image to\n// load and display.\nlet input;\nlet img;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a file input and place it beneath\n // the canvas.\n input = createFileInput(handleImage);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user selects an image file to load, it is displayed on the square.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw the image if loaded.\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\n// Create an image if the file is an image.\nfunction handleImage(file) {\n if (file.type === 'image') {\n img = createImg(file.data, '');\n img.hide();\n } else {\n img = null;\n }\n}\n
\n\n// Use the file input to select multiple images\n// to load and display.\nlet input;\nlet images = [];\n\nfunction setup() {\n // Create a file input and place it beneath\n // the canvas. Allow it to load multiple files.\n input = createFileInput(handleImage, true);\n input.position(0, 100);\n}\n\nfunction draw() {\n background(200);\n\n // Draw the images if loaded. Each image\n // is drawn 20 pixels lower than the\n // previous image.\n for (let i = 0; i < images.length; i += 1) {\n // Calculate the y-coordinate.\n let y = i * 20;\n\n // Draw the image.\n image(img, 0, y, 100, 100);\n }\n\n describe('A gray square with a file input beneath it. If the user selects multiple image files to load, they are displayed on the square.');\n}\n\n// Create an image if the file is an image,\n// then add it to the images array.\nfunction handleImage(file) {\n if (file.type === 'image') {\n let img = createImg(file.data, '');\n img.hide();\n images.push(img);\n }\n}\n
\nCrea un elemento
que puede aparecer fuera del lienzo.
El primer parámetro, src
, es una cadena con la ruta al archivo de imagen.\nsrc
debe ser una ruta relativa, como en '/assets/image.png'
, o una URL, como \nen 'https://example.com/image.png'
.
El segundo parámetro, alt
, es una cadena con el \n\n texto alternativo \npara la imagen. Se puede usar una cadena vacía ''
para imágenes que no se muestran.
El tercer parámetro, crossOrigin
, es opcional. Es una cadena que establece la \npropiedad crossOrigin \nde la imagen. Usa 'anonymous'
o 'use-credentials'
para recuperar la imagen \ncon acceso de origen cruzado.
El cuarto parámetro, callback
, también es opcional. Establece una función para \nllamar después de que se cargue la imagen. La nueva imagen se pasa a la función de devolución de llamada\ncomo un objeto p5.Element.
ruta relativa o URL de la imagen.
\n"],"type":[0,"String"]}],[0,{"name":[0,"alt"],"description":[0,"texto alternativo para la imagen.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"src"],"description":[0,""],"type":[0,"String"]}],[0,{"name":[0,"alt"],"description":[0,""],"type":[0,"String"]}],[0,{"name":[0,"crossOrigin"],"description":[0,"propiedad crossOrigin a utilizar para recuperar la imagen.
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"successCallback"],"description":[0,"función a llamar una vez que se cargue la imagen. La nueva imagen se pasará \n a la función como un objeto p5.Element.
\n"],"type":[0,"Function"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"nuevo objeto p5.Element."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n let img = createImg(\n 'https://p5js.org/assets/img/asterisk-01.png',\n 'The p5.js magenta asterisk.'\n );\n img.position(0, -10);\n\n describe('A gray square with a magenta asterisk in its center.');\n}\n
\nCrea un elemento de entrada de texto .
Llama a myInput.size()
para establecer la longitud del cuadro de texto.
El primer parámetro, value
, es opcional. Es una cadena que establece el\nvalor predeterminado de la entrada. La entrada está en blanco por defecto.
El segundo parámetro, type
, también es opcional. Es una cadena que\nespecifica el tipo de texto que se está ingresando. Consulta MDN para obtener una \nlista completa de opciones.\nEl valor predeterminado es 'text'
.
valor predeterminado del cuadro de entrada. Por defecto es una cadena vacía ''
.
tipo de entrada. Por defecto es 'text'
.
\nlet myInput;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create an input element and place it\n // beneath the canvas.\n myInput = createInput();\n myInput.position(0, 100);\n\n describe('A gray square with a text box beneath it. The text in the square changes when the user types something new in the input bar.');\n}\n\nfunction draw() {\n background(200);\n\n // Use the input to display a message.\n let msg = myInput.value();\n text(msg, 25, 55);\n}\n
\n\nlet myInput;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create an input element and place it\n // beneath the canvas. Set its default\n // text to \"hello!\".\n myInput = createInput('hello!');\n myInput.position(0, 100);\n\n describe('The text \"hello!\" written at the center of a gray square. A text box beneath the square also says \"hello!\". The text in the square changes when the user types something new in the input bar.');\n}\n\nfunction draw() {\n background(200);\n\n // Use the input to display a message.\n let msg = myInput.value();\n text(msg, 25, 55);\n}\n
\nCrea un elemento .
Los elementos se usan comúnmente para textos tan largos como un párrafo.
El parámetro html
es opcional. Acepta una cadena que establece el \nHTML interno del nuevo .
HTML interno para el nuevo elemento <p></p>
.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element and set its position.\n let p = createP('Tell me a story.');\n p.position(5, 0);\n\n describe('A gray square displaying the text \"Tell me a story.\" written in black.');\n}\n
\nCrea un elemento de botón de radio.
\nEl parámetro es opcional. Si se pasa una cadena, como en\nlet myRadio = createSelect('food')
, entonces cada opción de radio\ntendrá \"food\"
como su parámetro name
: .\nSi se pasa un elemento existente
o
,\ncomo en
let myRadio = createSelect(container)
, este se\nconvertirá en el elemento padre del botón de radio.
Los botones de radio extienden la clase p5.Element con algunos\nmétodos útiles para gestionar las opciones:
\nmyRadio.option(value, [label])
agrega una opción al menú. El primer parámetro, value
, es una cadena que establece el valor y la etiqueta de la opción. El segundo parámetro, label
, es opcional. Si se proporciona, establece la etiqueta que se muestra para el value
. Si una opción con value
ya existe, su etiqueta se cambia y se devuelve su valor.myRadio.value()
devuelve el valor de la opción actualmente seleccionada.myRadio.selected()
devuelve la opción actualmente seleccionada.myRadio.selected(valor)
selecciona la opción dada y la devuelve como un HTMLInputElement
.myRadio.disable(shouldDisable)
habilita el botón de radio completo si se pasa true
y lo deshabilita si se pasa false
.Elemento HTML contenedor, ya sea un <div></div>
\no un <span></span>
.
parámetro de nombre asignado a cada elemento <input></input>
element.
\nlet myRadio;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a radio button element and place it\n // in the top-left corner.\n myRadio = createRadio();\n myRadio.position(0, 0);\n myRadio.size(60);\n\n // Add a few color options.\n myRadio.option('red');\n myRadio.option('yellow');\n myRadio.option('blue');\n\n // Choose a default option.\n myRadio.selected('yellow');\n\n describe('A yellow square with three color options listed, \"red\", \"yellow\", and \"blue\". The square changes color when the user selects a new option.');\n}\n\nfunction draw() {\n // Set the background color using the radio button.\n let g = myRadio.value();\n background(g);\n}\n
\n\nlet myRadio;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a radio button element and place it\n // in the top-left corner.\n myRadio = createRadio();\n myRadio.position(0, 0);\n myRadio.size(50);\n\n // Add a few color options.\n // Color values are labeled with\n // emotions they evoke.\n myRadio.option('red', 'love');\n myRadio.option('yellow', 'joy');\n myRadio.option('blue', 'trust');\n\n // Choose a default option.\n myRadio.selected('yellow');\n\n describe('A yellow square with three options listed, \"love\", \"joy\", and \"trust\". The square changes color when the user selects a new option.');\n}\n\nfunction draw() {\n // Set the background color using the radio button.\n let c = myRadio.value();\n background(c);\n}\n
\n\nlet myRadio;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a radio button element and place it\n // in the top-left corner.\n myRadio = createRadio();\n myRadio.position(0, 0);\n myRadio.size(50);\n\n // Add a few color options.\n myRadio.option('red');\n myRadio.option('yellow');\n myRadio.option('blue');\n\n // Choose a default option.\n myRadio.selected('yellow');\n\n // Create a button and place it beneath the canvas.\n let btn = createButton('disable');\n btn.position(0, 100);\n\n // Call disableRadio() when btn is pressed.\n btn.mousePressed(disableRadio);\n\n describe('A yellow square with three options listed, \"red\", \"yellow\", and \"blue\". The square changes color when the user selects a new option. A \"disable\" button beneath the canvas disables the color options when pressed.');\n}\n\nfunction draw() {\n // Set the background color using the radio button.\n let c = myRadio.value();\n background(c);\n}\n\n// Disable myRadio.\nfunction disableRadio() {\n myRadio.disable(true);\n}\n
\nCrea un elemento de menú desplegable .
El parámetro es opcional. Si se pasa true
, como en\nlet mySelect = createSelect(true)
, entonces el menú desplegable admitirá\nselecciones múltiples. Si se pasa un elemento existente,\ncomo en
let mySelect = createSelect(otherSelect)
, el elemento existente se\nenvolverá en un nuevo objeto p5.Element\n.
Los menús desplegables extienden la clase p5.Element con algunos\nmétodos útiles para gestionar las opciones:
\nmySelect.option(name, [value])
agrega una opción al menú. El primer parámetro, nombre
, es una cadena que establece el nombre y valor de la opción. El segundo parámetro, valor
, es opcional. Si se proporciona, establece el valor que corresponde a la clave name
. Si ya existe una opción con el name
, su valor se cambia a value
.mySelect.value()
devuelve el valor de la opción actualmente seleccionada.mySelect.selected()
devuelve la opción actualmente seleccionada.mySelect.selected(option)
selecciona la opción dada de forma predeterminada.mySelect.disable()
marca todo el elemento del menú desplegable como deshabilitado.mySelect.disable(option)
marca una opción dada como deshabilitada.mySelect.enable()
marca todo el elemento del menú desplegable como habilitado.mySelect.enable(option)
marca una opción dada como habilitada.admite selecciones múltiples.
\n"],"type":[0,"Boolean"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"existing"],"description":[0,"elemento selecto para envolver, ya sea como un p5.Element o\n un HTMLSelectElement existente.
\n"],"type":[0,"Object"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"nuevo objeto p5.Element."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\nlet mySelect;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a dropdown and place it beneath the canvas.\n mySelect = createSelect();\n mySelect.position(0, 100);\n\n // Add color options.\n mySelect.option('red');\n mySelect.option('green');\n mySelect.option('blue');\n mySelect.option('yellow');\n\n // Set the selected option to \"red\".\n mySelect.selected('red');\n\n describe('A red square with a dropdown menu beneath it. The square changes color when a new color is selected.');\n}\n\nfunction draw() {\n // Use the selected value to paint the background.\n let c = mySelect.selected();\n background(c);\n}\n
\n\nlet mySelect;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a dropdown and place it beneath the canvas.\n mySelect = createSelect();\n mySelect.position(0, 100);\n\n // Add color options.\n mySelect.option('red');\n mySelect.option('green');\n mySelect.option('blue');\n mySelect.option('yellow');\n\n // Set the selected option to \"red\".\n mySelect.selected('red');\n\n // Disable the \"yellow\" option.\n mySelect.disable('yellow');\n\n describe('A red square with a dropdown menu beneath it. The square changes color when a new color is selected.');\n}\n\nfunction draw() {\n // Use the selected value to paint the background.\n let c = mySelect.selected();\n background(c);\n}\n
\n\nlet mySelect;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a dropdown and place it beneath the canvas.\n mySelect = createSelect();\n mySelect.position(0, 100);\n\n // Add color options with names and values.\n mySelect.option('one', 'red');\n mySelect.option('two', 'green');\n mySelect.option('three', 'blue');\n mySelect.option('four', 'yellow');\n\n // Set the selected option to \"one\".\n mySelect.selected('one');\n\n describe('A red square with a dropdown menu beneath it. The square changes color when a new color is selected.');\n}\n\nfunction draw() {\n // Use the selected value to paint the background.\n let c = mySelect.selected();\n background(c);\n}\n
\n\n// Hold CTRL to select multiple options on Windows and Linux.\n// Hold CMD to select multiple options on macOS.\nlet mySelect;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a dropdown and allow multiple selections.\n // Place it beneath the canvas.\n mySelect = createSelect(true);\n mySelect.position(0, 100);\n\n // Add color options.\n mySelect.option('red');\n mySelect.option('green');\n mySelect.option('blue');\n mySelect.option('yellow');\n\n describe('A gray square with a dropdown menu beneath it. Colorful circles appear when their color is selected.');\n}\n\nfunction draw() {\n background(200);\n\n // Use the selected value(s) to draw circles.\n let colors = mySelect.selected();\n for (let i = 0; i < colors.length; i += 1) {\n // Calculate the x-coordinate.\n let x = 10 + i * 20;\n\n // Access the color.\n let c = colors[i];\n\n // Draw the circle.\n fill(c);\n circle(x, 50, 20);\n }\n}\n
\nCrea un elemento deslizante.
Los deslizadores de rango son útiles para seleccionar rápidamente números de un rango dado.
\nLos dos primeros parámetros, min
y max
, son números que establecen el \nvalor mínimo y máximo del deslizador.
El tercer parámetro, value
, es opcional. Es un número que establece el \nvalor predeterminado del deslizador.
El cuarto parámetro, step
, también es opcional. Es un número que establece el \nespaciado entre cada valor en el rango del deslizador. Establecer step
en 0 \npermite que el deslizador se mueva suavemente desde min
hasta max
.
valor mínimo del deslizador.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"max"],"description":[0,"valor máximo del deslizador.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"value"],"description":[0,"valor predeterminado del deslizador.
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"step"],"description":[0,"tamaño para cada paso en el rango del deslizador.
\n"],"type":[0,"Number"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"nuevo objeto p5.Element."],"type":[0,"p5.Element"]}],"example":[1,[[0,"\n\nlet slider;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a slider and place it at the top of the canvas.\n slider = createSlider(0, 255);\n slider.position(10, 10);\n slider.size(80);\n\n describe('A dark gray square with a range slider at the top. The square changes color when the slider is moved.');\n}\n\nfunction draw() {\n // Use the slider as a grayscale value.\n let g = slider.value();\n background(g);\n}\n
\n\nlet slider;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a slider and place it at the top of the canvas.\n // Set its default value to 0.\n slider = createSlider(0, 255, 0);\n slider.position(10, 10);\n slider.size(80);\n\n describe('A black square with a range slider at the top. The square changes color when the slider is moved.');\n}\n\nfunction draw() {\n // Use the slider as a grayscale value.\n let g = slider.value();\n background(g);\n}\n
\n\nlet slider;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a slider and place it at the top of the canvas.\n // Set its default value to 0.\n // Set its step size to 50.\n slider = createSlider(0, 255, 0, 50);\n slider.position(10, 10);\n slider.size(80);\n\n describe('A black square with a range slider at the top. The square changes color when the slider is moved.');\n}\n\nfunction draw() {\n // Use the slider as a grayscale value.\n let g = slider.value();\n background(g);\n}\n
\n\nlet slider;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a slider and place it at the top of the canvas.\n // Set its default value to 0.\n // Set its step size to 0 so that it moves smoothly.\n slider = createSlider(0, 255, 0, 0);\n slider.position(10, 10);\n slider.size(80);\n\n describe('A black square with a range slider at the top. The square changes color when the slider is moved.');\n}\n\nfunction draw() {\n // Use the slider as a grayscale value.\n let g = slider.value();\n background(g);\n}\n
\nCrea un elemento .
Los elementos se usan comúnmente como contenedores \npara elementos en línea. Por ejemplo, un
\npuede contener parte de una oración que tiene un \nestilo diferente.
El parámetro html
es opcional. Acepta una cadena que establece el \nHTML interno del nuevo .
HTML interno para el nuevo elemento <span></span>
.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a span element and set its position.\n let span = createSpan('p5*js');\n span.position(25, 35);\n\n describe('A gray square with the text \"p5*js\" written in its center.');\n}\n
\n\nfunction setup() {\n background(200);\n\n // Create a div element as a container.\n let div = createDiv();\n\n // Place the div at the center.\n div.position(25, 35);\n\n // Create a span element.\n let s1 = createSpan('p5');\n\n // Create a second span element.\n let s2 = createSpan('*');\n\n // Set the second span's font color.\n s2.style('color', 'deeppink');\n\n // Create a third span element.\n let s3 = createSpan('js');\n\n // Add all the spans to the container div.\n s1.parent(div);\n s2.parent(div);\n s3.parent(div);\n\n describe('A gray square with the text \"p5*js\" written in black at its center. The asterisk is pink.');\n}\n
\nCrea un elemento para reproducción de audio/video simple.
createVideo()
devuelve un nuevo\nobjeto p5.MediaElement. Los vídeos se muestran por\ndefecto. Se pueden ocultar llamando a video.hide()
y dibujar en el\nlienzo usando image().
El primer parámetro, src
, es la ruta del vídeo. Si se pasa una sola cadena, \ncomo en '/assets/topsecret.mp4'
, se carga un único vídeo. Un arreglo\nde cadenas o strings se puede usar para cargar el mismo vídeo en diferentes formatos. Por\nejemplo, ['/assets/topsecret.mp4', '/assets/topsecret.ogv', '/assets/topsecret.webm']
.\nEsto es útil para asegurar que el vídeo se pueda reproducir en diferentes navegadores con\ndiferentes capacidades. Consulta\nMDN\npara obtener más información sobre los formatos admitidos.
El segundo parámetro, callback
, es opcional. Es una función que se llamará una vez\nque el vídeo esté listo para reproducirse.
ruta de un archivo de vídeo, o un arreglo de rutas para\n admitir diferentes navegadores.
\n"],"type":[0,"String|String[]"]}],[0,{"name":[0,"callback"],"description":[0,"función que se llamará una vez que el vídeo esté listo para reproducirse.
\n"],"type":[0,"Function"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"nuevo objeto p5.MediaElement."],"type":[0,"p5.MediaElement"]}],"example":[1,[[0,"\n\nfunction setup() {\n noCanvas();\n\n // Load a video and add it to the page.\n // Note: this may not work in some browsers.\n let video = createVideo('/assets/small.mp4');\n\n // Show the default video controls.\n video.showControls();\n\n describe('A video of a toy robot with playback controls beneath it.');\n}\n
\n\nfunction setup() {\n noCanvas();\n\n // Load a video and add it to the page.\n // Provide an array options for different file formats.\n let video = createVideo(\n ['/assets/small.mp4', '/assets/small.ogv', '/assets/small.webm']\n );\n\n // Show the default video controls.\n video.showControls();\n\n describe('A video of a toy robot with playback controls beneath it.');\n}\n
\n\nlet video;\n\nfunction setup() {\n noCanvas();\n\n // Load a video and add it to the page.\n // Provide an array options for different file formats.\n // Call mute() once the video loads.\n video = createVideo(\n ['/assets/small.mp4', '/assets/small.ogv', '/assets/small.webm'],\n muteVideo\n );\n\n // Show the default video controls.\n video.showControls();\n\n describe('A video of a toy robot with playback controls beneath it.');\n}\n\n// Mute the video once it loads.\nfunction muteVideo() {\n video.volume(0);\n}\n
\nLlama a una función cuando el elemento recibe entrada.
\nmyElement.input()
se usa a menudo con entradas de texto y deslizadores. Llamar a\nmyElement.input(false)
deshabilita la función.
función para llamar cuando se detecta entrada dentro\n del elemento.\n false
deshabilita la función.
\nlet slider;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a slider and place it beneath the canvas.\n slider = createSlider(0, 255, 200);\n slider.position(0, 100);\n\n // Call repaint() when the slider changes.\n slider.input(repaint);\n\n describe('A gray square with a range slider underneath it. The background changes shades of gray when the slider is moved.');\n}\n\n// Paint the background using slider's value.\nfunction repaint() {\n let g = slider.value();\n background(g);\n}\n
\n\nlet input;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an input and place it beneath the canvas.\n input = createInput('');\n input.position(0, 100);\n\n // Call repaint() when input is detected.\n input.input(repaint);\n\n describe('A gray square with a text input bar beneath it. Any text written in the input appears in the middle of the square.');\n}\n\n// Paint the background gray and display the input's value.\nfunction repaint() {\n background(200);\n let msg = input.value();\n text(msg, 5, 50);\n}\n
\nElimina todos los elementos creados por p5.js, incluidos los manejadores de eventos.
\nHay dos excepciones:\nlos elementos canvas creados por createCanvas()\ny los objetos p5.Render creados por\ncreateGraphics().
\n"],"line":[0,255],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element and place\n // it in the middle of the canvas.\n let p = createP('p5*js');\n p.position(25, 25);\n\n describe('A gray square with the text \"p5*js\" written in its center. The text disappears when the mouse is pressed.');\n}\n\n// Remove all elements when the mouse is pressed.\nfunction mousePressed() {\n removeElements();\n}\n
\n\nlet slider;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a paragraph element and place\n // it at the top of the canvas.\n let p = createP('p5*js');\n p.position(25, 25);\n\n // Create a slider element and place it\n // beneath the canvas.\n slider = createSlider(0, 255, 200);\n slider.position(0, 100);\n\n describe('A gray square with the text \"p5*js\" written in its center and a range slider beneath it. The square changes color when the slider is moved. The text and slider disappear when the square is double-clicked.');\n}\n\nfunction draw() {\n // Use the slider value to change the background color.\n let g = slider.value();\n background(g);\n}\n\n// Remove all elements when the mouse is double-clicked.\nfunction doubleClicked() {\n removeElements();\n}\n
\nBusca en la página el primer elemento que coincida con la\ncadena de selector CSS dada.
\nLa cadena de selector puede ser un ID, una clase, un nombre de etiqueta o una combinación.\nselect()
devuelve un objeto p5.Element si encuentra una \ncoincidencia y null
si no.
El segundo parámetro, container
, es opcional. Especifica un contenedor para\nbuscar dentro de él. container
puede ser una cadena de selector CSS, un\nobjeto p5.Element, o un\nHTMLElement object.
Cadena de selector CSS del elemento a buscar.
\n"],"type":[0,"String"]}],[0,{"name":[0,"container"],"description":[0,"Cadena de selector CSS, p5.Element, o\n HTMLElement to search within.
\n"],"type":[0,"String|p5.Element|HTMLElement"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"p5.Element que contiene el elemento."],"type":[0,"p5.Element|null"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n\n // Select the canvas by its tag.\n let cnv = select('canvas');\n cnv.style('border', '5px deeppink dashed');\n\n describe('A gray square with a dashed pink border.');\n}\n
\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n // Add a class attribute to the canvas.\n cnv.class('pinkborder');\n\n background(200);\n\n // Select the canvas by its class.\n cnv = select('.pinkborder');\n\n // Style its border.\n cnv.style('border', '5px deeppink dashed');\n\n describe('A gray square with a dashed pink border.');\n}\n
\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n // Set the canvas' ID.\n cnv.id('mycanvas');\n\n background(200);\n\n // Select the canvas by its ID.\n cnv = select('#mycanvas');\n\n // Style its border.\n cnv.style('border', '5px deeppink dashed');\n\n describe('A gray square with a dashed pink border.');\n}\n
\nBusca en la página todos los elementos que coinciden con la\ncadena de selector CSS dada.
\nLa cadena de selector puede ser un ID, una clase, un nombre de etiqueta o una combinación.\nselectAll()
devuelve un arreglo de objetos p5.Element\nsi encuentra alguna coincidencia y un arreglo vacío si no encuentra ninguna.
El segundo parámetro, container
, es opcional. Especifica un contenedor para\nbuscar dentro de él. container
puede ser una cadena de selector CSS, un\nobjeto p5.Element, o un\nobjeto HTMLElement.
Cadena de selector CSS del elemento a buscar.
\n"],"type":[0,"String"]}],[0,{"name":[0,"container"],"description":[0,"Cadena de selector CSS, p5.Element, or\n HTMLElement to search within.
\n"],"type":[0,"String|p5.Element|HTMLElement"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"arreglo de p5.Elements que contienen los elementos encontrados."],"type":[0,"p5.Element[]"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create three buttons.\n createButton('1');\n createButton('2');\n createButton('3');\n\n // Select the buttons by their tag.\n let buttons = selectAll('button');\n\n // Position the buttons.\n for (let i = 0; i < 3; i += 1) {\n buttons[i].position(0, i * 30);\n }\n\n describe('Three buttons stacked vertically. The buttons are labeled, \"1\", \"2\", and \"3\".');\n}\n
\n\nfunction setup() {\n // Create three buttons and position them.\n let b1 = createButton('1');\n b1.position(0, 0);\n let b2 = createButton('2');\n b2.position(0, 30);\n let b3 = createButton('3');\n b3.position(0, 60);\n\n // Add a class attribute to each button.\n b1.class('btn');\n b2.class('btn btn-pink');\n b3.class('btn');\n\n // Select the buttons by their class.\n let buttons = selectAll('.btn');\n let pinkButtons = selectAll('.btn-pink');\n\n // Style the selected buttons.\n buttons.forEach(setFont);\n pinkButtons.forEach(setColor);\n\n describe('Three buttons stacked vertically. The buttons are labeled, \"1\", \"2\", and \"3\". Buttons \"1\" and \"3\" are gray. Button \"2\" is pink.');\n}\n\n// Set a button's font to Comic Sans MS.\nfunction setFont(btn) {\n btn.style('font-family', 'Comic Sans MS');\n}\n\n// Set a button's background and font color.\nfunction setColor(btn) {\n btn.style('background', 'deeppink');\n btn.style('color', 'white');\n}\n
\nUna clase para describir un\nelemento HTML.
\nLos sketches pueden usar muchos elementos. Los elementos comunes incluyen el lienzo de dibujo,\nbotones, deslizadores, transmisiones de cámara web, etc.
\nTodos los elementos comparten los métodos de la clase p5.Element
. Se crean\ncon funciones como createCanvas() y\ncreateButton().
elemento DOM envuelto.
\n"],"type":[0,"HTMLElement"]}],[0,{"name":[0,"pInst"],"description":[0,"puntero a la instancia de p5.
\n"],"type":[0,"P5"],"optional":[0,true]}]]],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a button element and\n // place it beneath the canvas.\n let btn = createButton('change');\n btn.position(0, 100);\n\n // Call randomColor() when\n // the button is pressed.\n btn.mousePressed(randomColor);\n\n describe('A gray square with a button that says \"change\" beneath it. The square changes color when the user presses the button.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nAdjunta el elemento a un elemento padre.
\nPor ejemplo, un elemento puede usarse como un contenedor para\ncontener dos piezas de texto, un encabezado y un párrafo. El\n
es el elemento padre tanto del encabezado como del\npárrafo.
El parámetro parent
puede tener uno de tres tipos. parent
puede ser un\nstring con el ID del elemento padre, como en\nmyElement.parent('container')
. También puede ser otro objeto\np5.Element, como en\nmyElement.parent(myDiv)
. Finalmente, parent
puede ser un objeto HTMLElement
,\ncomo en myElement.parent(anotherElement)
.
Llamar a myElement.parent()
sin argumento devuelve el elemento \npadre.
Establece el ID del elemento usando un string dado.
\nLlamar a myElement.id()
sin argumentos devuelve su ID como un string o cadena.
Agrega un\natributo de clase\nal elemento usando una cadena dada.
\nLlamar a myElement.class()
sin argumentos devuelve una cadena con sus clases actuales.
Llama a una función cuando se presiona el mouse sobre el elemento.
\nLlamar a myElement.mousePressed(false)
desactiva la función.
Nota: Algunos navegadores móviles también pueden activar este evento cuando el elemento\nrecibe un toque rápido.
\n"],"path":[0,"p5.Element/mousePressed"]}],"doubleClicked":[0,{"description":[0,"Llama a una función cuando se presiona dos veces el mouse sobre el elemento.
\nLlamar a myElement.doubleClicked(false)
desactiva la función.
Llama a una función cuando la rueda del mouse se desplaza sobre el elemento.
\nLa función de devolución de llamada, fxn
, recibe un objeto event
. event
tiene\ndos propiedades numéricas, deltaY
y deltaX
. event.deltaY
es\nnegativo si la rueda del mouse gira alejándose del usuario. Es positivo si\nla rueda del mouse gira hacia el usuario. event.deltaX
es positivo si\nla rueda del mouse se mueve hacia la derecha. Es negativo si la rueda del mouse se mueve\nhacia la izquierda.
Llamar a myElement.mouseWheel(false)
desactiva la función.
Llama a una función cuando se libera el mouse sobre el elemento.
\nLlamar a myElement.mouseReleased(false)
desactiva la función.
Nota: Algunos navegadores móviles también pueden activar este evento cuando el elemento\nrecibe un toque rápido.
\n"],"path":[0,"p5.Element/mouseReleased"]}],"mouseClicked":[0,{"description":[0,"Llama a una función cuando se presiona y se libera el mouse sobre el elemento.
\nLlamar a myElement.mouseReleased(false)
desactiva la función.
Nota: Algunos navegadores móviles también pueden activar este evento cuando el elemento\nrecibe un toque rápido.
\n"],"path":[0,"p5.Element/mouseClicked"]}],"mouseMoved":[0,{"description":[0,"Llama a una función cuando el mouse se mueve sobre el elemento.
\nLlamar a myElement.mouseMoved(false)
desactiva la función.
Llama a una función cuando el mouse se mueve sobre el elemento.
\nLlamar a myElement.mouseOver(false)
desactiva la función.
Llama a una función cuando el mouse se mueve fuera del elemento.
\nLlamar a myElement.mouseOut(false)
desactiva la función.
Llama a una función cuando se toca el elemento.
\nLlamar a myElement.touchStarted(false)
desactiva la función.
Nota: Las funciones táctiles solo funcionan en dispositivos móviles.
\n"],"path":[0,"p5.Element/touchStarted"]}],"touchMoved":[0,{"description":[0,"Llama a una función cuando el usuario toca el elemento y se mueve.
\nLlamar a myElement.touchMoved(false)
desactiva la función.
Nota: Las funciones táctiles solo funcionan en dispositivos móviles.
\n"],"path":[0,"p5.Element/touchMoved"]}],"touchEnded":[0,{"description":[0,"Llama a una función cuando el usuario deja de tocar el elemento.
\nLlamar a myElement.touchMoved(false)
desactiva la función.
Nota: Las funciones táctiles solo funcionan en dispositivos móviles.
\n"],"path":[0,"p5.Element/touchEnded"]}],"dragOver":[0,{"description":[0,"Llama a una función cuando se arrastra un archivo sobre el elemento.
\nLlamar a myElement.dragOver(false)
desactiva la función.
Llama a una función cuando se arrastra un archivo fuera del elemento.
\nLlamar a myElement.dragLeave(false)
desactiva la función.
Agrega una clase al elemento.
\n"],"path":[0,"p5.Element/addClass"]}],"removeClass":[0,{"description":[0,"Elimina una clase del elemento.
\n"],"path":[0,"p5.Element/removeClass"]}],"hasClass":[0,{"description":[0,"Comprueba si una clase ya está aplicada al elemento.
\n"],"path":[0,"p5.Element/hasClass"]}],"toggleClass":[0,{"description":[0,"Alterna si se aplica una clase al elemento.
\n"],"path":[0,"p5.Element/toggleClass"]}],"child":[0,{"description":[0,"Adjunta el elemento como hijo de otro elemento.
\nmyElement.child()
acepta una cadena de ID, nodo DOM o\np5.Element. Por ejemplo,\nmyElement.child(otherElement)
. Si no se proporciona ningún argumento, se devuelve un array de\nnodos DOM hijos.
Centra el elemento vertical u horizontalmente, o ambos.
\ncenter()
centrará el elemento en relación a su padre o según\nel cuerpo de la página si el elemento no tiene padre.
Si no se pasa ningún argumento, como en myElement.center()
el elemento se alinea\ntanto vertical como horizontalmente.
Establece el HTML interno del elemento, reemplazando cualquier HTML existente.
\nEl segundo parámetro, append
, es opcional. Si se pasa true
, como en\nmyElement.html('hi', true)
, el HTML se añade en lugar de reemplazar\nel HTML existente.
Si no se pasan argumentos, como en myElement.html()
, se devuelve el HTML \ninterno del elemento.
Establece la posición del elemento.
\nLos primeros dos parámetros, x
y y
, establecen la posición del elemento relativa\na la esquina superior izquierda de la página web.
El tercer parámetro, positionType
, es opcional. Establece el\nesquema de posicionamiento del elemento.\npositionType
es una cadena que puede ser 'static'
, 'fixed'
,\n'relative'
, 'sticky'
, 'initial'
o 'inherit'
.
Si no se pasan argumentos, como en myElement.position()
, el método devuelve\nla posición del elemento en un objeto, como en { x: 0, y: 0 }
.
Aplica un estilo al elemento agregando una\ndeclaración CSS.
\nEl primer parámetro, property
, es un string. Si se pasa el nombre de una propiedad\n \nde estilo, como en myElement.style('color')
, el método devuelve\nel valor actual como un string o null
si no se ha establecido. Si se pasa una\ncadena property:style
, como en\nmyElement.style('color:deeppink')
, el método establece la propiedad de estilo property
\na value
.
El segundo parámetro, value
, es opcional. Establece el valor de la propiedad.\nvalue
puede ser un string, como en\nmyElement.style('color', 'deeppink')
, o un \nobjeto p5.Color, como en\nmyElement.style('color', myColor)
.
Agrega un\natributo\nal elemento.
\nEste método es útil para tareas avanzadas. La mayoría de los atributos más comúnmente utilizados, \ncomo id
, pueden configurarse con sus métodos dedicados. Por ejemplo,\nnextButton.id('next')
establece el atributo id
de un elemento. Llamar a\nnextButton.attribute('id', 'next')
tiene el mismo efecto.
El primer parámetro, attr
, es el nombre del atributo como un string. Llamar a\nmyElement.attribute('align')
devuelve el valor actual del atributo como un\nstring o null
si no se ha establecido.
El segundo parámetro, value
, es opcional. Es un string utilizado para establecer el\nvalor del atributo. Por ejemplo, llamar\na myElement.attribute('align', 'center')
establece la alineación horizontal \ndel elemento en center
.
Elimina un atributo del elemento.
\nEl parámetro attr
es el nombre del atributo como una cadena. Por ejemplo,\nllamar a myElement.removeAttribute('align')
elimina su atributo align
\nsi ha sido establecido.
Devuelve o establece el valor del elemento.
\nLlamar a myElement.value()
devuelve el valor actual del elemento.
El parámetro, value
, es un número o cadena opcional. Si se p roporciona,\ncomo en myElement.value(123)
, se utiliza para establecer el valor del elemento.
Muestra el elemento actual.
\n"],"path":[0,"p5.Element/show"]}],"hide":[0,{"description":[0,"Oculta el elemento actual.
\n"],"path":[0,"p5.Element/hide"]}],"size":[0,{"description":[0,"Establece el ancho y alto del elemento.
\nLlamar a myElement.size()
sin argumentos devuelve el tamaño del elemento\ncomo un objeto con las propiedades width
y height
. Por ejemplo,\n { width: 20, height: 10 }
.
El primer parámetro, width
, es opcional. Es un número utilizado para establecer el\nancho del elemento. Llamar a myElement.size(10)
El segundo parámetro, 'height, también es opcional. Es un número utilizado para establecer la altura del elemento. Por ejemplo, llamar
myElement.size(20, 10)` establece el ancho del elemento en 20 píxeles y la altura\nen 10 píxeles.
La constante AUTO
se puede usar para ajustar una dimensión a la vez manteniendo\nla relación de aspecto, que es width / height
. Por ejemplo,\nconsidera un elemento que mide 200 píxeles de ancho y 100 píxeles de alto. Llamar\na myElement.size(20, AUTO)
establece el ancho en 20 píxeles y la altura en 10\npíxeles.
Nota: En el caso de elementos que necesitan cargar datos, como imágenes, espera\npara llamar a myElement.size()
hasta después de que los datos se carguen.
Elimina el elemento, detiene todos los flujos de audio/video y elimina todas las\nfunciones de devolución de llamada.
\n"],"path":[0,"p5.Element/remove"]}],"drop":[0,{"description":[0,"Llama a una función cuando el usuario suelta un archivo sobre el elemento.
\nEl primer parámetro, callback
, es una función que se llama una vez que se carga el archivo.\nLa función de devolución de llamada (callback) debe tener un parámetro, file
, que es un\nobjeto p5.File. Si el usuario suelta varios archivos sobre\nel elemento, callback
se llama una vez para cada archivo.
El segundo parámetro, fxn
, es una función que se llama cuando el navegador detecta\nuno o varios archivos soltados. La función de devolución de llamada debe tener un\nparámetro, event
, que es un\nDragEvent.
Hace que el elemento sea arrastrable.
\nEl parámetro, elmnt
, es opcional. Si se pasa otro\np5.Element como en\nmyElement.draggable(otherElement)
, el otro elemento se volverá arrastrable.
Adds a class to the element.
\n"],"line":[0,2554],"params":[1,[[0,{"name":[0,"class"],"description":[0,"name of class to add.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\n function setup() {\n createCanvas(100, 100);\n background(200);\n // Create a div element.\n let div = createDiv('div');\n // Add a class to the div.\n div.addClass('myClass');\n describe('A gray square.');\n }\n
\n Adds an\nattribute\nto the element.
\nThis method is useful for advanced tasks. Most commonly-used attributes,\nsuch as id
, can be set with their dedicated methods. For example,\nnextButton.id('next')
sets an element's id
attribute. Calling\nnextButton.attribute('id', 'next')
has the same effect.
The first parameter, attr
, is the attribute's name as a string. Calling\nmyElement.attribute('align')
returns the attribute's current value as a\nstring or null
if it hasn't been set.
The second parameter, value
, is optional. It's a string used to set the\nattribute's value. For example, calling\nmyElement.attribute('align', 'center')
sets the element's horizontal\nalignment to center
.
attribute to set.
\n"],"type":[0,"String"]}],[0,{"name":[0,"value"],"description":[0,"value to assign to the attribute.
\n"],"type":[0,"String"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,false],"return":[0,{"description":[0,"value of the attribute."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a container div element and place it at the top-left corner.\n let container = createDiv();\n container.position(0, 0);\n\n // Create a paragraph element and place it within the container.\n // Set its horizontal alignment to \"left\".\n let p1 = createP('hi');\n p1.parent(container);\n p1.attribute('align', 'left');\n\n // Create a paragraph element and place it within the container.\n // Set its horizontal alignment to \"center\".\n let p2 = createP('hi');\n p2.parent(container);\n p2.attribute('align', 'center');\n\n // Create a paragraph element and place it within the container.\n // Set its horizontal alignment to \"right\".\n let p3 = createP('hi');\n p3.parent(container);\n p3.attribute('align', 'right');\n\n describe('A gray square with the text \"hi\" written on three separate lines, each placed further to the right.');\n}\n
\nCenters the element either vertically, horizontally, or both.
\ncenter()
will center the element relative to its parent or according to\nthe page's body if the element has no parent.
If no argument is passed, as in myElement.center()
the element is aligned\nboth vertically and horizontally.
passing 'vertical', 'horizontal' aligns element accordingly
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create the div element and style it.\n let div = createDiv('');\n div.size(10, 10);\n div.style('background-color', 'orange');\n\n // Center the div relative to the page's body.\n div.center();\n\n describe('A gray square and an orange rectangle. The rectangle is at the center of the page.');\n}\n
\nAttaches the element as a child of another element.
\nmyElement.child()
accepts either a string ID, DOM node, or\np5.Element. For example,\nmyElement.child(otherElement)
. If no argument is provided, an array of\nchildren DOM nodes is returned.
the ID, DOM node, or p5.Element\n to add to the current element
\n"],"type":[0,"String|p5.Element"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,false],"return":[0,{"description":[0,"an array of child nodes."],"type":[0,"Node[]"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create the div elements.\n let div0 = createDiv('Parent');\n let div1 = createDiv('Child');\n\n // Make div1 the child of div0\n // using the p5.Element.\n div0.child(div1);\n\n describe('A gray square with the words \"Parent\" and \"Child\" written beneath it.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create the div elements.\n let div0 = createDiv('Parent');\n let div1 = createDiv('Child');\n\n // Give div1 an ID.\n div1.id('apples');\n\n // Make div1 the child of div0\n // using its ID.\n div0.child('apples');\n\n describe('A gray square with the words \"Parent\" and \"Child\" written beneath it.');\n}\n
\n\n// This example assumes there is a div already on the page\n// with id \"myChildDiv\".\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create the div elements.\n let div0 = createDiv('Parent');\n\n // Select the child element by its ID.\n let elt = document.getElementById('myChildDiv');\n\n // Make div1 the child of div0\n // using its HTMLElement object.\n div0.child(elt);\n\n describe('A gray square with the words \"Parent\" and \"Child\" written beneath it.');\n}\n
\nAdds a\nclass attribute\nto the element using a given string.
\nCalling myElement.class()
without an argument returns a string with its current classes.
class to add.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Add the class \"small\" to the\n // canvas element.\n cnv.class('small');\n\n // Get the canvas element's class\n // and display it.\n let c = cnv.class();\n text(c, 35, 54);\n\n describe('The word \"small\" written in black on a gray canvas.');\n\n}\n
\nCalls a function when the mouse is pressed twice over the element.
\nCalling myElement.doubleClicked(false)
disables the function.
function to call when the mouse is\n double clicked over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // canvas is double-clicked.\n cnv.doubleClicked(randomColor);\n\n describe('A gray square changes color when the user double-clicks the canvas.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when a file is dragged off the element.
\nCalling myElement.dragLeave(false)
disables the function.
function to call when the file is\n dragged off the element.\n false
disables the function.
\n// Drag a file over, then off\n// the canvas to test.\n\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call byeFile() when a\n // file is dragged over,\n // then off the canvas.\n cnv.dragLeave(byeFile);\n\n describe('A gray square. The text \"bye, file\" appears when a file is dragged over, then off the square.');\n}\n\nfunction byeFile() {\n text('bye, file', 50, 50);\n}\n
\nCalls a function when a file is dragged over the element.
\nCalling myElement.dragOver(false)
disables the function.
function to call when the file is\n dragged over the element.\n false
disables the function.
\n// Drag a file over the canvas to test.\n\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call helloFile() when a\n // file is dragged over\n // the canvas.\n cnv.dragOver(helloFile);\n\n describe('A gray square. The text \"hello, file\" appears when a file is dragged over the square.');\n}\n\nfunction helloFile() {\n text('hello, file', 50, 50);\n}\n
\nMakes the element draggable.
\nThe parameter, elmnt
, is optional. If another\np5.Element object is passed, as in\nmyElement.draggable(otherElement)
, the other element will become draggable.
another p5.Element.
\n"],"type":[0,"p5.Element"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\nlet stickyNote;\nlet textInput;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a div element and style it.\n stickyNote = createDiv('Note');\n stickyNote.position(5, 5);\n stickyNote.size(80, 20);\n stickyNote.style('font-size', '16px');\n stickyNote.style('font-family', 'Comic Sans MS');\n stickyNote.style('background', 'orchid');\n stickyNote.style('padding', '5px');\n\n // Make the note draggable.\n stickyNote.draggable();\n\n // Create a panel div and style it.\n let panel = createDiv('');\n panel.position(5, 40);\n panel.size(80, 50);\n panel.style('background', 'orchid');\n panel.style('font-size', '16px');\n panel.style('padding', '5px');\n panel.style('text-align', 'center');\n\n // Make the panel draggable.\n panel.draggable();\n\n // Create a text input and style it.\n textInput = createInput('Note');\n textInput.size(70);\n\n // Add the input to the panel.\n textInput.parent(panel);\n\n // Call handleInput() when text is input.\n textInput.input(handleInput);\n\n describe(\n 'A gray square with two purple rectangles that move when dragged. The top rectangle displays the text that is typed into the bottom rectangle.'\n );\n}\n\n// Update stickyNote's HTML when text is input.\nfunction handleInput() {\n stickyNote.html(textInput.value());\n}\n
\nCalls a function when the user drops a file on the element.
\nThe first parameter, callback
, is a function to call once the file loads.\nThe callback function should have one parameter, file
, that's a\np5.File object. If the user drops multiple files on\nthe element, callback
, is called once for each file.
The second parameter, fxn
, is a function to call when the browser detects\none or more dropped files. The callback function should have one\nparameter, event
, that's a\nDragEvent.
called when a file loads. Called once for each file dropped.
\n"],"type":[0,"Function"]}],[0,{"name":[0,"fxn"],"description":[0,"called once when any files are dropped.
\n"],"type":[0,"Function"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\n// Drop an image on the canvas to view\n// this example.\nlet img;\n\nfunction setup() {\n let c = createCanvas(100, 100);\n\n background(200);\n\n // Call handleFile() when a file that's dropped on the canvas has loaded.\n c.drop(handleFile);\n\n describe('A gray square. When the user drops an image on the square, it is displayed.');\n}\n\n// Remove the existing image and display the new one.\nfunction handleFile(file) {\n // Remove the current image, if any.\n if (img) {\n img.remove();\n }\n\n // Create an
element with the\n // dropped file.\n img = createImg(file.data, '');\n img.hide();\n\n // Draw the image.\n image(img, 0, 0, width, height);\n}\n
\n\n// Drop an image on the canvas to view\n// this example.\nlet img;\nlet msg;\n\nfunction setup() {\n let c = createCanvas(100, 100);\n\n background(200);\n\n // Call functions when the user drops a file on the canvas\n // and when the file loads.\n c.drop(handleFile, handleDrop);\n\n describe('A gray square. When the user drops an image on the square, it is displayed. The id attribute of canvas element is also displayed.');\n}\n\n// Display the image when it loads.\nfunction handleFile(file) {\n // Remove the current image, if any.\n if (img) {\n img.remove();\n }\n\n // Create an img element with the dropped file.\n img = createImg(file.data, '');\n img.hide();\n\n // Draw the image.\n image(img, 0, 0, width, height);\n}\n\n// Display the file's name when it loads.\nfunction handleDrop(event) {\n // Remove current paragraph, if any.\n if (msg) {\n msg.remove();\n }\n\n // Use event to get the drop target's id.\n let id = event.target.id;\n\n // Write the canvas' id beneath it.\n msg = createP(id);\n msg.position(0, 100);\n\n // Set the font color randomly for each drop.\n let c = random(['red', 'green', 'blue']);\n msg.style('color', c);\n msg.style('font-size', '12px');\n}\n
\nThe element's underlying HTMLElement
object.
The\nHTMLElement\nobject's properties and methods can be used directly.
\n"],"line":[0,56],"itemtype":[0,"property"],"class":[0,"p5.Element"],"example":[1,[[0,"\n\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Set the border style for the\n // canvas.\n cnv.elt.style.border = '5px dashed deeppink';\n\n describe('A gray square with a pink border drawn with dashed lines.');\n}\n
\nChecks if a class is already applied to element.
\n"],"line":[0,2636],"params":[1,[[0,{"name":[0,"c"],"description":[0,"name of class to check.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,false],"return":[0,{"description":[0,"a boolean value if element has specified class."],"type":[0,"Boolean"]}],"example":[1,[[0,"\n\nlet div;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a div element.\n div = createDiv('div');\n\n // Add the class 'show' to the div.\n div.addClass('show');\n\n describe('A gray square.');\n}\n\n// Toggle the class 'show' when the mouse is pressed.\nfunction mousePressed() {\n if (div.hasClass('show')) {\n div.addClass('show');\n } else {\n div.removeClass('show');\n }\n}\n
\nA Number
property that stores the element's height.
Hides the current element.
\n"],"line":[0,3529],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\nlet p;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element.\n p = createP('p5*js');\n p.position(10, 10);\n\n describe('The text \"p5*js\" at the center of a gray square. The text disappears when the user double-clicks the square.');\n}\n\n// Hide the paragraph when the user double-clicks.\nfunction doubleClicked() {\n p.hide();\n}\n\n"]]],"isConstructor":[0,false],"path":[0,"p5.Element/hide"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.Element/html.mdx"],"slug":[0,"en/p5element/html"],"body":[0,"\n\n# html\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"html()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Sets the inner HTML of the element, replacing any existing HTML.
\nThe second parameter, append
, is optional. If true
is passed, as in\nmyElement.html('hi', true)
, the HTML is appended instead of replacing\nexisting HTML.
If no arguments are passed, as in myElement.html()
, the element's inner\nHTML is returned.
the HTML to be placed inside the element
\n"],"type":[0,"String"],"optional":[0,true]}],[0,{"name":[0,"append"],"description":[0,"whether to append HTML to existing
\n"],"type":[0,"Boolean"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,false],"return":[0,{"description":[0,"the inner HTML of the element"],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create the div element and set its size.\n let div = createDiv('');\n div.size(100, 100);\n\n // Set the inner HTML to \"hi\".\n div.html('hi');\n\n describe('A gray square with the word \"hi\" written beneath it.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create the div element and set its size.\n let div = createDiv('Hello ');\n div.size(100, 100);\n\n // Append \"World\" to the div's HTML.\n div.html('World', true);\n\n describe('A gray square with the text \"Hello World\" written beneath it.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create the div element.\n let div = createDiv('Hello');\n\n // Prints \"Hello\" to the console.\n print(div.html());\n\n describe('A gray square with the word \"Hello!\" written beneath it.');\n}\n
\nSets the element's ID using a given string.
\nCalling myElement.id()
without an argument returns its ID as a string.
ID of the element.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Set the canvas' ID\n // to \"mycanvas\".\n cnv.id('mycanvas');\n\n // Get the canvas' ID.\n let id = cnv.id();\n text(id, 24, 54);\n\n describe('The text \"mycanvas\" written in black on a gray background.');\n}\n
\nCalls a function when the mouse is pressed and released over the element.
\nCalling myElement.mouseReleased(false)
disables the function.
Note: Some mobile browsers may also trigger this event when the element\nreceives a quick tap.
\n"],"line":[0,578],"params":[1,[[0,{"name":[0,"fxn"],"description":[0,"function to call when the mouse is\n pressed and released over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when a\n // mouse press ends.\n cnv.mouseClicked(randomColor);\n\n describe('A gray square changes color when the user releases a mouse press.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the mouse moves over the element.
\nCalling myElement.mouseMoved(false)
disables the function.
function to call when the mouse\n moves over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // mouse moves.\n cnv.mouseMoved(randomColor);\n\n describe('A gray square changes color when the mouse moves over the canvas.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the mouse moves off the element.
\nCalling myElement.mouseOut(false)
disables the function.
function to call when the mouse\n moves off the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // mouse moves off the canvas.\n cnv.mouseOut(randomColor);\n\n describe('A gray square changes color when the mouse moves off the canvas.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the mouse moves onto the element.
\nCalling myElement.mouseOver(false)
disables the function.
function to call when the mouse\n moves onto the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // mouse moves onto the canvas.\n cnv.mouseOver(randomColor);\n\n describe('A gray square changes color when the mouse moves onto the canvas.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the mouse is pressed over the element.
\nCalling myElement.mousePressed(false)
disables the function.
Note: Some mobile browsers may also trigger this event when the element\nreceives a quick tap.
\n"],"line":[0,350],"params":[1,[[0,{"name":[0,"fxn"],"description":[0,"function to call when the mouse is\n pressed over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the canvas\n // is pressed.\n cnv.mousePressed(randomColor);\n\n describe('A gray square changes color when the mouse is pressed.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the mouse is released over the element.
\nCalling myElement.mouseReleased(false)
disables the function.
Note: Some mobile browsers may also trigger this event when the element\nreceives a quick tap.
\n"],"line":[0,533],"params":[1,[[0,{"name":[0,"fxn"],"description":[0,"function to call when the mouse is\n pressed over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when a\n // mouse press ends.\n cnv.mouseReleased(randomColor);\n\n describe('A gray square changes color when the user releases a mouse press.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the mouse wheel scrolls over the element.
\nThe callback function, fxn
, is passed an event
object. event
has\ntwo numeric properties, deltaY
and deltaX
. event.deltaY
is\nnegative if the mouse wheel rotates away from the user. It's positive if\nthe mouse wheel rotates toward the user. event.deltaX
is positive if\nthe mouse wheel moves to the right. It's negative if the mouse wheel moves\nto the left.
Calling myElement.mouseWheel(false)
disables the function.
function to call when the mouse wheel is\n scrolled over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // mouse wheel moves.\n cnv.mouseWheel(randomColor);\n\n describe('A gray square changes color when the user scrolls the mouse wheel over the canvas.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\n\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call changeBackground() when the\n // mouse wheel moves.\n cnv.mouseWheel(changeBackground);\n\n describe('A gray square. When the mouse wheel scrolls over the square, it changes color and displays shapes.');\n}\n\nfunction changeBackground(event) {\n // Change the background color\n // based on deltaY.\n if (event.deltaY > 0) {\n background('deeppink');\n } else if (event.deltaY < 0) {\n background('cornflowerblue');\n } else {\n background(200);\n }\n\n // Draw a shape based on deltaX.\n if (event.deltaX > 0) {\n circle(50, 50, 20);\n } else if (event.deltaX < 0) {\n square(40, 40, 20);\n }\n}\n
\nAttaches the element to a parent element.
\nFor example, a element may be used as a box to\nhold two pieces of text, a header and a paragraph. The\n
is the parent element of both the header and\nparagraph.
The parameter parent
can have one of three types. parent
can be a\nstring with the parent element's ID, as in\nmyElement.parent('container')
. It can also be another\np5.Element object, as in\nmyElement.parent(myDiv)
. Finally, parent
can be an HTMLElement
\nobject, as in myElement.parent(anotherElement)
.
Calling myElement.parent()
without an argument returns the element's\nparent.
ID, p5.Element,\n or HTMLElement of desired parent element.
\n"],"type":[0,"String|p5.Element|Object"]}]]]}],[0,{"params":[1,[]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\nfunction setup() {\n background(200);\n\n // Create a div element.\n let div = createDiv();\n\n // Place the div in the top-left corner.\n div.position(10, 20);\n\n // Set its width and height.\n div.size(80, 60);\n\n // Set its background color to white\n div.style('background-color', 'white');\n\n // Align any text to the center.\n div.style('text-align', 'center');\n\n // Set its ID to \"container\".\n div.id('container');\n\n // Create a paragraph element.\n let p = createP('p5*js');\n\n // Make the div its parent\n // using its ID \"container\".\n p.parent('container');\n\n describe('The text \"p5*js\" written in black at the center of a white rectangle. The rectangle is inside a gray square.');\n}\n
\n\nfunction setup() {\n background(200);\n\n // Create rectangular div element.\n let div = createDiv();\n\n // Place the div in the top-left corner.\n div.position(10, 20);\n\n // Set its width and height.\n div.size(80, 60);\n\n // Set its background color and align\n // any text to the center.\n div.style('background-color', 'white');\n div.style('text-align', 'center');\n\n // Create a paragraph element.\n let p = createP('p5*js');\n\n // Make the div its parent.\n p.parent(div);\n\n describe('The text \"p5*js\" written in black at the center of a white rectangle. The rectangle is inside a gray square.');\n}\n
\n\nfunction setup() {\n background(200);\n\n // Create rectangular div element.\n let div = createDiv();\n\n // Place the div in the top-left corner.\n div.position(10, 20);\n\n // Set its width and height.\n div.size(80, 60);\n\n // Set its background color and align\n // any text to the center.\n div.style('background-color', 'white');\n div.style('text-align', 'center');\n\n // Create a paragraph element.\n let p = createP('p5*js');\n\n // Make the div its parent\n // using the underlying\n // HTMLElement.\n p.parent(div.elt);\n\n describe('The text \"p5*js\" written in black at the center of a white rectangle. The rectangle is inside a gray square.');\n}\n
\nSets the element's position.
\nThe first two parameters, x
and y
, set the element's position relative\nto the top-left corner of the web page.
The third parameter, positionType
, is optional. It sets the element's\npositioning scheme.\npositionType
is a string that can be either 'static'
, 'fixed'
,\n'relative'
, 'sticky'
, 'initial'
, or 'inherit'
.
If no arguments passed, as in myElement.position()
, the method returns\nthe element's position in an object, as in { x: 0, y: 0 }
.
x-position relative to top-left of window (optional)
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"y"],"description":[0,"y-position relative to top-left of window (optional)
\n"],"type":[0,"Number"],"optional":[0,true]}],[0,{"name":[0,"positionType"],"description":[0,"it can be static, fixed, relative, sticky, initial or inherit (optional)
\n"],"type":[0,"String"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,false],"return":[0,{"description":[0,"object of form `{ x: 0, y: 0 }` containing the element's position."],"type":[0,"Object"]}],"example":[1,[[0,"\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Positions the canvas 50px to the right and 100px\n // below the top-left corner of the window.\n cnv.position(50, 100);\n\n describe('A gray square that is 50 pixels to the right and 100 pixels down from the top-left corner of the web page.');\n}\n
\n\nfunction setup() {\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Positions the canvas at the top-left corner\n // of the window with a 'fixed' position type.\n cnv.position(0, 0, 'fixed');\n\n describe('A gray square in the top-left corner of the web page.');\n}\n
\nRemoves the element, stops all audio/video streams, and removes all\ncallback functions.
\n"],"line":[0,3731],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,false],"example":[1,[[0,"\n\nlet p;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element.\n p = createP('p5*js');\n p.position(10, 10);\n\n describe('The text \"p5*js\" written at the center of a gray square. ');\n}\n\n// Remove the paragraph when the user double-clicks.\nfunction doubleClicked() {\n p.remove();\n}\n
\nRemoves an attribute from the element.
\nThe parameter attr
is the attribute's name as a string. For example,\ncalling myElement.removeAttribute('align')
removes its align
\nattribute if it's been set.
attribute to remove.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\nlet p;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element and place it in the center of the canvas.\n // Set its \"align\" attribute to \"center\".\n p = createP('hi');\n p.position(0, 20);\n p.attribute('align', 'center');\n\n describe('The text \"hi\" written in black at the center of a gray square. The text moves to the left edge when double-clicked.');\n}\n\n// Remove the 'align' attribute when the user double-clicks the paragraph.\nfunction doubleClicked() {\n p.removeAttribute('align');\n}\n
\nRemoves a class from the element.
\n"],"line":[0,2593],"params":[1,[[0,{"name":[0,"class"],"description":[0,"name of class to remove.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\n// In this example, a class is set when the div is created\n// and removed when mouse is pressed. This could link up\n// with a CSS style rule to toggle style properties.\n\nlet div;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a div element.\n div = createDiv('div');\n\n // Add a class to the div.\n div.addClass('myClass');\n\n describe('A gray square.');\n}\n\n// Remove 'myClass' from the div when the user presses the mouse.\nfunction mousePressed() {\n div.removeClass('myClass');\n}\n
\nShows the current element.
\n"],"line":[0,3493],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\nlet p;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element and hide it.\n p = createP('p5*js');\n p.position(10, 10);\n p.hide();\n\n describe('A gray square. The text \"p5*js\" appears when the user double-clicks the square.');\n}\n\n// Show the paragraph when the user double-clicks.\nfunction doubleClicked() {\n p.show();\n}\n
\nSets the element's width and height.
\nCalling myElement.size()
without an argument returns the element's size\nas an object with the properties width
and height
. For example,\n { width: 20, height: 10 }
.
The first parameter, width
, is optional. It's a number used to set the\nelement's width. Calling myElement.size(10)
The second parameter, 'height, is also optional. It's a number used to set the element's height. For example, calling
myElement.size(20, 10)` sets the element's width to 20 pixels and height\nto 10 pixels.
The constant AUTO
can be used to adjust one dimension at a time while\nmaintaining the aspect ratio, which is width / height
. For example,\nconsider an element that's 200 pixels wide and 100 pixels tall. Calling\nmyElement.size(20, AUTO)
sets the width to 20 pixels and height to 10\npixels.
Note: In the case of elements that need to load data, such as images, wait\nto call myElement.size()
until after the data loads.
width of the element, either AUTO, or a number.
\n"],"type":[0,"Number|Constant"],"optional":[0,true]}],[0,{"name":[0,"h"],"description":[0,"height of the element, either AUTO, or a number.
\n"],"type":[0,"Number|Constant"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,false],"return":[0,{"description":[0,"width and height of the element in an object."],"type":[0,"Object"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a pink div element and place it at the top-left corner.\n let div = createDiv();\n div.position(10, 10);\n div.style('background-color', 'deeppink');\n\n // Set the div's width to 80 pixels and height to 20 pixels.\n div.size(80, 20);\n\n describe('A gray square with a pink rectangle near its top.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a pink div element and place it at the top-left corner.\n let div = createDiv();\n div.position(10, 10);\n div.style('background-color', 'deeppink');\n\n // Set the div's width to 80 pixels and height to 40 pixels.\n div.size(80, 40);\n\n // Get the div's size as an object.\n let s = div.size();\n\n // Display the div's dimensions.\n div.html(`${s.width} x ${s.height}`);\n\n describe('A gray square with a pink rectangle near its top. The text \"80 x 40\" is written within the rectangle.');\n}\n
\n\nlet img1;\nlet img2;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Load an image of an astronaut on the moon\n // and place it at the top-left of the canvas.\n img1 = createImg(\n '/assets/moonwalk.jpg',\n 'An astronaut walking on the moon',\n ''\n );\n img1.position(0, 0);\n\n // Load an image of an astronaut on the moon\n // and place it at the top-left of the canvas.\n // Resize the image once it's loaded.\n img2 = createImg(\n '/assets/moonwalk.jpg',\n 'An astronaut walking on the moon',\n '',\n resizeImage\n );\n img2.position(0, 0);\n\n describe('A gray square two copies of a space image at the top-left. The copy in front is smaller.');\n}\n\n// Resize img2 and keep its aspect ratio.\nfunction resizeImage() {\n img2.size(50, AUTO);\n}\n
\nApplies a style to the element by adding a\nCSS declaration.
\nThe first parameter, property
, is a string. If the name of a style\nproperty is passed, as in myElement.style('color')
, the method returns\nthe current value as a string or null
if it hasn't been set. If a\nproperty:style
string is passed, as in\nmyElement.style('color:deeppink')
, the method sets the style property
\nto value
.
The second parameter, value
, is optional. It sets the property's value.\nvalue
can be a string, as in\nmyElement.style('color', 'deeppink')
, or a\np5.Color object, as in\nmyElement.style('color', myColor)
.
style property to set.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"property"],"description":[0,""],"type":[0,"String"]}],[0,{"name":[0,"value"],"description":[0,"value to assign to the property.
\n"],"type":[0,"String|p5.Color"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,false],"return":[0,{"description":[0,"value of the property."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element and set its font color to \"deeppink\".\n let p = createP('p5*js');\n p.position(25, 20);\n p.style('color', 'deeppink');\n\n describe('The text p5*js written in pink on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.Color object.\n let c = color('deeppink');\n\n // Create a paragraph element and set its font color using a p5.Color object.\n let p = createP('p5*js');\n p.position(25, 20);\n p.style('color', c);\n\n describe('The text p5*js written in pink on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a paragraph element and set its font color to \"deeppink\"\n // using property:value syntax.\n let p = createP('p5*js');\n p.position(25, 20);\n p.style('color:deeppink');\n\n describe('The text p5*js written in pink on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an empty paragraph element and set its font color to \"deeppink\".\n let p = createP();\n p.position(5, 5);\n p.style('color', 'deeppink');\n\n // Get the element's color as an RGB color string.\n let c = p.style('color');\n\n // Set the element's inner HTML using the RGB color string.\n p.html(c);\n\n describe('The text \"rgb(255, 20, 147)\" written in pink on a gray background.');\n}\n
\nToggles whether a class is applied to the element.
\n"],"line":[0,2677],"params":[1,[[0,{"name":[0,"c"],"description":[0,"class name to toggle.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Element"],"chainable":[0,true],"example":[1,[[0,"\n\nlet div;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a div element.\n div = createDiv('div');\n\n // Add the 'show' class to the div.\n div.addClass('show');\n\n describe('A gray square.');\n}\n\n// Toggle the 'show' class when the mouse is pressed.\nfunction mousePressed() {\n div.toggleClass('show');\n}\n
\nCalls a function when the user stops touching the element.
\nCalling myElement.touchMoved(false)
disables the function.
Note: Touch functions only work on mobile devices.
\n"],"line":[0,837],"params":[1,[[0,{"name":[0,"fxn"],"description":[0,"function to call when the touch\n ends.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // user touches the canvas,\n // then lifts their finger.\n cnv.touchEnded(randomColor);\n\n describe('A gray square changes color when the user touches the canvas, then lifts their finger.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the user touches the element and moves.
\nCalling myElement.touchMoved(false)
disables the function.
Note: Touch functions only work on mobile devices.
\n"],"line":[0,793],"params":[1,[[0,{"name":[0,"fxn"],"description":[0,"function to call when the touch\n moves over the element.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // user touches the canvas\n // and moves.\n cnv.touchMoved(randomColor);\n\n describe('A gray square changes color when the user touches the canvas and moves.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nCalls a function when the element is touched.
\nCalling myElement.touchStarted(false)
disables the function.
Note: Touch functions only work on mobile devices.
\n"],"line":[0,749],"params":[1,[[0,{"name":[0,"fxn"],"description":[0,"function to call when the touch\n starts.\n false
disables the function.
\nfunction setup() {\n // Create a canvas element and\n // assign it to cnv.\n let cnv = createCanvas(100, 100);\n\n background(200);\n\n // Call randomColor() when the\n // user touches the canvas.\n cnv.touchStarted(randomColor);\n\n describe('A gray square changes color when the user touches the canvas.');\n}\n\n// Paint the background either\n// red, yellow, blue, or green.\nfunction randomColor() {\n let c = random(['red', 'yellow', 'blue', 'green']);\n background(c);\n}\n
\nReturns or sets the element's value.
\nCalling myElement.value()
returns the element's current value.
The parameter, value
, is an optional number or string. If provided,\nas in myElement.value(123)
, it's used to set the element's value.
\nlet input;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a text input and place it beneath the canvas.\n // Set its default value to \"hello\".\n input = createInput('hello');\n input.position(0, 100);\n\n describe('The text from an input box is displayed on a gray square.');\n}\n\nfunction draw() {\n background(200);\n\n // Use the input's value to display a message.\n let msg = input.value();\n text(msg, 0, 55);\n}\n
\n\nlet input;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a text input and place it beneath the canvas.\n // Set its default value to \"hello\".\n input = createInput('hello');\n input.position(0, 100);\n\n describe('The text from an input box is displayed on a gray square. The text resets to \"hello\" when the user double-clicks the square.');\n}\n\nfunction draw() {\n background(200);\n\n // Use the input's value to display a message.\n let msg = input.value();\n text(msg, 0, 55);\n}\n\n// Reset the input's value.\nfunction doubleClicked() {\n input.value('hello');\n}\n
\nA Number
property that stores the element's width.
A class to describe a file.
\np5.File
objects are used by\nmyElement.drop() and\ncreated by\ncreateFileInput.
wrapped file.
\n"],"type":[0,"File"]}]]],"chainable":[0,false],"example":[1,[[0,"\n\n// Use the file input to load a\n// file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displayInfo() when the file loads.\n let input = createFileInput(displayInfo);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its info is written in black.');\n}\n\n// Display the p5.File's info once it loads.\nfunction displayInfo(file) {\n background(200);\n\n // Display the p5.File's name.\n text(file.name, 10, 10, 80, 40);\n\n // Display the p5.File's type and subtype.\n text(`${file.type}/${file.subtype}`, 10, 70);\n\n // Display the p5.File's size in bytes.\n text(file.size, 10, 90);\n}\n
\n\n// Use the file input to select an image to\n// load and display.\nlet img;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a file input and place it beneath the canvas.\n // Call handleImage() when the file image loads.\n let input = createFileInput(handleImage);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user selects an image file to load, it is displayed on the square.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw the image if it's ready.\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\n// Use the p5.File's data once it loads.\nfunction handleImage(file) {\n // Check the p5.File's type.\n if (file.type === 'image') {\n // Create an image using using the p5.File's data.\n img = createImg(file.data, '');\n\n // Hide the image element so it doesn't appear twice.\n img.hide();\n } else {\n img = null;\n }\n}\n
\nUnderlying\nFile\nobject. All File
properties and methods are accessible.
The file\nMIME type\nas a string.
\nFor example, 'image'
and 'text'
are both MIME types.
The file subtype as a string.
\nFor example, a file with an 'image'
\nMIME type\nmay have a subtype such as png
or jpeg
.
The file name as a string.
\n"],"path":[0,"p5.File/name"]}],"size":[0,{"description":[0,"The number of bytes in the file.
\n"],"path":[0,"p5.File/size"]}],"data":[0,{"description":[0,"A string containing the file's data.
\nData can be either image data, text contents, or a parsed object in the\ncase of JSON and p5.XML objects.
\n"],"path":[0,"p5.File/data"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.File"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.File/data.mdx"],"slug":[0,"en/p5file/data"],"body":[0,"\n\n# data\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"data"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"A string containing the file's data.
\nData can be either image data, text contents, or a parsed object in the\ncase of JSON and p5.XML objects.
\n"],"line":[0,5769],"itemtype":[0,"property"],"class":[0,"p5.File"],"example":[1,[[0,"\n\n// Use the file input to load a file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displayData() when the file loads.\n let input = createFileInput(displayData);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its data is written in black.');\n}\n\n// Display the p5.File's data once it loads.\nfunction displayData(file) {\n background(200);\n\n // Display the p5.File's data, which looks like a random string of characters.\n text(file.data, 10, 10, 80, 80);\n}\n
\nUnderlying\nFile\nobject. All File
properties and methods are accessible.
\n// Use the file input to load a\n// file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displayInfo() when the file loads.\n let input = createFileInput(displayInfo);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its info is written in black.');\n}\n\n// Use the p5.File once it loads.\nfunction displayInfo(file) {\n background(200);\n\n // Display the p5.File's name.\n text(file.name, 10, 10, 80, 40);\n\n // Display the p5.File's type and subtype.\n text(`${file.type}/${file.subtype}`, 10, 70);\n\n // Display the p5.File's size in bytes.\n text(file.size, 10, 90);\n}\n
\nThe file name as a string.
\n"],"line":[0,5699],"itemtype":[0,"property"],"class":[0,"p5.File"],"example":[1,[[0,"\n\n// Use the file input to load a\n// file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displayName() when the file loads.\n let input = createFileInput(displayName);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its name is written in black.');\n}\n\n// Display the p5.File's name once it loads.\nfunction displayName(file) {\n background(200);\n\n // Display the p5.File's name.\n text(`This is file's name is: ${file.name}`, 10, 10, 80, 80);\n}\n
\nThe number of bytes in the file.
\n"],"line":[0,5734],"itemtype":[0,"property"],"class":[0,"p5.File"],"example":[1,[[0,"\n\n// Use the file input to load a file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displaySize() when the file loads.\n let input = createFileInput(displaySize);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its size in bytes is written in black.');\n}\n\n// Display the p5.File's size in bytes once it loads.\nfunction displaySize(file) {\n background(200);\n\n // Display the p5.File's size.\n text(`This is file has ${file.size} bytes.`, 10, 10, 80, 80);\n}\n
\nThe file subtype as a string.
\nFor example, a file with an 'image'
\nMIME type\nmay have a subtype such as png
or jpeg
.
\n// Use the file input to load a\n// file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displaySubtype() when the file loads.\n let input = createFileInput(displaySubtype);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its subtype is written in black.');\n}\n\n// Display the p5.File's type once it loads.\nfunction displaySubtype(file) {\n background(200);\n\n // Display the p5.File's subtype.\n text(`This is file's subtype is: ${file.subtype}`, 10, 10, 80, 80);\n}\n
\nThe file\nMIME type\nas a string.
\nFor example, 'image'
and 'text'
are both MIME types.
\n// Use the file input to load a file and display its info.\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a file input and place it beneath the canvas.\n // Call displayType() when the file loads.\n let input = createFileInput(displayType);\n input.position(0, 100);\n\n describe('A gray square with a file input beneath it. If the user loads a file, its type is written in black.');\n}\n\n// Display the p5.File's type once it loads.\nfunction displayType(file) {\n background(200);\n\n // Display the p5.File's type.\n text(`This is file's type is: ${file.type}`, 10, 10, 80, 80);\n}\n
\nA class to handle audio and video.
\np5.MediaElement
extends p5.Element with\nmethods to handle audio and video. p5.MediaElement
objects are created by\ncalling createVideo,\ncreateAudio, and\ncreateCapture.
DOM node that is wrapped
\n"],"type":[0,"String"]}]]],"chainable":[0,false],"example":[1,[[0,"\n\nlet capture;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createCapture().\n capture = createCapture(VIDEO);\n capture.hide();\n\n describe('A webcam feed with inverted colors.');\n}\n\nfunction draw() {\n // Display the video stream and invert the colors.\n image(capture, 0, 0, width, width * capture.height / capture.width);\n filter(INVERT);\n}\n
\nPlays audio or video from a media element.
\n"],"path":[0,"p5.MediaElement/play"]}],"stop":[0,{"description":[0,"Stops a media element and sets its current time to 0.
\nCalling media.play()
will restart playing audio/video from the beginning.
Pauses a media element.
\nCalling media.play()
will resume playing audio/video from the moment it paused.
Plays the audio/video repeatedly in a loop.
\n"],"path":[0,"p5.MediaElement/loop"]}],"noLoop":[0,{"description":[0,"Stops the audio/video from playing in a loop.
\nThe media will stop when it finishes playing.
\n"],"path":[0,"p5.MediaElement/noLoop"]}],"autoplay":[0,{"description":[0,"Sets the audio/video to play once it's loaded.
\nThe parameter, shouldAutoplay
, is optional. Calling\nmedia.autoplay()
without an argument causes the media to play\nautomatically. If true
is passed, as in media.autoplay(true)
, the\nmedia will automatically play. If false
is passed, as in\nmedia.autoPlay(false)
, it won't play automatically.
Sets the audio/video volume.
\nCalling media.volume()
without an argument returns the current volume\nas a number in the range 0 (off) to 1 (maximum).
The parameter, val
, is optional. It's a number that sets the volume\nfrom 0 (off) to 1 (maximum). For example, calling media.volume(0.5)
\nsets the volume to half of its maximum.
Sets the audio/video playback speed.
\nThe parameter, val
, is optional. It's a number that sets the playback\nspeed. 1 plays the media at normal speed, 0.5 plays it at half speed, 2\nplays it at double speed, and so on. -1 plays the media at normal speed\nin reverse.
Calling media.speed()
returns the current speed as a number.
Note: Not all browsers support backward playback. Even if they do,\nplayback might not be smooth.
\n"],"path":[0,"p5.MediaElement/speed"]}],"time":[0,{"description":[0,"Sets the media element's playback time.
\nThe parameter, time
, is optional. It's a number that specifies the\ntime, in seconds, to jump to when playback begins.
Calling media.time()
without an argument returns the number of seconds\nthe audio/video has played.
Note: Time resets to 0 when looping media restarts.
\n"],"path":[0,"p5.MediaElement/time"]}],"duration":[0,{"description":[0,"Returns the audio/video's duration in seconds.
\n"],"path":[0,"p5.MediaElement/duration"]}],"onended":[0,{"description":[0,"Calls a function when the audio/video reaches the end of its playback.
\nThe element is passed as an argument to the callback function.
\nNote: The function won't be called if the media is looping.
\n"],"path":[0,"p5.MediaElement/onended"]}],"connect":[0,{"description":[0,"Sends the element's audio to an output.
\nThe parameter, audioNode
, can be an AudioNode
or an object from the\np5.sound
library.
If no element is provided, as in myElement.connect()
, the element\nconnects to the main output. All connections are removed by the\n.disconnect()
method.
Note: This method is meant to be used with the p5.sound.js addon library.
\n"],"path":[0,"p5.MediaElement/connect"]}],"disconnect":[0,{"description":[0,"Disconnect all Web Audio routing, including to the main output.
\nThis is useful if you want to re-route the output through audio effects,\nfor example.
\n"],"path":[0,"p5.MediaElement/disconnect"]}],"showControls":[0,{"description":[0,"Show the default\nHTMLMediaElement\ncontrols.
\nNote: The controls vary between web browsers.
\n"],"path":[0,"p5.MediaElement/showControls"]}],"hideControls":[0,{"description":[0,"Hide the default\nHTMLMediaElement\ncontrols.
\n"],"path":[0,"p5.MediaElement/hideControls"]}],"addCue":[0,{"description":[0,"Schedules a function to call when the audio/video reaches a specific time\nduring its playback.
\nThe first parameter, time
, is the time, in seconds, when the function\nshould run. This value is passed to callback
as its first argument.
The second parameter, callback
, is the function to call at the specified\ncue time.
The third parameter, value
, is optional and can be any type of value.\nvalue
is passed to callback
.
Calling media.addCue()
returns an ID as a string. This is useful for\nremoving the cue later.
Removes a callback based on its ID.
\n"],"path":[0,"p5.MediaElement/removeCue"]}],"clearCues":[0,{"description":[0,"Removes all functions scheduled with media.addCue()
.
Path to the media element's source as a string.
\n"],"path":[0,"p5.MediaElement/src"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.MediaElement"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.MediaElement/addCue.mdx"],"slug":[0,"en/p5mediaelement/addcue"],"body":[0,"\n\n# addCue\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"addCue()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Schedules a function to call when the audio/video reaches a specific time\nduring its playback.
\nThe first parameter, time
, is the time, in seconds, when the function\nshould run. This value is passed to callback
as its first argument.
The second parameter, callback
, is the function to call at the specified\ncue time.
The third parameter, value
, is optional and can be any type of value.\nvalue
is passed to callback
.
Calling media.addCue()
returns an ID as a string. This is useful for\nremoving the cue later.
cue time to run the callback function.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"callback"],"description":[0,"function to call at the cue time.
\n"],"type":[0,"Function"]}],[0,{"name":[0,"value"],"description":[0,"object to pass as the argument to\n callback
.
\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n let beat = createAudio('/assets/beat.mp3');\n\n // Play the beat in a loop.\n beat.loop();\n\n // Schedule a few events.\n beat.addCue(0, changeBackground, 'red');\n beat.addCue(2, changeBackground, 'deeppink');\n beat.addCue(4, changeBackground, 'orchid');\n beat.addCue(6, changeBackground, 'lavender');\n\n describe('A red square with a beat playing in the background. Its color changes every 2 seconds while the audio plays.');\n}\n\n// Change the background color.\nfunction changeBackground(c) {\n background(c);\n}\n
\nSets the audio/video to play once it's loaded.
\nThe parameter, shouldAutoplay
, is optional. Calling\nmedia.autoplay()
without an argument causes the media to play\nautomatically. If true
is passed, as in media.autoplay(true)
, the\nmedia will automatically play. If false
is passed, as in\nmedia.autoPlay(false)
, it won't play automatically.
whether the element should autoplay.
\n"],"type":[0,"Boolean"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,true],"example":[1,[[0,"\n\nlet video;\n\nfunction setup() {\n noCanvas();\n\n // Call handleVideo() once the video loads.\n video = createVideo('/assets/fingers.mov', handleVideo);\n\n describe('A video of fingers walking on a treadmill.');\n}\n\n// Set the video's size and play it.\nfunction handleVideo() {\n video.size(100, 100);\n video.autoplay();\n}\n
\n\nfunction setup() {\n noCanvas();\n\n // Load a video, but don't play it automatically.\n let video = createVideo('/assets/fingers.mov', handleVideo);\n\n // Play the video when the user clicks on it.\n video.mousePressed(handlePress);\n\n describe('An image of fingers on a treadmill. They start walking when the user double-clicks on them.');\n}\n
\nRemoves all functions scheduled with media.addCue()
.
\nlet isChanging = true;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.MediaElement using createAudio().\n let beat = createAudio('/assets/beat.mp3');\n\n // Play the beat in a loop.\n beat.loop();\n\n // Schedule a few events.\n beat.addCue(0, changeBackground, 'red');\n beat.addCue(2, changeBackground, 'deeppink');\n beat.addCue(4, changeBackground, 'orchid');\n beat.addCue(6, changeBackground, 'lavender');\n\n describe('The text \"Double-click to stop changing.\" written on a square. The color changes every 2 seconds while the audio plays. The color stops changing when the user double-clicks the square.');\n}\n\nfunction draw() {\n background(200);\n\n // Display different instructions based on the available callbacks.\n if (isChanging === true) {\n text('Double-click to stop changing.', 10, 10, 80, 80);\n } else {\n text('No more changes.', 10, 10, 80, 80);\n }\n}\n\n// Change the background color.\nfunction changeBackground(c) {\n background(c);\n}\n\n// Remove cued functions and stop changing colors when the user\n// double-clicks.\nfunction doubleClicked() {\n if (isChanging === true) {\n beat.clearCues();\n isChanging = false;\n }\n}\n
\nSends the element's audio to an output.
\nThe parameter, audioNode
, can be an AudioNode
or an object from the\np5.sound
library.
If no element is provided, as in myElement.connect()
, the element\nconnects to the main output. All connections are removed by the\n.disconnect()
method.
Note: This method is meant to be used with the p5.sound.js addon library.
\n"],"line":[0,5095],"params":[1,[[0,{"name":[0,"audioNode"],"description":[0,"AudioNode from the Web Audio API,\nor an object from the p5.sound library
\n"],"type":[0,"AudioNode|Object"]}]]],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,false],"isConstructor":[0,false],"path":[0,"p5.MediaElement/connect"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.MediaElement/disconnect.mdx"],"slug":[0,"en/p5mediaelement/disconnect"],"body":[0,"\n\n# disconnect\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"disconnect()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Disconnect all Web Audio routing, including to the main output.
\nThis is useful if you want to re-route the output through audio effects,\nfor example.
\n"],"line":[0,5148],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,false],"isConstructor":[0,false],"path":[0,"p5.MediaElement/disconnect"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.MediaElement/duration.mdx"],"slug":[0,"en/p5mediaelement/duration"],"body":[0,"\n\n# duration\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"duration()"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Returns the audio/video's duration in seconds.
\n"],"line":[0,4868],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,false],"return":[0,{"description":[0,"duration (in seconds)."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nlet dragon;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.MediaElement using createAudio().\n dragon = createAudio('/assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n describe('The text \"S seconds left\" on a gray square with media controls beneath it. The number \"S\" decreases as the song plays.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the time remaining.\n let s = dragon.duration() - dragon.time();\n\n // Round s to 1 decimal place for display.\n s = round(s, 1);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the time remaining.\n text(`${s} seconds left`, 50, 50);\n}\n
\nHide the default\nHTMLMediaElement\ncontrols.
\n"],"line":[0,5207],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,false],"example":[1,[[0,"\n\nlet dragon;\nlet isHidden = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n dragon = createAudio('/assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n describe('The text \"Double-click to hide controls\" written in the middle of a gray square. A song plays in the background. Audio controls are displayed beneath the canvas. The controls appear/disappear when the user double-clicks the square.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n\n // Display a different message when controls are hidden or shown.\n if (isHidden === true) {\n text('Double-click to show controls', 10, 20, 80, 80);\n } else {\n text('Double-click to hide controls', 10, 20, 80, 80);\n }\n}\n\n// Show/hide controls based on a double-click.\nfunction doubleClicked() {\n if (isHidden === true) {\n dragon.showControls();\n isHidden = false;\n } else {\n dragon.hideControls();\n isHidden = true;\n }\n}\n
\nPlays the audio/video repeatedly in a loop.
\n"],"line":[0,4400],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,true],"example":[1,[[0,"\n\nlet beat;\nlet isLooping = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('/assets/beat.mp3');\n\n describe('The text \"Click to loop\" written in black on a gray background. A beat plays repeatedly in a loop when the user clicks. The beat stops when the user clicks again.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display different instructions based on playback.\n if (isLooping === true) {\n text('Click to stop', 50, 50);\n } else {\n text('Click to loop', 50, 50);\n }\n}\n\n// Adjust playback when the user presses the mouse.\nfunction mousePressed() {\n if (isLooping === true) {\n // If the beat is looping, stop it.\n beat.stop();\n isLooping = false;\n } else {\n // If the beat is stopped, loop it.\n beat.loop();\n isLooping = true;\n }\n}\n
\nStops the audio/video from playing in a loop.
\nThe media will stop when it finishes playing.
\n"],"line":[0,4458],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,true],"example":[1,[[0,"\n\nlet beat;\nlet isPlaying = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('/assets/beat.mp3');\n\n describe('The text \"Click to play\" written in black on a gray background. A beat plays when the user clicks. The beat stops when the user clicks again.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display different instructions based on playback.\n if (isPlaying === true) {\n text('Click to stop', 50, 50);\n } else {\n text('Click to play', 50, 50);\n }\n}\n\n// Adjust playback when the user presses the mouse.\nfunction mousePressed() {\n if (isPlaying === true) {\n // If the beat is playing, stop it.\n beat.stop();\n isPlaying = false;\n } else {\n // If the beat is stopped, play it.\n beat.play();\n isPlaying = true;\n }\n}\n
\nCalls a function when the audio/video reaches the end of its playback.
\nThe element is passed as an argument to the callback function.
\nNote: The function won't be called if the media is looping.
\n"],"line":[0,5024],"params":[1,[[0,{"name":[0,"callback"],"description":[0,"function to call when playback ends.\n The p5.MediaElement
is passed as\n the argument.
\nlet beat;\nlet isPlaying = false;\nlet isDone = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('/assets/beat.mp3');\n\n // Call handleEnd() when the beat finishes.\n beat.onended(handleEnd);\n\n describe('The text \"Click to play\" written in black on a gray square. A beat plays when the user clicks. The text \"Done!\" appears when the beat finishes playing.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display different messages based on playback.\n if (isDone === true) {\n text('Done!', 50, 50);\n } else if (isPlaying === false) {\n text('Click to play', 50, 50);\n } else {\n text('Playing...', 50, 50);\n }\n}\n\n// Play the beat when the user presses the mouse.\nfunction mousePressed() {\n if (isPlaying === false) {\n isPlaying = true;\n beat.play();\n }\n}\n\n// Set isDone when playback ends.\nfunction handleEnd() {\n isDone = false;\n}\n
\nPauses a media element.
\nCalling media.play()
will resume playing audio/video from the moment it paused.
\nlet beat;\nlet isPaused = true;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('/assets/beat.mp3');\n\n describe('The text \"Click to play\" written in black on a gray background. The beat plays or pauses when the user clicks the square.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display different instructions based on playback.\n if (isPaused === true) {\n text('Click to play', 50, 50);\n } else {\n text('Click to pause', 50, 50);\n }\n}\n\n// Adjust playback when the user presses the mouse.\nfunction mousePressed() {\n if (isPaused === true) {\n // If the beat is paused,\n // play it.\n beat.play();\n isPaused = false;\n } else {\n // If the beat is playing,\n // pause it.\n beat.pause();\n isPaused = true;\n }\n}\n
\nPlays audio or video from a media element.
\n"],"line":[0,4215],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,true],"example":[1,[[0,"\n\nlet beat;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display a message.\n text('Click to play', 50, 50);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('/assets/beat.mp3');\n\n describe('The text \"Click to play\" written in black on a gray background. A beat plays when the user clicks the square.');\n}\n\n// Play the beat when the user presses the mouse.\nfunction mousePressed() {\n beat.play();\n}\n
\nRemoves a callback based on its ID.
\n"],"line":[0,5328],"params":[1,[[0,{"name":[0,"id"],"description":[0,"ID of the cue, created by media.addCue()
.
\nlet lavenderID;\nlet isRemoved = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n let beat = createAudio('/assets/beat.mp3');\n\n // Play the beat in a loop.\n beat.loop();\n\n // Schedule a few events.\n beat.addCue(0, changeBackground, 'red');\n beat.addCue(2, changeBackground, 'deeppink');\n beat.addCue(4, changeBackground, 'orchid');\n\n // Record the ID of the \"lavender\" callback.\n lavenderID = beat.addCue(6, changeBackground, 'lavender');\n\n describe('The text \"Double-click to remove lavender.\" written on a red square. The color changes every 2 seconds while the audio plays. The lavender option is removed when the user double-clicks the square.');\n}\n\nfunction draw() {\n background(200);\n\n // Display different instructions based on the available callbacks.\n if (isRemoved === false) {\n text('Double-click to remove lavender.', 10, 10, 80, 80);\n } else {\n text('No more lavender.', 10, 10, 80, 80);\n }\n}\n\n// Change the background color.\nfunction changeBackground(c) {\n background(c);\n}\n\n// Remove the lavender color-change cue when the user double-clicks.\nfunction doubleClicked() {\n if (isRemoved === false) {\n beat.removeCue(lavenderID);\n isRemoved = true;\n }\n}\n
\nShow the default\nHTMLMediaElement\ncontrols.
\nNote: The controls vary between web browsers.
\n"],"line":[0,5166],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background('cornflowerblue');\n\n // Style the text.\n textAlign(CENTER);\n textSize(50);\n\n // Display a dragon.\n text('🐉', 50, 50);\n\n // Create a p5.MediaElement using createAudio().\n let dragon = createAudio('/assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n describe('A dragon emoji, 🐉, drawn in the center of a blue square. A song plays in the background. Audio controls are displayed beneath the canvas.');\n}\n
\nSets the audio/video playback speed.
\nThe parameter, val
, is optional. It's a number that sets the playback\nspeed. 1 plays the media at normal speed, 0.5 plays it at half speed, 2\nplays it at double speed, and so on. -1 plays the media at normal speed\nin reverse.
Calling media.speed()
returns the current speed as a number.
Note: Not all browsers support backward playback. Even if they do,\nplayback might not be smooth.
\n"],"line":[0,4691],"overloads":[1,[[0,{"params":[1,[]]}],[0,{"params":[1,[[0,{"name":[0,"speed"],"description":[0,"speed multiplier for playback.
\n"],"type":[0,"Number"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,false],"return":[0,{"description":[0,"current playback speed."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nlet dragon;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n dragon = createAudio('/assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n describe('The text \"Speed: S\" on a gray square with media controls beneath it. The number \"S\" oscillates between 0 and 1 as the music plays.');\n}\n\nfunction draw() {\n background(200);\n\n // Produce a number between 0 and 2.\n let n = sin(frameCount * 0.01) + 1;\n\n // Use n to set the playback speed.\n dragon.speed(n);\n\n // Get the current speed and display it.\n let s = dragon.speed();\n\n // Round s to 1 decimal place for display.\n s = round(s, 1);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the speed.\n text(`Speed: ${s}`, 50, 50);\n}\n
"]]],"isConstructor":[0,false],"path":[0,"p5.MediaElement/speed"]}],"render":[0,null]}],[0,{"id":[0,"en/p5.MediaElement/src.mdx"],"slug":[0,"en/p5mediaelement/src"],"body":[0,"\n\n# src\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"src"],"module":[0,"DOM"],"submodule":[0,"DOM"],"file":[0,"src/dom/dom.js"],"description":[0,"Path to the media element's source as a string.
\n"],"line":[0,4158],"itemtype":[0,"property"],"class":[0,"p5.MediaElement"],"example":[1,[[0,"\n\nlet beat;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('/assets/beat.mp3');\n\n describe('The text \"https://p5js.org/reference//assets/beat.mp3\" written in black on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n textWrap(CHAR);\n text(beat.src, 10, 10, 80, 80);\n}\n
\nStops a media element and sets its current time to 0.
\nCalling media.play()
will restart playing audio/video from the beginning.
\nlet beat;\nlet isStopped = true;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n beat = createAudio('/assets/beat.mp3');\n\n describe('The text \"Click to start\" written in black on a gray background. The beat starts or stops when the user presses the mouse.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display different instructions based on playback.\n if (isStopped === true) {\n text('Click to start', 50, 50);\n } else {\n text('Click to stop', 50, 50);\n }\n}\n\n// Adjust playback when the user presses the mouse.\nfunction mousePressed() {\n if (isStopped === true) {\n // If the beat is stopped, play it.\n beat.play();\n isStopped = false;\n } else {\n // If the beat is playing, stop it.\n beat.stop();\n isStopped = true;\n }\n}\n
\nSets the media element's playback time.
\nThe parameter, time
, is optional. It's a number that specifies the\ntime, in seconds, to jump to when playback begins.
Calling media.time()
without an argument returns the number of seconds\nthe audio/video has played.
Note: Time resets to 0 when looping media restarts.
\n"],"line":[0,4766],"overloads":[1,[[0,{"params":[1,[]]}],[0,{"params":[1,[[0,{"name":[0,"time"],"description":[0,"time to jump to (in seconds).
\n"],"type":[0,"Number"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,false],"return":[0,{"description":[0,"current time (in seconds)."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nlet dragon;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n dragon = createAudio('/assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n describe('The text \"S seconds\" on a gray square with media controls beneath it. The number \"S\" increases as the song plays.');\n}\n\nfunction draw() {\n background(200);\n\n // Get the current playback time.\n let s = dragon.time();\n\n // Round s to 1 decimal place for display.\n s = round(s, 1);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the playback time.\n text(`${s} seconds`, 50, 50);\n}\n
\n\nlet dragon;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n dragon = createAudio('/assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n // Jump to 2 seconds to start.\n dragon.time(2);\n\n describe('The text \"S seconds\" on a gray square with media controls beneath it. The number \"S\" increases as the song plays.');\n}\n\nfunction draw() {\n background(200);\n\n // Get the current playback time.\n let s = dragon.time();\n\n // Round s to 1 decimal place for display.\n s = round(s, 1);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the playback time.\n text(`${s} seconds`, 50, 50);\n}\n
\nSets the audio/video volume.
\nCalling media.volume()
without an argument returns the current volume\nas a number in the range 0 (off) to 1 (maximum).
The parameter, val
, is optional. It's a number that sets the volume\nfrom 0 (off) to 1 (maximum). For example, calling media.volume(0.5)
\nsets the volume to half of its maximum.
volume between 0.0 and 1.0.
\n"],"type":[0,"Number"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.MediaElement"],"chainable":[0,false],"return":[0,{"description":[0,"current volume."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nlet dragon;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.MediaElement using createAudio().\n dragon = createAudio('/assets/lucky_dragons.mp3');\n\n // Show the default media controls.\n dragon.showControls();\n\n describe('The text \"Volume: V\" on a gray square with media controls beneath it. The number \"V\" oscillates between 0 and 1 as the music plays.');\n}\n\nfunction draw() {\n background(200);\n\n // Produce a number between 0 and 1.\n let n = 0.5 * sin(frameCount * 0.01) + 0.5;\n\n // Use n to set the volume.\n dragon.volume(n);\n\n // Get the current volume and display it.\n let v = dragon.volume();\n\n // Round v to 1 decimal place for display.\n v = round(v, 1);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the volume.\n text(`Volume: ${v}`, 50, 50);\n}\n
\nAdds a value to the end of an array. Extends the length of\nthe array by one. Maps to Array.push().
\n"],"line":[0,10],"params":[1,[[0,{"name":[0,"array"],"description":[0,"Array to append
\n"],"type":[0,"Array"]}],[0,{"name":[0,"value"],"description":[0,"to be added to the Array
\n"],"type":[0,"Any"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"the array that was appended to"],"type":[0,"Array"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myArray = ['Mango', 'Apple', 'Papaya'];\n print(myArray); // ['Mango', 'Apple', 'Papaya']\n\n append(myArray, 'Peach');\n print(myArray); // ['Mango', 'Apple', 'Papaya', 'Peach']\n}\n
Copies an array (or part of an array) to another array. The src array is\ncopied to the dst array, beginning at the position specified by\nsrcPosition and into the position specified by dstPosition. The number of\nelements to copy is determined by length. Note that copying values\noverwrites existing values in the destination array. To append values\ninstead of overwriting them, use concat().
\nThe simplified version with only two arguments, arrayCopy(src, dst),\ncopies an entire array to another of the same size. It is equivalent to\narrayCopy(src, 0, dst, 0, src.length).
\nUsing this function is far more efficient for copying array data than\niterating through a for() loop and copying each element individually.
\n"],"line":[0,35],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"src"],"description":[0,"the source Array
\n"],"type":[0,"Array"]}],[0,{"name":[0,"srcPosition"],"description":[0,"starting position in the source Array
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"dst"],"description":[0,"the destination Array
\n"],"type":[0,"Array"]}],[0,{"name":[0,"dstPosition"],"description":[0,"starting position in the destination Array
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"length"],"description":[0,"number of Array elements to be copied
\n"],"type":[0,"Integer"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"src"],"description":[0,""],"type":[0,"Array"]}],[0,{"name":[0,"dst"],"description":[0,""],"type":[0,"Array"]}],[0,{"name":[0,"length"],"description":[0,""],"type":[0,"Integer"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nlet src = ['A', 'B', 'C'];\nlet dst = [1, 2, 3];\nlet srcPosition = 1;\nlet dstPosition = 0;\nlet length = 2;\n\nprint(src); // ['A', 'B', 'C']\nprint(dst); // [ 1 , 2 , 3 ]\n\narrayCopy(src, srcPosition, dst, dstPosition, length);\nprint(dst); // ['B', 'C', 3]\n
Concatenates two arrays, maps to Array.concat(). Does not modify the\ninput arrays.
\n"],"line":[0,112],"params":[1,[[0,{"name":[0,"a"],"description":[0,"first Array to concatenate
\n"],"type":[0,"Array"]}],[0,{"name":[0,"b"],"description":[0,"second Array to concatenate
\n"],"type":[0,"Array"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"concatenated array"],"type":[0,"Array"]}],"example":[1,[[0,"\n\nfunction setup() {\n let arr1 = ['A', 'B', 'C'];\n let arr2 = [1, 2, 3];\n\n print(arr1); // ['A','B','C']\n print(arr2); // [1,2,3]\n\n let arr3 = concat(arr1, arr2);\n\n print(arr1); // ['A','B','C']\n print(arr2); // [1, 2, 3]\n print(arr3); // ['A','B','C', 1, 2, 3]\n}\n
Reverses the order of an array, maps to Array.reverse()
\n"],"line":[0,141],"params":[1,[[0,{"name":[0,"list"],"description":[0,"Array to reverse
\n"],"type":[0,"Array"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"the reversed list"],"type":[0,"Array"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myArray = ['A', 'B', 'C'];\n print(myArray); // ['A','B','C']\n\n reverse(myArray);\n print(myArray); // ['C','B','A']\n}\n
Decreases an array by one element and returns the shortened array,\nmaps to Array.pop().
\n"],"line":[0,161],"params":[1,[[0,{"name":[0,"list"],"description":[0,"Array to shorten
\n"],"type":[0,"Array"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"shortened Array"],"type":[0,"Array"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myArray = ['A', 'B', 'C'];\n print(myArray); // ['A', 'B', 'C']\n let newArray = shorten(myArray);\n print(myArray); // ['A','B','C']\n print(newArray); // ['A','B']\n}\n
Shuffles the elements of an array.
\nThe first parameter, array
, is the array to be shuffled. For example,\ncalling shuffle(myArray)
will shuffle the elements of myArray
. By\ndefault, the original array won’t be modified. Instead, a copy will be\ncreated, shuffled, and returned.
The second parameter, modify
, is optional. If true
is passed, as in\nshuffle(myArray, true)
, then the array will be shuffled in place without\nmaking a copy.
array to shuffle.
\n"],"type":[0,"Array"]}],[0,{"name":[0,"bool"],"description":[0,"if true
, shuffle the original array in place. Defaults to false
.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of colors.\n let colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];\n\n // Create a shuffled copy of the array.\n let shuffledColors = shuffle(colors);\n\n // Draw a row of circles using the original array.\n for (let i = 0; i < colors.length; i += 1) {\n // Calculate the x-coordinate.\n let x = (i + 1) * 12.5;\n\n // Style the circle.\n let c = colors[i];\n fill(c);\n\n // Draw the circle.\n circle(x, 33, 10);\n }\n\n // Draw a row of circles using the original array.\n for (let i = 0; i < shuffledColors.length; i += 1) {\n // Calculate the x-coordinate.\n let x = (i + 1) * 12.5;\n\n // Style the circle.\n let c = shuffledColors[i];\n fill(c);\n\n // Draw the circle.\n circle(x, 67, 10);\n }\n\n describe(\n 'Two rows of circles on a gray background. The top row follows the color sequence ROYGBIV. The bottom row has all the same colors but they are shuffled.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of colors.\n let colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];\n\n // Shuffle the array.\n shuffle(colors, true);\n\n // Draw a row of circles using the original array.\n for (let i = 0; i < colors.length; i += 1) {\n // Calculate the x-coordinate.\n let x = (i + 1) * 12.5;\n\n // Style the circle.\n let c = colors[i];\n fill(c);\n\n // Draw the circle.\n circle(x, 50, 10);\n }\n\n describe(\n 'A row of colorful circles on a gray background. Their sequence changes each time the sketch runs.'\n );\n}\n
\nSorts an array of numbers from smallest to largest, or puts an array of\nwords in alphabetical order. The original array is not modified; a\nre-ordered array is returned. The count parameter states the number of\nelements to sort. For example, if there are 12 elements in an array and\ncount is set to 5, only the first 5 elements in the array will be sorted.
\n"],"line":[0,300],"params":[1,[[0,{"name":[0,"list"],"description":[0,"Array to sort
\n"],"type":[0,"Array"]}],[0,{"name":[0,"count"],"description":[0,"number of elements to sort, starting from 0
\n"],"type":[0,"Integer"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"the sorted list"],"type":[0,"Array"]}],"example":[1,[[0,"\n\nfunction setup() {\n let words = ['banana', 'apple', 'pear', 'lime'];\n print(words); // ['banana', 'apple', 'pear', 'lime']\n let count = 4; // length of array\n\n words = sort(words, count);\n print(words); // ['apple', 'banana', 'lime', 'pear']\n}\n
\nfunction setup() {\n let numbers = [2, 6, 1, 5, 14, 9, 8, 12];\n print(numbers); // [2, 6, 1, 5, 14, 9, 8, 12]\n let count = 5; // Less than the length of the array\n\n numbers = sort(numbers, count);\n print(numbers); // [1,2,5,6,14,9,8,12]\n}\n
Inserts a value or an array of values into an existing array. The first\nparameter specifies the initial array to be modified, and the second\nparameter defines the data to be inserted. The third parameter is an index\nvalue which specifies the array position from which to insert data.\n(Remember that array index numbering starts at zero, so the first position\nis 0, the second position is 1, and so on.)
\n"],"line":[0,346],"params":[1,[[0,{"name":[0,"list"],"description":[0,"Array to splice into
\n"],"type":[0,"Array"]}],[0,{"name":[0,"value"],"description":[0,"value to be spliced in
\n"],"type":[0,"Any"]}],[0,{"name":[0,"position"],"description":[0,"in the array from which to insert data
\n"],"type":[0,"Integer"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"the list"],"type":[0,"Array"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myArray = [0, 1, 2, 3, 4];\n let insArray = ['A', 'B', 'C'];\n print(myArray); // [0, 1, 2, 3, 4]\n print(insArray); // ['A','B','C']\n\n splice(myArray, insArray, 3);\n print(myArray); // [0,1,2,'A','B','C',3,4]\n}\n
Extracts an array of elements from an existing array. The list parameter\ndefines the array from which the elements will be copied, and the start\nand count parameters specify which elements to extract. If no count is\ngiven, elements will be extracted from the start to the end of the array.\nWhen specifying the start, remember that the first array element is 0.\nThis function does not change the source array.
\n"],"line":[0,381],"params":[1,[[0,{"name":[0,"list"],"description":[0,"Array to extract from
\n"],"type":[0,"Array"]}],[0,{"name":[0,"start"],"description":[0,"position to begin
\n"],"type":[0,"Integer"]}],[0,{"name":[0,"count"],"description":[0,"number of values to extract
\n"],"type":[0,"Integer"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"Array of extracted elements"],"type":[0,"Array"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myArray = [1, 2, 3, 4, 5];\n print(myArray); // [1, 2, 3, 4, 5]\n\n let sub1 = subset(myArray, 0, 3);\n let sub2 = subset(myArray, 2, 2);\n print(sub1); // [1,2,3]\n print(sub2); // [3,4]\n}\n
Convierte un número o una cadena de caracteres en su representación booleana. Para un número, cualquier valor distinto de cero (positivo o negativo) se evalúa como ‘true’ (verdadero), mientras que cero se evalúa como ‘false’ (falso). En una cadena de caracteres, el valor 'true' se evalúa como verdadero, mientras que cualquier otro valor se evalúa como ‘false’ (falso). Cuando se pasa un arreglo de valores numéricos o de cadena de caracteres, se devuelve un arreglo de booleanos de la misma longitud.
\n"],"line":[0,112],"params":[1,[[0,{"name":[0,"n"],"description":[0,"value to parse
\n"],"type":[0,"String|Boolean|Number|Array"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"boolean representation of value"],"type":[0,"Boolean"]}],"example":[1,[[0,"\n\nprint(boolean(0)); // false\nprint(boolean(1)); // true\nprint(boolean('true')); // true\nprint(boolean('abcd')); // false\nprint(boolean([0, 12, 'true'])); // [false, true, true]\n
Converts a Boolean
, String
, or Number
to its byte value.
byte()
converts a value to an integer (whole number) between -128 and\n127. Values greater than 127 wrap around while negative values are\nunchanged. For example, 128 becomes -128 and -129 remains the same.
The parameter, n
, is the value to convert. If n
is a Boolean, as in\nbyte(false)
or byte(true)
, the number 0 (false
) or 1 (true
) will be\nreturned. If n
is a string or number, as in byte('256')
or byte(256)
,\nthen the byte value will be returned. Decimal values are ignored. If an\narray is passed, as in byte([true, 123, '456'])
, then an array of byte\nvalues will be returned.
Note: If a value can't be converted to a number, as in byte('giraffe')
,\nthen the value NaN
(not a number) will be returned.
value to convert.
\n"],"type":[0,"String|Boolean|Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"ns"],"description":[0,"values to convert.
\n"],"type":[0,"Array"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted byte value."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a Boolean variable.\n let original = true;\n\n // Convert the Boolean to its byte value.\n let converted = byte(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} : ${converted}`, 50, 50);\n\n describe('The text \"true : 1\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let original = '256';\n\n // Convert the string to its byte value.\n let converted = byte(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} : ${converted}`, 50, 50);\n\n describe('The text \"256 : 0\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a number variable.\n let original = 256;\n\n // Convert the number to its byte value.\n let converted = byte(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} : ${converted}`, 50, 50);\n\n describe('The text \"256 : 0\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of values.\n let original = [false, '64', 383];\n\n // Convert the array elements to their byte values.\n let converted = byte(original);\n\n // Iterate over the converted array elements.\n for (let i = 0; i < converted.length; i += 1) {\n\n // Style the circle.\n fill(converted[i]);\n\n // Calculate the x-coordinate.\n let x = (i + 1) * 25;\n\n // Draw the circle.\n circle(x, 50, 20);\n }\n\n describe(\n 'Three gray circles on a gray background. The circles get lighter from left to right.'\n );\n}\n
\nConverts a Number
or String
to a single-character String
.
char()
converts numbers to their single-character string representations.
The parameter, n
, is the value to convert. If a number is passed, as in\nchar(65)
, the corresponding single-character string is returned. If a\nstring is passed, as in char('65')
, the string is converted to an integer\n(whole number) and the corresponding single-character string is returned.\nIf an array is passed, as in char([65, 66, 67])
, an array of\nsingle-character strings is returned.
See MDN\nfor more information about conversions.
\n"],"line":[0,612],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"n"],"description":[0,"value to convert.
\n"],"type":[0,"String|Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"ns"],"description":[0,"values to convert.
\n"],"type":[0,"Array"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted single-character string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a number variable.\n let original = 65;\n\n // Convert the number to a char.\n let converted = char(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} : ${converted}`, 50, 50);\n\n describe('The text \"65 : A\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let original = '65';\n\n // Convert the string to a char.\n let converted = char(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} : ${converted}`, 50, 50);\n\n describe('The text \"65 : A\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of numbers.\n let original = ['65', 66, '67'];\n\n // Convert the string to a char.\n let converted = char(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Iterate over elements of the converted array.\n for (let i = 0; i < converted.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Display the original and converted values.\n text(`${original[i]} : ${converted[i]}`, 50, y);\n }\n\n describe(\n 'The text \"65 : A\", \"66 : B\", and \"67 : C\" written on three separate lines. The text is in black on a gray background.'\n );\n}\n
\nConverts a String
to a floating point (decimal) Number
.
float()
converts strings that resemble numbers, such as '12.34'
, into\nnumbers.
The parameter, str
, is the string value to convert. For example, calling\nfloat('12.34')
returns the number 12.34
. If an array of strings is\npassed, as in float(['12.34', '56.78'])
, then an array of numbers will be\nreturned.
Note: If a string can't be converted to a number, as in float('giraffe')
,\nthen the value NaN
(not a number) will be returned.
string to convert.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"ns"],"description":[0,"array of strings to convert.
\n"],"type":[0,"String[]"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let original = '12.3';\n\n // Convert the string to a number.\n let converted = float(original);\n\n // Double the converted value.\n let twice = converted * 2;\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(12);\n\n // Display the original and converted values.\n text(`${original} × 2 = ${twice}`, 50, 50);\n\n describe('The text \"12.3 × 2 = 24.6\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of strings.\n let original = ['60', '30', '15'];\n\n // Convert the strings to numbers.\n let diameters = float(original);\n\n for (let d of diameters) {\n // Draw a circle.\n circle(50, 50, d);\n }\n\n describe('Three white, concentric circles on a gray background.');\n}\n
\nConverts a Number
to a String
with its hexadecimal value.
hex()
converts a number to a string with its hexadecimal number value.\nHexadecimal (hex) numbers are base-16, which means there are 16 unique\ndigits. Hex extends the numbers 0–9 with the letters A–F. For example, the\nnumber 11
(eleven) in base-10 is written as the letter B
in hex.
The first parameter, n
, is the number to convert. For example, hex(20)
,\nreturns the string '00000014'
. If an array is passed, as in\nhex([1, 10, 100])
, an array of hexadecimal strings is returned.
The second parameter, digits
, is optional. If a number is passed, as in\nhex(20, 2)
, it sets the number of hexadecimal digits to display. For\nexample, calling hex(20, 2)
returns the string '14'
.
value to convert.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"digits"],"description":[0,"number of digits to include.
\n"],"type":[0,"Number"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"ns"],"description":[0,"values to convert.
\n"],"type":[0,"Number[]"]}],[0,{"name":[0,"digits"],"description":[0,""],"type":[0,"Number"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted hexadecimal value."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a number variable.\n let original = 20;\n\n // Convert the number to a hex string.\n let converted = hex(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Display the original and converted values.\n text(`${original} = ${converted}`, 50, 50);\n\n describe('The text \"20 = 00000014\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a number variable.\n let original = 20;\n\n // Convert the number to a hex string.\n // Only display two hex digits.\n let converted = hex(original, 2);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} = ${converted}`, 50, 50);\n\n describe('The text \"20 = 14\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of numbers.\n let original = [1, 10, 100];\n\n // Convert the numbers to hex strings.\n // Only use two hex digits.\n let converted = hex(original, 2);\n\n // Style the text.\n textAlign(RIGHT, CENTER);\n textSize(16);\n\n // Iterate over the converted values.\n for (let i = 0; i < converted.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Display the original and converted values.\n text(`${ original[i]} = ${converted[i]}`, 75, y);\n }\n\n describe(\n 'The text \"1 = 01\", \"10 = 0A\", and \"100 = 64\" written on three separate lines. The text is in black on a gray background.'\n );\n}\n
\nConverts a Boolean
, String
, or decimal Number
to an integer.
int()
converts values to integers. Integers are positive or negative\nnumbers without decimals. If the original value has decimals, as in -34.56,\nthey're removed to produce an integer such as -34.
The parameter, n
, is the value to convert. If n
is a Boolean, as in\nint(false)
or int(true)
, then the number 0 (false
) or 1 (true
) will\nbe returned. If n
is a string or number, as in int('45')
or\nint(67.89)
, then an integer will be returned. If an array is passed, as\nin int([12.34, 56.78])
, then an array of integers will be returned.
Note: If a value can't be converted to a number, as in int('giraffe')
,\nthen the value NaN
(not a number) will be returned.
value to convert.
\n"],"type":[0,"String|Boolean|Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"ns"],"description":[0,"values to convert.
\n"],"type":[0,"Array"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a Boolean variable.\n let original = false;\n\n // Convert the Boolean to an integer.\n let converted = int(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} : ${converted}`, 50, 50);\n\n describe('The text \"false : 0\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let original = '12.34';\n\n // Convert the string to an integer.\n let converted = int(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Display the original and converted values.\n text(`${original} ≈ ${converted}`, 50, 50);\n\n describe('The text \"12.34 ≈ 12\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a decimal number variable.\n let original = 12.34;\n\n // Convert the decimal number to an integer.\n let converted = int(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Display the original and converted values.\n text(`${original} ≈ ${converted}`, 50, 50);\n\n describe('The text \"12.34 ≈ 12\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of strings.\n let original = ['60', '30', '15'];\n\n // Convert the strings to integers.\n let diameters = int(original);\n\n for (let d of diameters) {\n // Draw a circle.\n circle(50, 50, d);\n }\n\n describe('Three white, concentric circles on a gray background.');\n}\n
\nConverts a Boolean
or Number
to String
.
str()
converts values to strings. See the\nString reference page for guidance on using\ntemplate literals instead.
The parameter, n
, is the value to convert. If n
is a Boolean, as in\nstr(false)
or str(true)
, then the value will be returned as a string,\nas in 'false'
or 'true'
. If n
is a number, as in str(123)
, then its\nvalue will be returned as a string, as in '123'
. If an array is passed,\nas in str([12.34, 56.78])
, then an array of strings will be returned.
value to convert.
\n"],"type":[0,"String|Boolean|Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a Boolean variable.\n let original = false;\n\n // Convert the Boolean to a string.\n let converted = str(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} : ${converted}`, 50, 50);\n\n describe('The text \"false : false\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a number variable.\n let original = 123;\n\n // Convert the number to a string.\n let converted = str(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} = ${converted}`, 50, 50);\n\n describe('The text \"123 = 123\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of numbers.\n let original = [12, 34, 56];\n\n // Convert the numbers to strings.\n let strings = str(original);\n\n // Create an empty string variable.\n let final = '';\n\n // Concatenate all the strings.\n for (let s of strings) {\n final += s;\n }\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the concatenated string.\n text(final, 50, 50);\n\n describe('The text \"123456\" written in black on a gray background.');\n}\n
\nConverts a single-character String
to a Number
.
unchar()
converts single-character strings to their corresponding\ninteger (whole number).
The parameter, n
, is the character to convert. For example,\nunchar('A')
, returns the number 65. If an array is passed, as in\nunchar(['A', 'B', 'C'])
, an array of integers is returned.
value to convert.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"ns"],"description":[0,"values to convert.
\n"],"type":[0,"String[]"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let original = 'A';\n\n // Convert the string to a number.\n let converted = unchar(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} : ${converted}`, 50, 50);\n\n describe('The text \"A : 65\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of characters.\n let original = ['A', 'B', 'C'];\n\n // Convert the string to a number.\n let converted = unchar(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Iterate over elements of the converted array.\n for (let i = 0; i < converted.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Display the original and converted values.\n text(`${original[i]} : ${converted[i]}`, 50, y);\n }\n\n describe(\n 'The text \"A : 65\", \"B : 66\", and \"C :67\" written on three separate lines. The text is in black on a gray background.'\n );\n}\n
\nConverts a String
with a hexadecimal value to a Number
.
unhex()
converts a string with its hexadecimal number value to a number.\nHexadecimal (hex) numbers are base-16, which means there are 16 unique\ndigits. Hex extends the numbers 0–9 with the letters A–F. For example, the\nnumber 11
(eleven) in base-10 is written as the letter B
in hex.
The first parameter, n
, is the hex string to convert. For example,\nunhex('FF')
, returns the number 255. If an array is passed, as in\nunhex(['00', '80', 'FF'])
, an array of numbers is returned.
value to convert.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"ns"],"description":[0,"values to convert.
\n"],"type":[0,"String[]"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"converted number."],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a a hex string variable\n let original = 'FF';\n\n // Convert the hex string to a number.\n let converted = unhex(original);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the original and converted values.\n text(`${original} = ${converted}`, 50, 50);\n\n describe('The text \"FF = 255\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of numbers.\n let original = ['00', '80', 'FF'];\n\n // Convert the numbers to hex strings.\n // Only use two hex digits.\n let converted = unhex(original, 2);\n\n // Style the text.\n textAlign(RIGHT, CENTER);\n textSize(16);\n\n // Iterate over the converted values.\n for (let i = 0; i < converted.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Display the original and converted values.\n text(`${ original[i]} = ${converted[i]}`, 80, y);\n }\n\n describe(\n 'The text \"00 = 0\", \"80 = 128\", and \"FF = 255\" written on three separate lines. The text is in black on a gray background.'\n );\n}\n
\nCreates a new instance of p5.NumberDict using the key-value pair\n or object you provide.
\n"],"line":[0,48],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"key"],"description":[0,""],"type":[0,"Number"]}],[0,{"name":[0,"value"],"description":[0,""],"type":[0,"Number"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"object"],"description":[0,"object
\n"],"type":[0,"Object"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"p5.NumberDict"]}],"example":[1,[[0,"\n\n function setup() {\n let myDictionary = createNumberDict(100, 42);\n print(myDictionary.hasKey(100)); // logs true to console\n let anotherDictionary = createNumberDict({ 200: 84 });\n print(anotherDictionary.hasKey(200)); // logs true to console\n }\n
Creates a new instance of p5.StringDict using the key-value pair\n or the object you provide.
\n"],"line":[0,14],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"key"],"description":[0,""],"type":[0,"String"]}],[0,{"name":[0,"value"],"description":[0,""],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"object"],"description":[0,"object
\n"],"type":[0,"Object"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"p5.StringDict"]}],"example":[1,[[0,"\n\n function setup() {\n let myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n let anotherDictionary = createStringDict({ happy: 'coding' });\n print(anotherDictionary.hasKey('happy')); // logs true to console\n }\n
A simple Dictionary class for Strings.
\n"],"line":[0,397],"path":[0,"p5/p5.StringDict"]}],"render":[0,null]}]]]}],[0,{"name":[0,"LocalStorage"],"entry":[0],"entries":[1,[[0,{"id":[0,"en/p5/clearStorage.mdx"],"slug":[0,"en/p5/clearstorage"],"body":[0,"\n\n# clearStorage\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"clearStorage()"],"module":[0,"Data"],"submodule":[0,"LocalStorage"],"file":[0,"src/data/local_storage.js"],"description":[0,"Removes all items in the web browser's local storage.
\nWeb browsers can save small amounts of data using the built-in\nlocalStorage object.\nData stored in localStorage
can be retrieved at any point, even after\nrefreshing a page or restarting the browser. Data are stored as key-value\npairs. Calling clearStorage()
removes all data from localStorage
.
Note: Sensitive data such as passwords or personal information shouldn't be\nstored in localStorage
.
\n// Double-click to clear localStorage.\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Store the player's name.\n storeItem('name', 'Feist');\n\n // Store the player's score.\n storeItem('score', 1234);\n\n describe(\n 'The text \"Feist: 1234\" written in black on a gray background. The text \"null: null\" appears when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Retrieve the name.\n let name = getItem('name');\n\n // Retrieve the score.\n let score = getItem('score');\n\n // Display the score.\n text(`${name}: ${score}`, 50, 50);\n}\n\n// Clear localStorage when the user double-clicks.\nfunction doubleClicked() {\n clearStorage();\n}\n
\nReturns a value in the web browser's local storage.
\nWeb browsers can save small amounts of data using the built-in\nlocalStorage object.\nData stored in localStorage
can be retrieved at any point, even after\nrefreshing a page or restarting the browser. Data are stored as key-value\npairs.
storeItem() makes it easy to store values in\nlocalStorage
and getItem()
makes it easy to retrieve them.
The first parameter, key
, is the name of the value to be stored as a\nstring.
The second parameter, value
, is the value to be retrieved a string. For\nexample, calling getItem('size')
retrieves the value with the key size
.
Note: Sensitive data such as passwords or personal information shouldn't be\nstored in localStorage
.
name of the value.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"stored item."],"type":[0,"String|Number|Boolean|Object|Array"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Store the player's name.\n storeItem('name', 'Feist');\n\n // Store the player's score.\n storeItem('score', 1234);\n\n describe('The text \"Feist: 1234\" written in black on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Retrieve the name.\n let name = getItem('name');\n\n // Retrieve the score.\n let score = getItem('score');\n\n // Display the score.\n text(`${name}: ${score}`, 50, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create an object.\n let p = { x: 50, y: 50 };\n\n // Store the object.\n storeItem('position', p);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Retrieve the object.\n let p = getItem('position');\n\n // Draw the circle.\n circle(p.x, p.y, 30);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create a p5.Color object.\n let c = color('deeppink');\n\n // Store the object.\n storeItem('color', c);\n\n describe('A pink circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Retrieve the object.\n let c = getItem('color');\n\n // Style the circle.\n fill(c);\n\n // Draw the circle.\n circle(50, 50, 30);\n}\n
\nRemoves an item from the web browser's local storage.
\nWeb browsers can save small amounts of data using the built-in\nlocalStorage object.\nData stored in localStorage
can be retrieved at any point, even after\nrefreshing a page or restarting the browser. Data are stored as key-value\npairs.
storeItem() makes it easy to store values in\nlocalStorage
and removeItem()
makes it easy to delete them.
The parameter, key
, is the name of the value to remove as a string. For\nexample, calling removeItem('size')
removes the item with the key size
.
Note: Sensitive data such as passwords or personal information shouldn't be\nstored in localStorage
.
name of the value to remove.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Double-click to remove an item from localStorage.\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Store the player's name.\n storeItem('name', 'Feist');\n\n // Store the player's score.\n storeItem('score', 1234);\n\n describe(\n 'The text \"Feist: 1234\" written in black on a gray background. The text \"Feist: null\" appears when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Retrieve the name.\n let name = getItem('name');\n\n // Retrieve the score.\n let score = getItem('score');\n\n // Display the score.\n text(`${name}: ${score}`, 50, 50);\n}\n\n// Remove the word from localStorage when the user double-clicks.\nfunction doubleClicked() {\n removeItem('score');\n}\n
\nStores a value in the web browser's local storage.
\nWeb browsers can save small amounts of data using the built-in\nlocalStorage object.\nData stored in localStorage
can be retrieved at any point, even after\nrefreshing a page or restarting the browser. Data are stored as key-value\npairs.
storeItem()
makes it easy to store values in localStorage
and\ngetItem() makes it easy to retrieve them.
The first parameter, key
, is the name of the value to be stored as a\nstring.
The second parameter, value
, is the value to be stored. Values can have\nany type.
Note: Sensitive data such as passwords or personal information shouldn't be\nstored in localStorage
.
name of the value.
\n"],"type":[0,"String"]}],[0,{"name":[0,"value"],"description":[0,"value to be stored.
\n"],"type":[0,"String|Number|Boolean|Object|Array"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Store the player's name.\n storeItem('name', 'Feist');\n\n // Store the player's score.\n storeItem('score', 1234);\n\n describe('The text \"Feist: 1234\" written in black on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Retrieve the name.\n let name = getItem('name');\n\n // Retrieve the score.\n let score = getItem('score');\n\n // Display the score.\n text(`${name}: ${score}`, 50, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create an object.\n let p = { x: 50, y: 50 };\n\n // Store the object.\n storeItem('position', p);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Retrieve the object.\n let p = getItem('position');\n\n // Draw the circle.\n circle(p.x, p.y, 30);\n}\n
\nCombines an array of strings into one string.
\nThe first parameter, list
, is the array of strings to join.
The second parameter, separator
, is the character(s) that should be used\nto separate the combined strings. For example, calling\njoin(myWords, ' : ')
would return a string of words each separated by a\ncolon and spaces.
array of strings to combine.
\n"],"type":[0,"Array"]}],[0,{"name":[0,"separator"],"description":[0,"character(s) to place between strings when they're combined.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"combined string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of strings.\n let myWords = ['one', 'two', 'three'];\n\n // Create a combined string\n let combined = join(myWords, ' : ');\n\n // Style the text.\n textAlign(CENTER, CENTER);\n\n // Display the combined string.\n text(combined, 50, 50);\n\n describe('The text \"one : two : three\" written in black on a gray canvas.');\n}\n
\nApplies a regular expression to a string and returns an array with the\nfirst match.
\nmatch()
uses regular expressions (regex) to match patterns in text. For\nexample, the regex abc
can be used to search a string for the exact\nsequence of characters abc
. See\nMDN.\nfor more information about regexes.
The first parameter, str
, is the string to search.
The second parameter, regex
, is a string with the regular expression to\napply. For example, calling match('Hello, p5*js!', '[a-z][0-9]')
would\nreturn the array ['p5']
.
Note: If no matches are found, null
is returned.
string to search.
\n"],"type":[0,"String"]}],[0,{"name":[0,"regexp"],"description":[0,"regular expression to match.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"match if found."],"type":[0,"String[]"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let string = 'Hello, p5*js!';\n\n // Match the characters that are lowercase\n // letters followed by digits.\n let matches = match(string, '[a-z][0-9]');\n\n // Print the matches array to the console:\n // ['p5']\n print(matches);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the matches.\n text(matches, 50, 50);\n\n describe('The text \"p5\" written in black on a gray canvas.');\n}\n
\nApplies a regular expression to a string and returns an array of matches.
\nmatch()
uses regular expressions (regex) to match patterns in text. For\nexample, the regex abc
can be used to search a string for the exact\nsequence of characters abc
. See\nMDN.\nfor more information about regexes. matchAll()
is different from\nmatch() because it returns every match, not just\nthe first.
The first parameter, str
, is the string to search.
The second parameter, regex
, is a string with the regular expression to\napply. For example, calling\nmatchAll('p5*js is easier than abc123', '[a-z][0-9]')
would return the\n2D array [['p5'], ['c1']]
.
Note: If no matches are found, an empty array []
is returned.
string to search.
\n"],"type":[0,"String"]}],[0,{"name":[0,"regexp"],"description":[0,"regular expression to match.
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"matches found."],"type":[0,"String[]"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let string = 'p5*js is easier than abc123';\n\n // Match the character sequences that are\n // lowercase letters followed by digits.\n let matches = matchAll(string, '[a-z][0-9]');\n\n // Print the matches array to the console:\n // [['p5'], ['c1']]\n print(matches);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Iterate over the matches array.\n for (let i = 0; i < matches.length; i += 1) {\n\n // Calculate the y-coordainate.\n let y = (i + 1) * 33;\n\n // Display the match.\n text(matches[i], 50, y);\n }\n\n describe(\n 'The text \"p5\" and \"c1\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\nConverts a Number
into a String
with a given number of digits.
nf()
converts numbers such as 123.45
into strings formatted with a set\nnumber of digits, as in '123.4500'
.
The first parameter, num
, is the number to convert to a string. For\nexample, calling nf(123.45)
returns the string '123.45'
. If an array of\nnumbers is passed, as in nf([123.45, 67.89])
, an array of formatted\nstrings will be returned.
The second parameter, left
, is optional. If a number is passed, as in\nnf(123.45, 4)
, it sets the minimum number of digits to include to the\nleft of the decimal place. If left
is larger than the number of digits in\nnum
, then unused digits will be set to 0. For example, calling\nnf(123.45, 4)
returns the string '0123.45'
.
The third parameter, right
, is also optional. If a number is passed, as\nin nf(123.45, 4, 1)
, it sets the minimum number of digits to include to\nthe right of the decimal place. If right
is smaller than the number of\ndecimal places in num
, then num
will be rounded to the given number of\ndecimal places. For example, calling nf(123.45, 4, 1)
returns the string\n'0123.5'
. If right is larger than the number of decimal places in num
,\nthen unused decimal places will be set to 0. For example, calling\nnf(123.45, 4, 3)
returns the string '0123.450'
.
When the number is negative, for example, calling nf(-123.45, 5, 2)
\nreturns the string '-00123.45'
.
number to format.
\n"],"type":[0,"Number|String"]}],[0,{"name":[0,"left"],"description":[0,"number of digits to include to the left of\n the decimal point.
\n"],"type":[0,"Integer|String"],"optional":[0,true]}],[0,{"name":[0,"right"],"description":[0,"number of digits to include to the right\n of the decimal point.
\n"],"type":[0,"Integer|String"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"nums"],"description":[0,"numbers to format.
\n"],"type":[0,"Number[]"]}],[0,{"name":[0,"left"],"description":[0,""],"type":[0,"Integer|String"],"optional":[0,true]}],[0,{"name":[0,"right"],"description":[0,""],"type":[0,"Integer|String"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"formatted string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(16);\n\n // Create a number variable.\n let number = 123.45;\n\n // Display the number as a string.\n let formatted = nf(number);\n text(formatted, 20, 20);\n\n let negative = nf(-number, 4, 2);\n text(negative, 20, 40);\n\n // Display the number with four digits\n // to the left of the decimal.\n let left = nf(number, 4);\n text(left, 20, 60);\n\n // Display the number with four digits\n // to the left of the decimal and one\n // to the right.\n let right = nf(number, 4, 1);\n text(right, 20, 80);\n\n describe(\n 'The numbers \"123.45\", \"-0123.45\", \"0123.45\", and \"0123.5\" written on four separate lines. The text is in black on a gray background.'\n );\n}\n
\nConverts a Number
into a String
with commas to mark units of 1,000.
nfc()
converts numbers such as 12345 into strings formatted with commas\nto mark the thousands place, as in '12,345'
.
The first parameter, num
, is the number to convert to a string. For\nexample, calling nfc(12345)
returns the string '12,345'
.
The second parameter, right
, is optional. If a number is passed, as in\nnfc(12345, 1)
, it sets the minimum number of digits to include to the\nright of the decimal place. If right
is smaller than the number of\ndecimal places in num
, then num
will be rounded to the given number of\ndecimal places. For example, calling nfc(12345.67, 1)
returns the string\n'12,345.7'
. If right
is larger than the number of decimal places in\nnum
, then unused decimal places will be set to 0. For example, calling\nnfc(12345.67, 3)
returns the string '12,345.670'
.
number to format.
\n"],"type":[0,"Number|String"]}],[0,{"name":[0,"right"],"description":[0,"number of digits to include to the right\n of the decimal point.
\n"],"type":[0,"Integer|String"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"nums"],"description":[0,"numbers to format.
\n"],"type":[0,"Number[]"]}],[0,{"name":[0,"right"],"description":[0,""],"type":[0,"Integer|String"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"formatted string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(LEFT, CENTER);\n textSize(16);\n\n // Create a number variable.\n let number = 12345;\n\n // Display the number as a string.\n let commas = nfc(number);\n text(commas, 15, 33);\n\n // Display the number with four digits\n // to the left of the decimal.\n let decimals = nfc(number, 2);\n text(decimals, 15, 67);\n\n describe(\n 'The numbers \"12,345\" and \"12,345.00\" written on separate lines. The text is in black on a gray background.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of numbers.\n let numbers = [12345, 6789];\n\n // Convert the numbers to formatted strings.\n let formatted = nfc(numbers);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Iterate over the array.\n for (let i = 0; i < formatted.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 33;\n\n // Display the original and formatted numbers.\n text(`${numbers[i]} : ${formatted[i]}`, 50, y);\n }\n\n describe(\n 'The text \"12345 : 12,345\" and \"6789 : 6,789\" written on two separate lines. The text is in black on a gray background.'\n );\n}\n
\nConverts a Number
into a String
with a plus or minus sign.
nfp()
converts numbers such as 123 into strings formatted with a +
or\n-
symbol to mark whether they're positive or negative, as in '+123'
.
The first parameter, num
, is the number to convert to a string. For\nexample, calling nfp(123.45)
returns the string '+123.45'
. If an array\nof numbers is passed, as in nfp([123.45, -6.78])
, an array of formatted\nstrings will be returned.
The second parameter, left
, is optional. If a number is passed, as in\nnfp(123.45, 4)
, it sets the minimum number of digits to include to the\nleft of the decimal place. If left
is larger than the number of digits in\nnum
, then unused digits will be set to 0. For example, calling\nnfp(123.45, 4)
returns the string '+0123.45'
.
The third parameter, right
, is also optional. If a number is passed, as\nin nfp(123.45, 4, 1)
, it sets the minimum number of digits to include to\nthe right of the decimal place. If right
is smaller than the number of\ndecimal places in num
, then num
will be rounded to the given number of\ndecimal places. For example, calling nfp(123.45, 4, 1)
returns the\nstring '+0123.5'
. If right
is larger than the number of decimal places\nin num
, then unused decimal places will be set to 0. For example,\ncalling nfp(123.45, 4, 3)
returns the string '+0123.450'
.
number to format.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"left"],"description":[0,"number of digits to include to the left of the\n decimal point.
\n"],"type":[0,"Integer"],"optional":[0,true]}],[0,{"name":[0,"right"],"description":[0,"number of digits to include to the right of the\n decimal point.
\n"],"type":[0,"Integer"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"nums"],"description":[0,"numbers to format.
\n"],"type":[0,"Number[]"]}],[0,{"name":[0,"left"],"description":[0,""],"type":[0,"Integer"],"optional":[0,true]}],[0,{"name":[0,"right"],"description":[0,""],"type":[0,"Integer"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"formatted string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create number variables.\n let positive = 123;\n let negative = -123;\n\n // Convert the positive number to a formatted string.\n let p = nfp(positive);\n\n // Convert the negative number to a formatted string\n // with four digits to the left of the decimal\n // and two digits to the right of the decimal.\n let n = nfp(negative, 4, 2);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Display the original and formatted numbers.\n text(`${positive} : ${p}`, 50, 33);\n text(`${negative} : ${n}`, 50, 67);\n\n describe(\n 'The text \"123 : +123\" and \"-123 : -123.00\" written on separate lines. The text is in black on a gray background.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create number variables.\n let numbers = [123, -4.56];\n\n // Convert the numbers to formatted strings\n // with four digits to the left of the decimal\n // and one digit to the right of the decimal.\n let formatted = nfp(numbers, 4, 1);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(14);\n\n // Iterate over the array.\n for (let i = 0; i < formatted.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 33;\n\n // Display the original and formatted numbers.\n text(`${numbers[i]} : ${formatted[i]}`, 50, y);\n }\n\n describe(\n 'The text \"123 : +0123.0\" and \"-4.56 : 00-4.6\" written on separate lines. The text is in black on a gray background.'\n );\n}\n
\nConverts a positive Number
into a String
with an extra space in front.
nfs()
converts positive numbers such as 123.45 into strings formatted\nwith an extra space in front, as in ' 123.45'. Doing so can be helpful for\naligning positive and negative numbers.
The first parameter, num
, is the number to convert to a string. For\nexample, calling nfs(123.45)
returns the string ' 123.45'
.
The second parameter, left
, is optional. If a number is passed, as in\nnfs(123.45, 4)
, it sets the minimum number of digits to include to the\nleft of the decimal place. If left
is larger than the number of digits in\nnum
, then unused digits will be set to 0. For example, calling\nnfs(123.45, 4)
returns the string ' 0123.45'
.
The third parameter, right
, is also optional. If a number is passed, as\nin nfs(123.45, 4, 1)
, it sets the minimum number of digits to include to\nthe right of the decimal place. If right
is smaller than the number of\ndecimal places in num
, then num
will be rounded to the given number of\ndecimal places. For example, calling nfs(123.45, 4, 1)
returns the\nstring ' 0123.5'
. If right
is larger than the number of decimal places\nin num
, then unused decimal places will be set to 0. For example,\ncalling nfs(123.45, 4, 3)
returns the string ' 0123.450'
.
number to format.
\n"],"type":[0,"Number"]}],[0,{"name":[0,"left"],"description":[0,"number of digits to include to the left of the\n decimal point.
\n"],"type":[0,"Integer"],"optional":[0,true]}],[0,{"name":[0,"right"],"description":[0,"number of digits to include to the right of the\n decimal point.
\n"],"type":[0,"Integer"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"nums"],"description":[0,"numbers to format.
\n"],"type":[0,"Array"]}],[0,{"name":[0,"left"],"description":[0,""],"type":[0,"Integer"],"optional":[0,true]}],[0,{"name":[0,"right"],"description":[0,""],"type":[0,"Integer"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"formatted string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create number variables.\n let positive = 123;\n let negative = -123;\n\n // Convert the positive number to a formatted string.\n let formatted = nfs(positive);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(16);\n\n // Display the negative number and the formatted positive number.\n text(negative, 50, 33);\n text(formatted, 50, 67);\n\n describe(\n 'The numbers -123 and 123 written on separate lines. The numbers align vertically. The text is in black on a gray background.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a number variable.\n let number = 123.45;\n\n // Convert the positive number to a formatted string.\n // Use four digits to the left of the decimal and\n // one digit to the right.\n let formatted = nfs(number, 4, 1);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(16);\n\n // Display a negative version of the number and\n // the formatted positive version.\n text('-0123.5', 50, 33);\n text(formatted, 50, 67);\n\n describe(\n 'The numbers \"-0123.5\" and \"0123.5\" written on separate lines. The numbers align vertically. The text is in black on a gray background.'\n );\n}\n
\nSplits a String
into pieces and returns an array containing the pieces.
The first parameter, value
, is the string to split.
The second parameter, delim
, is the character(s) that should be used to\nsplit the string. For example, calling\nsplit('rock...paper...scissors', '...')
would return the array\n['rock', 'paper', 'scissors']
because there are three periods ...
\nbetween each word.
the String to be split
\n"],"type":[0,"String"]}],[0,{"name":[0,"delim"],"description":[0,"the String used to separate the data
\n"],"type":[0,"String"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"Array of Strings"],"type":[0,"String[]"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let string = 'rock...paper...scissors';\n\n // Split the string at each ...\n let words = split(string, '...');\n\n // Print the array to the console:\n // [\"rock\", \"paper\", \"scissors\"]\n print(words);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(16);\n\n // Iterate over the words array.\n for (let i = 0; i < words.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 25;\n\n // Display the word.\n text(words[i], 50, y);\n }\n\n describe(\n 'The words \"rock\", \"paper\", and \"scissors\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\nSplits a String
into pieces and returns an array containing the pieces.
splitTokens()
is an enhanced version of\nsplit(). It can split a string when any characters\nfrom a list are detected.
The first parameter, value
, is the string to split.
The second parameter, delim
, is optional. It sets the character(s) that\nshould be used to split the string. delim
can be a single string, as in\nsplitTokens('rock...paper...scissors...shoot', '...')
, or an array of\nstrings, as in\nsplitTokens('rock;paper,scissors...shoot, [';', ',', '...'])
. By default,\nif no delim
characters are specified, then any whitespace character is\nused to split. Whitespace characters include tab (\\t
), line feed (\\n
),\ncarriage return (\\r
), form feed (\\f
), and space.
string to split.
\n"],"type":[0,"String"]}],[0,{"name":[0,"delim"],"description":[0,"character(s) to use for splitting the string.
\n"],"type":[0,"String"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"separated strings."],"type":[0,"String[]"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let string = 'rock paper scissors shoot';\n\n // Split the string at each space.\n let words = splitTokens(string);\n\n // Print the array to the console.\n print(words);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Iterate over the words array.\n for (let i = 0; i < words.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 20;\n\n // Display the word.\n text(words[i], 50, y);\n }\n\n describe(\n 'The words \"rock\", \"paper\", \"scissors\", and \"shoot\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let string = 'rock...paper...scissors...shoot';\n\n // Split the string at each ...\n let words = splitTokens(string, '...');\n\n // Print the array to the console.\n print(words);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Iterate over the words array.\n for (let i = 0; i < words.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 20;\n\n // Display the word.\n text(words[i], 50, y);\n }\n\n describe(\n 'The words \"rock\", \"paper\", \"scissors\", and \"shoot\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let string = 'rock;paper,scissors...shoot';\n\n // Split the string at each semicolon, comma, or ...\n let words = splitTokens(string, [';', ',', '...']);\n\n // Print the array to the console.\n print(words);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(12);\n\n // Iterate over the words array.\n for (let i = 0; i < words.length; i += 1) {\n\n // Calculate the y-coordinate.\n let y = (i + 1) * 20;\n\n // Display the word.\n text(words[i], 50, y);\n }\n\n describe(\n 'The words \"rock\", \"paper\", \"scissors\", and \"shoot\" written on separate lines. The text is black on a gray background.'\n );\n}\n
\nRemoves whitespace from the start and end of a String
without changing the middle.
trim()
trims\nwhitespace characters\nsuch as spaces, carriage returns, tabs, Unicode \"nbsp\" character.
The parameter, str
, is the string to trim. If a single string is passed,\nas in trim(' pad ')
, a single string is returned. If an array of\nstrings is passed, as in trim([' pad ', '\\n space \\n'])
, an array of\nstrings is returned.
string to trim.
\n"],"type":[0,"String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"strs"],"description":[0,"strings to trim.
\n"],"type":[0,"String[]"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"trimmed string."],"type":[0,"String"]}],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create a string variable.\n let string = ' p5*js ';\n\n // Trim the whitespace.\n let trimmed = trim(string);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the text.\n text(`Hello, ${trimmed}!`, 50, 50);\n\n describe('The text \"Hello, p5*js!\" written in black on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Create an array of strings.\n let strings = [' wide ', '\\n open ', '\\n spaces '];\n\n // Trim the whitespace.\n let trimmed = trim(strings);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(10);\n\n // Display the text.\n text(`${trimmed[0]} ${trimmed[1]} ${trimmed[2]}`, 50, 50);\n\n describe('The text \"wide open spaces\" written in black on a gray background.');\n}\n
\nA simple Dictionary class for Numbers.
\n"],"line":[0,415],"chainable":[0,false],"methods":[0,{"add":[0,{"description":[0,"Add the given number to the value currently stored at the given key.\nThe sum then replaces the value previously stored in the Dictionary.
\n"],"path":[0,"p5.NumberDict/add"]}],"sub":[0,{"description":[0,"Subtract the given number from the value currently stored at the given key.\nThe difference then replaces the value previously stored in the Dictionary.
\n"],"path":[0,"p5.NumberDict/sub"]}],"mult":[0,{"description":[0,"Multiply the given number with the value currently stored at the given key.\nThe product then replaces the value previously stored in the Dictionary.
\n"],"path":[0,"p5.NumberDict/mult"]}],"div":[0,{"description":[0,"Divide the given number with the value currently stored at the given key.\nThe quotient then replaces the value previously stored in the Dictionary.
\n"],"path":[0,"p5.NumberDict/div"]}],"minValue":[0,{"description":[0,"Return the lowest number currently stored in the Dictionary.
\n"],"path":[0,"p5.NumberDict/minValue"]}],"maxValue":[0,{"description":[0,"Return the highest number currently stored in the Dictionary.
\n"],"path":[0,"p5.NumberDict/maxValue"]}],"minKey":[0,{"description":[0,"Return the lowest key currently used in the Dictionary.
\n"],"path":[0,"p5.NumberDict/minKey"]}],"maxKey":[0,{"description":[0,"Return the highest key currently used in the Dictionary.
\n"],"path":[0,"p5.NumberDict/maxKey"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.NumberDict"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.NumberDict/add.mdx"],"slug":[0,"en/p5numberdict/add"],"body":[0,"\n\n# add\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"add()"],"module":[0,"Data"],"submodule":[0,"Dictionary"],"file":[0,"src/data/p5.TypedDict.js"],"description":[0,"Add the given number to the value currently stored at the given key.\nThe sum then replaces the value previously stored in the Dictionary.
\n"],"line":[0,439],"params":[1,[[0,{"name":[0,"Key"],"description":[0,"for the value you wish to add to
\n"],"type":[0,"Number"]}],[0,{"name":[0,"Number"],"description":[0,"to add to the value
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.NumberDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 5);\n myDictionary.add(2, 2);\n print(myDictionary.get(2)); // logs 7 to console.\n}\n
Divide the given number with the value currently stored at the given key.\nThe quotient then replaces the value previously stored in the Dictionary.
\n"],"line":[0,516],"params":[1,[[0,{"name":[0,"Key"],"description":[0,"for value you wish to divide
\n"],"type":[0,"Number"]}],[0,{"name":[0,"Amount"],"description":[0,"to divide the value by
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.NumberDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 8);\n myDictionary.div(2, 2);\n print(myDictionary.get(2)); // logs 4 to console.\n}\n
Return the highest key currently used in the Dictionary.
\n"],"line":[0,649],"itemtype":[0,"method"],"class":[0,"p5.NumberDict"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n let highestKey = myDictionary.maxKey(); // value is 4\n print(highestKey);\n}\n
Return the highest number currently stored in the Dictionary.
\n"],"line":[0,587],"itemtype":[0,"method"],"class":[0,"p5.NumberDict"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n let highestValue = myDictionary.maxValue(); // value is 3\n print(highestValue);\n}\n
Return the lowest key currently used in the Dictionary.
\n"],"line":[0,629],"itemtype":[0,"method"],"class":[0,"p5.NumberDict"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n let lowestKey = myDictionary.minKey(); // value is 1.2\n print(lowestKey);\n}\n
Return the lowest number currently stored in the Dictionary.
\n"],"line":[0,567],"itemtype":[0,"method"],"class":[0,"p5.NumberDict"],"chainable":[0,false],"return":[0,{"description":[0,""],"type":[0,"Number"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n let lowestValue = myDictionary.minValue(); // value is -10\n print(lowestValue);\n}\n
Multiply the given number with the value currently stored at the given key.\nThe product then replaces the value previously stored in the Dictionary.
\n"],"line":[0,489],"params":[1,[[0,{"name":[0,"Key"],"description":[0,"for value you wish to multiply
\n"],"type":[0,"Number"]}],[0,{"name":[0,"Amount"],"description":[0,"to multiply the value by
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.NumberDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 4);\n myDictionary.mult(2, 2);\n print(myDictionary.get(2)); // logs 8 to console.\n}\n
Subtract the given number from the value currently stored at the given key.\nThe difference then replaces the value previously stored in the Dictionary.
\n"],"line":[0,466],"params":[1,[[0,{"name":[0,"Key"],"description":[0,"for the value you wish to subtract from
\n"],"type":[0,"Number"]}],[0,{"name":[0,"Number"],"description":[0,"to subtract from the value
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5.NumberDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createNumberDict(2, 5);\n myDictionary.sub(2, 2);\n print(myDictionary.get(2)); // logs 3 to console.\n}\n
Base class for all p5.Dictionary types. Specifically\n typed Dictionary classes inherit from this class.
\n"],"line":[0,82],"chainable":[0,false],"methods":[0,{"size":[0,{"description":[0,"Returns the number of key-value pairs currently stored in the Dictionary.
\n"],"path":[0,"p5.TypedDict/size"]}],"hasKey":[0,{"description":[0,"Returns true if the given key exists in the Dictionary,\notherwise returns false.
\n"],"path":[0,"p5.TypedDict/hasKey"]}],"get":[0,{"description":[0,"Returns the value stored at the given key.
\n"],"path":[0,"p5.TypedDict/get"]}],"set":[0,{"description":[0,"Updates the value associated with the given key in case it already exists\nin the Dictionary. Otherwise a new key-value pair is added.
\n"],"path":[0,"p5.TypedDict/set"]}],"create":[0,{"description":[0,"Creates a new key-value pair in the Dictionary.
\n"],"path":[0,"p5.TypedDict/create"]}],"clear":[0,{"description":[0,"Removes all previously stored key-value pairs from the Dictionary.
\n"],"path":[0,"p5.TypedDict/clear"]}],"remove":[0,{"description":[0,"Removes the key-value pair stored at the given key from the Dictionary.
\n"],"path":[0,"p5.TypedDict/remove"]}],"print":[0,{"description":[0,"Logs the set of items currently stored in the Dictionary to the console.
\n"],"path":[0,"p5.TypedDict/print"]}],"saveTable":[0,{"description":[0,"Converts the Dictionary into a CSV file for local download.
\n"],"path":[0,"p5.TypedDict/saveTable"]}],"saveJSON":[0,{"description":[0,"Converts the Dictionary into a JSON file for local download.
\n"],"path":[0,"p5.TypedDict/saveJSON"]}]}],"isConstructor":[0,true],"path":[0,"p5/p5.TypedDict"]}],"render":[0,null]}],"entries":[1,[[0,{"id":[0,"en/p5.TypedDict/clear.mdx"],"slug":[0,"en/p5typeddict/clear"],"body":[0,"\n\n# clear\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"clear()"],"module":[0,"Data"],"submodule":[0,"Dictionary"],"file":[0,"src/data/p5.TypedDict.js"],"description":[0,"Removes all previously stored key-value pairs from the Dictionary.
\n"],"line":[0,245],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // prints 'true'\n myDictionary.clear();\n print(myDictionary.hasKey('p5')); // prints 'false'\n}\n
\nCreates a new key-value pair in the Dictionary.
\n"],"line":[0,209],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"key"],"description":[0,""],"type":[0,"Number|String"]}],[0,{"name":[0,"value"],"description":[0,""],"type":[0,"Number|String"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"obj"],"description":[0,"key/value pair
\n"],"type":[0,"Object"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n
Returns the value stored at the given key.
\n"],"line":[0,145],"params":[1,[[0,{"name":[0,"the"],"description":[0,"key you want to access
\n"],"type":[0,"Number|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"return":[0,{"description":[0,"the value stored at that key"],"type":[0,"Number|String"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n let myValue = myDictionary.get('p5');\n print(myValue === 'js'); // logs true to console\n}\n
Returns true if the given key exists in the Dictionary,\notherwise returns false.
\n"],"line":[0,123],"params":[1,[[0,{"name":[0,"key"],"description":[0,"that you want to look up
\n"],"type":[0,"Number|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"return":[0,{"description":[0,"whether that key exists in Dictionary"],"type":[0,"Boolean"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n}\n
Logs the set of items currently stored in the Dictionary to the console.
\n"],"line":[0,295],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n
\nRemoves the key-value pair stored at the given key from the Dictionary.
\n"],"line":[0,266],"params":[1,[[0,{"name":[0,"key"],"description":[0,"for the pair to remove
\n"],"type":[0,"Number|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n myDictionary.remove('p5');\n myDictionary.print();\n // above logs \"key: happy value: coding\" to console\n}\n
Converts the Dictionary into a JSON file for local download.
\n"],"line":[0,357],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n}\n\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveJSON('beatles');\n }\n}\n
\nConverts the Dictionary into a CSV file for local download.
\n"],"line":[0,319],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n text('click here to save', 10, 10, 70, 80);\n}\n\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveTable('beatles');\n }\n}\n
\nUpdates the value associated with the given key in case it already exists\nin the Dictionary. Otherwise a new key-value pair is added.
\n"],"line":[0,171],"params":[1,[[0,{"name":[0,"key"],"description":[0,""],"type":[0,"Number|String"]}],[0,{"name":[0,"value"],"description":[0,""],"type":[0,"Number|String"]}]]],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createStringDict('p5', 'js');\n myDictionary.set('p5', 'JS');\n myDictionary.print(); // logs \"key: p5 - value: JS\" to console\n}\n
Returns the number of key-value pairs currently stored in the Dictionary.
\n"],"line":[0,102],"itemtype":[0,"method"],"class":[0,"p5.TypedDict"],"chainable":[0,false],"return":[0,{"description":[0,"the number of key-value pairs in the Dictionary"],"type":[0,"Integer"]}],"example":[1,[[0,"\n\nfunction setup() {\n let myDictionary = createNumberDict(1, 10);\n myDictionary.create(2, 20);\n myDictionary.create(3, 30);\n print(myDictionary.size()); // logs 3 to the console\n}\n
\n La función draw()
es la función central de un sketch. Se\n ejecuta de forma continua después de la función\n setup(), hasta que el programa se\n detenga o se llame a la función noLoop()
. La frecuencia de\n ejecución se establece por defecto en 60 fotogramas por segundo, y podemos\n ajustarlo mediante la función\n frameRate().\n
\n Podemos controlar cuándo y cómo se ejecuta draw()
con las\n funciones:\n
draw()
.draw()
.draw()
una sola vez después de haber sido invocada.\n Nota: si se llama la función noLoop()
dentro de setup()
,\n draw()
se ejecutará una vez más antes de detenerse.\n
Consideraciones importantes:
\ndraw()
por sketch.draw()
es indispensable para generar animaciones o procesar eventos como mousePressed().fill()
y stroke()
, se mantienen entre ejecuciones consecutivas de draw()
.draw()
, el sistema de coordenadas se reinicia. Las transformaciones aplicadas previamente, como escalar, rotar y traslación, se eliminan evitando su acumulación.\nlet yPos = 0;\nfunction setup() {\n // setup() runs once\n frameRate(30);\n}\nfunction draw() {\n // draw() loops forever, until stopped\n background(204);\n yPos = yPos - 1;\n if (yPos < 0) {\n yPos = height;\n }\n line(0, yPos, width, yPos);\n}\n
La función setup() es llamada una vez al comienzo del programa. Se utiliza para configurar el entorno inicial, como el tamaño de la pantalla, el color del fondo, y para cargar archivos multimedia, imágenes y fuentes, al inicializar el programa.
Solo puede haber una función setup() por programa y no debería volverse a llamar después de su ejecución inicial.
Nota: Las variables declaradas dentro de setup() no son accesibles dentro de otras funciones, incluyendo a draw().
\n"],"line":[0,82],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\nlet a = 0;\nfunction setup() {\n background(0);\n noStroke();\n fill(102);\n}\nfunction draw() {\n rect(a++ % width, 10, 2, 80);\n}\n
Turns off the parts of the Friendly Error System (FES) that impact performance.
\nThe FES\ncan cause sketches to draw slowly because it does extra work behind the\nscenes. For example, the FES checks the arguments passed to functions,\nwhich takes time to process. Disabling the FES can significantly improve\nperformance by turning off these checks.
\n"],"line":[0,877],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// Disable the FES.\np5.disableFriendlyErrors = true;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // The circle() function requires three arguments. The\n // next line would normally display a friendly error that\n // points this out. Instead, nothing happens and it fails\n // silently.\n circle(50, 50);\n\n describe('A gray square.');\n}\n
\nReturns true
if the draw loop is running and false
if not.
By default, draw() tries to run 60 times per\nsecond. Calling noLoop() stops\ndraw() from repeating. The draw loop can be\nrestarted by calling loop().
\nThe isLooping()
function can be used to check whether a sketch is\nlooping, as in isLooping() === true
.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle drawn against a gray background. When the user double-clicks, the circle stops or resumes following the mouse.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw the circle at the mouse's position.\n circle(mouseX, mouseY, 20);\n}\n\n// Toggle the draw loop when the user double-clicks.\nfunction doubleClicked() {\n if (isLooping() === true) {\n noLoop();\n } else {\n loop();\n }\n}\n
\nResumes the draw loop after noLoop() has been\ncalled.
\nBy default, draw() tries to run 60 times per\nsecond. Calling noLoop() stops\ndraw() from repeating. The draw loop can be\nrestarted by calling loop()
.
The isLooping() function can be used to check\nwhether a sketch is looping, as in isLooping() === true
.
\nfunction setup() {\n createCanvas(100, 100);\n\n // Turn off the draw loop.\n noLoop();\n\n describe(\n 'A white half-circle on the left edge of a gray square. The circle starts moving to the right when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the circle's x-coordinate.\n let x = frameCount;\n\n // Draw the circle.\n circle(x, 50, 20);\n}\n\n// Resume the draw loop when the user double-clicks.\nfunction doubleClicked() {\n loop();\n}\n
\n\nlet startButton;\nlet stopButton;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create the button elements and place them\n // beneath the canvas.\n startButton = createButton('▶');\n startButton.position(0, 100);\n startButton.size(50, 20);\n stopButton = createButton('◾');\n stopButton.position(50, 100);\n stopButton.size(50, 20);\n\n // Set functions to call when the buttons are pressed.\n startButton.mousePressed(loop);\n stopButton.mousePressed(noLoop);\n\n // Slow the frame rate.\n frameRate(5);\n\n describe(\n 'A white circle moves randomly on a gray background. Play and stop buttons are shown beneath the canvas. The circle stops or starts moving when the user presses a button.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the circle's coordinates.\n let x = random(0, 100);\n let y = random(0, 100);\n\n // Draw the circle.\n // Normally, the circle would move from left to right.\n circle(x, y, 20);\n}\n
\nStops the code in draw() from running repeatedly.
\nBy default, draw() tries to run 60 times per\nsecond. Calling noLoop()
stops draw() from\nrepeating. The draw loop can be restarted by calling\nloop(). draw() can be run\nonce by calling redraw().
The isLooping() function can be used to check\nwhether a sketch is looping, as in isLooping() === true
.
\nfunction setup() {\n createCanvas(100, 100);\n\n // Turn off the draw loop.\n noLoop();\n\n describe('A white half-circle on the left edge of a gray square.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the circle's x-coordinate.\n let x = frameCount;\n\n // Draw the circle.\n // Normally, the circle would move from left to right.\n circle(x, 50, 20);\n}\n
\n\n// Double-click to stop the draw loop.\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(5);\n\n describe('A white circle moves randomly on a gray background. It stops moving when the user double-clicks.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the circle's coordinates.\n let x = random(0, 100);\n let y = random(0, 100);\n\n // Draw the circle.\n // Normally, the circle would move from left to right.\n circle(x, y, 20);\n}\n\n// Stop the draw loop when the user double-clicks.\nfunction doubleClicked() {\n noLoop();\n}\n
\n\nlet startButton;\nlet stopButton;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Create the button elements and place them\n // beneath the canvas.\n startButton = createButton('▶');\n startButton.position(0, 100);\n startButton.size(50, 20);\n stopButton = createButton('◾');\n stopButton.position(50, 100);\n stopButton.size(50, 20);\n\n // Set functions to call when the buttons are pressed.\n startButton.mousePressed(loop);\n stopButton.mousePressed(noLoop);\n\n // Slow the frame rate.\n frameRate(5);\n\n describe(\n 'A white circle moves randomly on a gray background. Play and stop buttons are shown beneath the canvas. The circle stops or starts moving when the user presses a button.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the circle's coordinates.\n let x = random(0, 100);\n let y = random(0, 100);\n\n // Draw the circle.\n // Normally, the circle would move from left to right.\n circle(x, y, 20);\n}\n
\nEnds a drawing group that contains its own styles and transformations.
\nBy default, styles such as fill() and\ntransformations such as rotate() are applied to\nall drawing that follows. The push() and pop()
\nfunctions can limit the effect of styles and transformations to a specific\ngroup of shapes, images, and text. For example, a group of shapes could be\ntranslated to follow the mouse without affecting the rest of the sketch:
// Begin the drawing group.\npush();\n\n// Translate the origin to the mouse's position.\ntranslate(mouseX, mouseY);\n\n// Style the face.\nnoStroke();\nfill('green');\n\n// Draw the face.\ncircle(0, 0, 60);\n\n// Style the eyes.\nfill('white');\n\n// Draw the left eye.\nellipse(-20, -20, 30, 20);\n\n// Draw the right eye.\nellipse(20, -20, 30, 20);\n\n// End the drawing group.\npop();\n\n// Draw a bug.\nlet x = random(0, 100);\nlet y = random(0, 100);\ntext('🦟', x, y);\n
\nIn the code snippet above, the bug's position isn't affected by\ntranslate(mouseX, mouseY)
because that transformation is contained\nbetween push() and pop()
. The bug moves around\nthe entire canvas as expected.
Note: push() and pop()
are always called as a\npair. Both functions are required to begin and end a drawing group.
push() and pop()
can also be nested to create\nsubgroups. For example, the code snippet above could be changed to give\nmore detail to the frog’s eyes:
// Begin the drawing group.\npush();\n\n// Translate the origin to the mouse's position.\ntranslate(mouseX, mouseY);\n\n// Style the face.\nnoStroke();\nfill('green');\n\n// Draw a face.\ncircle(0, 0, 60);\n\n// Style the eyes.\nfill('white');\n\n// Draw the left eye.\npush();\ntranslate(-20, -20);\nellipse(0, 0, 30, 20);\nfill('black');\ncircle(0, 0, 8);\npop();\n\n// Draw the right eye.\npush();\ntranslate(20, -20);\nellipse(0, 0, 30, 20);\nfill('black');\ncircle(0, 0, 8);\npop();\n\n// End the drawing group.\npop();\n\n// Draw a bug.\nlet x = random(0, 100);\nlet y = random(0, 100);\ntext('🦟', x, y);\n
\nIn this version, the code to draw each eye is contained between its own\npush() and pop()
functions. Doing so makes it\neasier to add details in the correct part of a drawing.
push() and pop()
contain the effects of the\nfollowing functions:
In WebGL mode, push() and pop()
contain the\neffects of a few additional styles:
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw the left circle.\n circle(25, 50, 20);\n\n // Begin the drawing group.\n push();\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Style the circle.\n strokeWeight(5);\n stroke('royalblue');\n fill('orange');\n\n // Draw the circle.\n circle(0, 0, 20);\n\n // End the drawing group.\n pop();\n\n // Draw the right circle.\n circle(75, 50, 20);\n\n describe(\n 'Three circles drawn in a row on a gray background. The left and right circles are white with thin, black borders. The middle circle is orange with a thick, blue border.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(24);\n\n describe('A mosquito buzzes in front of a green frog. The frog follows the mouse as the user moves.');\n}\n\nfunction draw() {\n background(200);\n\n // Begin the drawing group.\n push();\n\n // Translate the origin to the mouse's position.\n translate(mouseX, mouseY);\n\n // Style the face.\n noStroke();\n fill('green');\n\n // Draw a face.\n circle(0, 0, 60);\n\n // Style the eyes.\n fill('white');\n\n // Draw the left eye.\n push();\n translate(-20, -20);\n ellipse(0, 0, 30, 20);\n fill('black');\n circle(0, 0, 8);\n pop();\n\n // Draw the right eye.\n push();\n translate(20, -20);\n ellipse(0, 0, 30, 20);\n fill('black');\n circle(0, 0, 8);\n pop();\n\n // End the drawing group.\n pop();\n\n // Draw a bug.\n let x = random(0, 100);\n let y = random(0, 100);\n text('🦟', x, y);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'Two spheres drawn on a gray background. The sphere on the left is red and lit from the front. The sphere on the right is a blue wireframe.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Draw the red sphere.\n push();\n translate(-25, 0, 0);\n noStroke();\n directionalLight(255, 0, 0, 0, 0, -1);\n sphere(20);\n pop();\n\n // Draw the blue sphere.\n push();\n translate(25, 0, 0);\n strokeWeight(0.3);\n stroke(0, 0, 255);\n noFill();\n sphere(20);\n pop();\n}\n
\nA function that's called once to load assets before the sketch runs.
\nDeclaring the function preload()
sets a code block to run once\nautomatically before setup() or\ndraw(). It's used to load assets including\nmultimedia files, fonts, data, and 3D models:
function preload() {\n // Code to run before the rest of the sketch.\n}\n
\nFunctions such as loadImage(),\nloadFont(),\nloadJSON(), and\nloadModel() are guaranteed to either\nfinish loading or raise an error if they're called within preload()
.\nDoing so ensures that assets are available when the sketch begins\nrunning.
\nlet img;\n\n// Load an image and create a p5.Image object.\nfunction preload() {\n img = loadImage('/assets/bricks.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Draw the image.\n image(img, 0, 0);\n\n describe('A red brick wall.');\n}\n
\nBegins a drawing group that contains its own styles and transformations.
\nBy default, styles such as fill() and\ntransformations such as rotate() are applied to\nall drawing that follows. The push()
and pop()\nfunctions can limit the effect of styles and transformations to a specific\ngroup of shapes, images, and text. For example, a group of shapes could be\ntranslated to follow the mouse without affecting the rest of the sketch:
// Begin the drawing group.\npush();\n\n// Translate the origin to the mouse's position.\ntranslate(mouseX, mouseY);\n\n// Style the face.\nnoStroke();\nfill('green');\n\n// Draw the face.\ncircle(0, 0, 60);\n\n// Style the eyes.\nfill('white');\n\n// Draw the left eye.\nellipse(-20, -20, 30, 20);\n\n// Draw the right eye.\nellipse(20, -20, 30, 20);\n\n// End the drawing group.\npop();\n\n// Draw a bug.\nlet x = random(0, 100);\nlet y = random(0, 100);\ntext('🦟', x, y);\n
\nIn the code snippet above, the bug's position isn't affected by\ntranslate(mouseX, mouseY)
because that transformation is contained\nbetween push()
and pop(). The bug moves around\nthe entire canvas as expected.
Note: push()
and pop() are always called as a\npair. Both functions are required to begin and end a drawing group.
push()
and pop() can also be nested to create\nsubgroups. For example, the code snippet above could be changed to give\nmore detail to the frog’s eyes:
// Begin the drawing group.\npush();\n\n// Translate the origin to the mouse's position.\ntranslate(mouseX, mouseY);\n\n// Style the face.\nnoStroke();\nfill('green');\n\n// Draw a face.\ncircle(0, 0, 60);\n\n// Style the eyes.\nfill('white');\n\n// Draw the left eye.\npush();\ntranslate(-20, -20);\nellipse(0, 0, 30, 20);\nfill('black');\ncircle(0, 0, 8);\npop();\n\n// Draw the right eye.\npush();\ntranslate(20, -20);\nellipse(0, 0, 30, 20);\nfill('black');\ncircle(0, 0, 8);\npop();\n\n// End the drawing group.\npop();\n\n// Draw a bug.\nlet x = random(0, 100);\nlet y = random(0, 100);\ntext('🦟', x, y);\n
\nIn this version, the code to draw each eye is contained between its own\npush()
and pop() functions. Doing so makes it\neasier to add details in the correct part of a drawing.
push()
and pop() contain the effects of the\nfollowing functions:
In WebGL mode, push()
and pop() contain the\neffects of a few additional styles:
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw the left circle.\n circle(25, 50, 20);\n\n // Begin the drawing group.\n push();\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Style the circle.\n strokeWeight(5);\n stroke('royalblue');\n fill('orange');\n\n // Draw the circle.\n circle(0, 0, 20);\n\n // End the drawing group.\n pop();\n\n // Draw the right circle.\n circle(75, 50, 20);\n\n describe(\n 'Three circles drawn in a row on a gray background. The left and right circles are white with thin, black borders. The middle circle is orange with a thick, blue border.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(24);\n\n describe('A mosquito buzzes in front of a green frog. The frog follows the mouse as the user moves.');\n}\n\nfunction draw() {\n background(200);\n\n // Begin the drawing group.\n push();\n\n // Translate the origin to the mouse's position.\n translate(mouseX, mouseY);\n\n // Style the face.\n noStroke();\n fill('green');\n\n // Draw a face.\n circle(0, 0, 60);\n\n // Style the eyes.\n fill('white');\n\n // Draw the left eye.\n push();\n translate(-20, -20);\n ellipse(0, 0, 30, 20);\n fill('black');\n circle(0, 0, 8);\n pop();\n\n // Draw the right eye.\n push();\n translate(20, -20);\n ellipse(0, 0, 30, 20);\n fill('black');\n circle(0, 0, 8);\n pop();\n\n // End the drawing group.\n pop();\n\n // Draw a bug.\n let x = random(0, 100);\n let y = random(0, 100);\n text('🦟', x, y);\n}\n
\n\n// Click and drag the mouse to view the scene from different angles.\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n 'Two spheres drawn on a gray background. The sphere on the left is red and lit from the front. The sphere on the right is a blue wireframe.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Enable orbiting with the mouse.\n orbitControl();\n\n // Draw the red sphere.\n push();\n translate(-25, 0, 0);\n noStroke();\n directionalLight(255, 0, 0, 0, 0, -1);\n sphere(20);\n pop();\n\n // Draw the blue sphere.\n push();\n translate(25, 0, 0);\n strokeWeight(0.3);\n stroke(0, 0, 255);\n noFill();\n sphere(20);\n pop();\n}\n
\nRuns the code in draw() once.
\nBy default, draw() tries to run 60 times per\nsecond. Calling noLoop() stops\ndraw() from repeating. Calling redraw()
will\nexecute the code in the draw() function a set\nnumber of times.
The parameter, n
, is optional. If a number is passed, as in redraw(5)
,\nthen the draw loop will run the given number of times. By default, n
is\n1.
number of times to run draw(). Defaults to 1.
\n"],"type":[0,"Integer"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// Double-click the canvas to move the circle.\n\nlet x = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Turn off the draw loop.\n noLoop();\n\n describe(\n 'A white half-circle on the left edge of a gray square. The circle moves a little to the right when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw the circle.\n circle(x, 50, 20);\n\n // Increment x.\n x += 5;\n}\n\n// Run the draw loop when the user double-clicks.\nfunction doubleClicked() {\n redraw();\n}\n
\n\n// Double-click the canvas to move the circle.\n\nlet x = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Turn off the draw loop.\n noLoop();\n\n describe(\n 'A white half-circle on the left edge of a gray square. The circle hops to the right when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw the circle.\n circle(x, 50, 20);\n\n // Increment x.\n x += 5;\n}\n\n// Run the draw loop three times when the user double-clicks.\nfunction doubleClicked() {\n redraw(3);\n}\n
\nRemoves the sketch from the web page.
\nCalling remove()
stops the draw loop and removes any HTML elements\ncreated by the sketch, including the canvas. A new sketch can be\ncreated by using the p5() constructor, as in\nnew p5()
.
\n// Double-click to remove the canvas.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A white circle on a gray background. The circle follows the mouse as the user moves. The sketch disappears when the user double-clicks.'\n );\n}\n\nfunction draw() {\n // Paint the background repeatedly.\n background(200);\n\n // Draw circles repeatedly.\n circle(mouseX, mouseY, 40);\n}\n\n// Remove the sketch when the user double-clicks.\nfunction doubleClicked() {\n remove();\n}\n
\nUna lista que mantiene diferentes tipos de datos en orden
Los arreglos son útiles para almacenar datos relacionados. Pueden contener datos de cualquier tipo. Por ejemplo, un arreglo podría contener una lista de colores favoritos de alguien como cadenas de caracteres. Los arreglos se crean de la siguiente manera:
let colors = ['deeppink', 'darkorchid', 'magenta'];
Cada dato dentro de un arreglo se llama elemento. Cada elemento tiene una dirección, o índice, dentro de su arreglo. La variable colors
se refiere a un arreglo con tres elementos de tipo String, 'deeppink'
, 'darkorchid'
, y 'magenta'
. Los arreglos empiezan con índice cero, lo que significa que 'deeppink'
está en el índice 0, 'darkorchid'
está en el índice 1, y 'magenta'
está en el índice 2. Los elementos del arreglo se pueden acceder utilizando sus índices de la siguiente manera:
let zeroth = colors[0]; // 'deeppink' let first = colors[1]; // 'darkorchid' let second = colors[2]; // 'magenta'
Se pueden agregar elementos al final de un arreglo llamando al método push()
de la siguiente manera:
colors.push('lavender'); let third = colors[3]; // 'lavender'
Consulta MDN para obtener más información sobre arreglos.
\n"],"line":[0,1137],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// Declare the variable xCoordinates and assign it an array\n// with three numeric elements.\nlet xCoordinates = [25, 50, 75];\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'Three white circles drawn in a horizontal line on a gray background.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Access the element at index 0, which is 25.\n circle(xCoordinates[0], 50, 20);\n\n // Access the element at index 1, which is 50.\n circle(xCoordinates[1], 50, 20);\n\n // Access the element at index 2, which is 75.\n circle(xCoordinates[2], 50, 20);\n}\n
\n\n// Declare the variable xCoordinates and assign it an array with three numeric elements.\nlet xCoordinates = [20, 40, 60];\n\n// Add another element to the end of the array.\nxCoordinates.push(80);\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Four white circles drawn in a horizontal line on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the element at index 0, which is 20.\n circle(xCoordinates[0], 50, 20);\n\n // Access the element at index 1, which is 40.\n circle(xCoordinates[1], 50, 20);\n\n // Access the element at index 2, which is 60.\n circle(xCoordinates[2], 50, 20);\n\n // Access the element at index 3, which is 80.\n circle(xCoordinates[3], 50, 20);\n}\n
\n\n// Declare the variable xCoordinates and assign it an empty array.\nlet xCoordinates = [];\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Add elements to the array using a loop.\n for (let x = 20; x < 100; x += 20) {\n xCoordinates.push(x);\n }\n\n describe('Four white circles drawn in a horizontal line on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the element at index i and use it to draw a circle.\n for (let i = 0; i < xCoordinates.length; i += 1) {\n circle(xCoordinates[i], 50, 20);\n }\n}\n
\n\n// Declare the variable xCoordinates and assign it an empty array.\nlet xCoordinates = [];\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Add elements to the array using a loop.\n for (let x = 20; x < 100; x += 20) {\n xCoordinates.push(x);\n }\n\n describe('Four white circles drawn in a horizontal line on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access each element of the array and use it to draw a circle.\n for (let x of xCoordinates) {\n circle(x, 50, 20);\n }\n}\n
\n\n// Declare the variable xCoordinates and assign it an empty array.\nlet xCoordinates = [];\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Add elements to the array using a loop.\n for (let x = 20; x < 100; x += 20) {\n xCoordinates.push(x);\n }\n\n describe(\n 'Four white circles in a horizontal line on a gray background. The circles move randomly.'\n );\n}\n\nfunction draw() {\n background(200);\n\n for (let i = 0; i < xCoordinates.length; i += 1) {\n // Update the element at index i.\n xCoordinates[i] += random(-1, 1);\n\n // Use the element at index i to draw a circle.\n circle(xCoordinates[i], 50, 20);\n }\n}\n
\nUna plantilla para crear objetos de un tipo en particular.
Las clases pueden facilitar la programación con objetos. Por ejemplo, una clase Frog
podría crear objetos que se comporten como ranas. Cada objeto creado usando una clase se llama ‘instancia’. Todas las instancias de una clase son del mismo tipo. Aquí tienes un ejemplo de crear una instancia de la clase Frog
:
let fifi = new Frog(50, 50, 20);
\nLa variable fifi
se refiere a una instancia de la clase Frog
. La palabra clave new
se utiliza para llamar al constructor de la clase Frog
en la declaración new Frog()
. En resumen, se creó un nuevo objeto Frog
y se asignó a la variable fifi
. Las clases son plantillas, por lo que se pueden usar para crear más de una instancia:
// First Frog instance. let frog1 = new Frog(25, 50, 10); // Second Frog instance. let frog2 = new Frog(75, 50, 10);
Una clase simple Frog
podría declararse de la siguiente manera:
class Frog { (x, y, size) { // This code runs once when an instance is created. this.x = x; this.y = y; this.size = size; } show() { // This code runs once when myFrog.show() is called. textAlign(CENTER, CENTER); textSize(this.size); text('🐸', this.x, this.y); }
hop() { // This code runs once when myFrog.hop() is called. this.x += random(-10, 10); this.y += random(-10, 10); }
}
Las declaraciones de clase comienzan con la palabra clave class
seguida del nombre de la clase, como Frog
, y llaves {}
. Los nombres de las clases deben usar PascalCase
y no pueden tener espacios en sus nombres. Por ejemplo, nombrar una clase Kermit The Frog
con espacios entre cada palabra produciría un error SyntaxError
. El código que se encuentra dentro de las llaves {}
define la clase.
Las funciones que pertenecen a una clase se llaman métodos. constructor()
, show()
y hop()
son métodos en la clase Frog
. Los métodos definen el comportamiento de un objeto. Los métodos pueden aceptar parámetros y devolver valores, al igual que las funciones. Ten en cuenta que los métodos no utilizan la palabra clave function
.
constructor()
es un método especial que se llama una vez cuando se crea una instancia de la clase. La declaración new Frog()
llama al método constructor()
de la clase Frog
.
Una definición de clase es una plantilla para instancias. La palabra clave this
se refiere a los datos y métodos de una instancia. Por ejemplo, cada instancia de Frog
tiene coordenadas únicas almacenadas en this.x
y this.y
. El método show()
usa esas coordenadas para dibujar la rana. El método hop()
actualiza esas coordenadas cuando se llama. Una vez que se crea una instancia de Frog
, sus datos y métodos se pueden acceder utilizando el operador de punto .
de la siguiente manera:
// Draw a lily pad. fill('green'); stroke('green'); circle(fifi.x, fifi.y, 2 * fifi. size);\n// Show the frog. fifi.show();
\n//Hop. fifi.hop();
"],"line":[0,1325],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// Declare a frog variable.\nlet fifi;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Assign the frog variable a new Frog object.\n fifi = new Frog(50, 50, 20);\n\n describe('A frog face drawn on a gray background.');\n}\n\nfunction draw() {\n background('cornflowerblue');\n\n // Show the frog.\n fifi.show();\n}\n\nclass Frog {\n constructor(x, y, size) {\n this.x = x;\n this.y = y;\n this.size = size;\n }\n\n show() {\n textAlign(CENTER, CENTER);\n textSize(this.size);\n text('🐸', this.x, this.y);\n }\n}\n
\n\n// Declare two frog variables.\nlet frog1;\nlet frog2;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Assign the frog variables a new Frog object.\n frog1 = new Frog(25, 50, 10);\n frog2 = new Frog(75, 50, 20);\n\n describe('Two frog faces drawn next to each other on a gray background.');\n}\n\nfunction draw() {\n background('cornflowerblue');\n\n // Show the frogs.\n frog1.show();\n frog2.show();\n}\n\nclass Frog {\n constructor(x, y, size) {\n this.x = x;\n this.y = y;\n this.size = size;\n }\n\n show() {\n textAlign(CENTER, CENTER);\n textSize(this.size);\n text('🐸', this.x, this.y);\n }\n}\n
\n\n// Declare two frog variables.\nlet frog1;\nlet frog2;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Assign the frog variables a new Frog object.\n frog1 = new Frog(25, 50, 10);\n frog2 = new Frog(75, 50, 20);\n\n // Slow the frame rate.\n frameRate(1);\n\n describe('Two frog faces on a gray background. The frogs hop around randomly.');\n}\n\nfunction draw() {\n background('cornflowerblue');\n\n // Show the frogs.\n frog1.show();\n frog2.show();\n\n // Move the frogs.\n frog1.hop();\n frog2.hop();\n\n // Wrap around if they've hopped off the edge.\n frog1.checkEdges();\n frog2.checkEdges();\n}\n\nclass Frog {\n constructor(x, y, size) {\n this.x = x;\n this.y = y;\n this.size = size;\n }\n\n show() {\n textAlign(CENTER, CENTER);\n textSize(this.size);\n text('🐸', this.x, this.y);\n }\n\n hop() {\n this.x += random(-10, 10);\n this.y += random(-10, 10);\n }\n\n checkEdges() {\n if (this.x > width) {\n this.x = this.x - width;\n } else if (this.x < 0) {\n this.x = width - this.x;\n }\n\n if (this.y > height) {\n this.y = this.y - height;\n } else if (this.y < 0) {\n this.y = height - this.y;\n }\n }\n}\n
\n\n// Declare two frog variables.\nlet frog1;\nlet frog2;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Assign the frog variables a new Frog object.\n frog1 = new Frog(25, 50, 10);\n frog2 = new Frog(75, 50, 20);\n\n describe('Two frog faces drawn next to each other on a gray background.');\n}\n\nfunction draw() {\n background('cornflowerblue');\n\n // Show the frogs.\n frog1.show();\n frog2.show();\n}\n\nclass Frog {\n constructor(x, y, size) {\n this.x = x;\n this.y = y;\n this.size = size;\n }\n\n show() {\n textAlign(CENTER, CENTER);\n textSize(this.size);\n text('🐸', this.x, this.y);\n }\n}\n
\n\n// Create an array that will hold frogs.\nlet frogs = [];\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Add Frog objects to the array.\n for (let i = 0; i < 5; i += 1) {\n // Calculate random coordinates and size.\n let x = random(0, 100);\n let y = random(0, 100);\n let s = random(2, 20);\n\n // Create a new Frog object.\n let frog = new Frog(x, y, s);\n\n // Add the Frog to the array.\n frogs.push(frog);\n }\n\n // Slow the frame rate.\n frameRate(1);\n\n describe(\n 'Five frog faces on a gray background. The frogs hop around randomly.'\n );\n}\n\nfunction draw() {\n background('cornflowerblue');\n\n for (let frog of frogs) {\n // Show the frog.\n frog.show();\n\n // Move the frog.\n frog.hop();\n\n // Wrap around if they've hopped off the edge.\n frog.checkEdges();\n }\n}\n\nclass Frog {\n constructor(x, y, size) {\n this.x = x;\n this.y = y;\n this.size = size;\n }\n\n show() {\n textAlign(CENTER, CENTER);\n textSize(this.size);\n text('🐸', this.x, this.y);\n }\n\n hop() {\n this.x += random(-10, 10);\n this.y += random(-10, 10);\n }\n\n checkEdges() {\n if (this.x > width) {\n this.x = this.x - width;\n } else if (this.x < 0) {\n this.x = width - this.x;\n }\n\n if (this.y > height) {\n this.y = this.y - height;\n } else if (this.y < 0) {\n this.y = height - this.y;\n }\n }\n}\n
\nUna forma de repetir un bloque de código cuando se conoce el número de iteraciones.
Los bucles for
son útiles para repetir declaraciones un cierto número de veces. Por ejemplo, un bucle for
facilita expresar la idea \"dibujar cinco líneas\" de la siguiente manera:
for (let x = 10; x < 100; x += 20) { line(x, 25, x, 75); }
La cabecera del bucle comienza con la palabra clave for
. Los bucles generalmente incrementan o disminuyen a medida que se repiten, o iteran. Las declaraciones entre paréntesis let x = 10; x < 100; x += 20
indican al bucle cómo debe repetirse:
let x = 10
indica al bucle que comience a contar desde 10
y llevando un seguimiento de las iteraciones usando la variable x
.x < 100
le indica al bucle que cuente hasta, pero sin incluir, 100
.x += 20
indica al bucle que incremente en 20
al final de cada iteración.El código entre llaves {}
es el cuerpo del bucle. Las declaraciones dentro del cuerpo del bucle se repiten durante cada iteración del bucle.
Es común crear bucles infinitos accidentalmente. Cuando esto sucede, los bocetos pueden volverse no responsivos y el navegador web puede mostrar una advertencia. Por ejemplo, el siguiente bucle nunca deja de iterar porque no se le ha indicado que incremente:
\n for (let x = 10; x < 100; x = 20) {\n line(x, 25, x, 75);\n}
La declaración x = 20
mantiene la variable x
estancada en 20
. El bucle continua infinitamente precisamente porque 20
siempre va a ser menor que 100
.
Los bucles for
también pueden contar hacia abajo (disminuir):
\n for (let d = 100; d > 0; d -= 10) {\n circle(50, 50, d);\n}
Los bucles for
también pueden contener otros bucles. El siguiente bucle anidado dibuja una cuadrícula de puntos:
// Loop from left to right for (let x = 10; x < 100; x += 10) { // Loop from top to bottom for (let y = 10; y < 100; y += 10) {\n point(x, y);\n} }
Los bucles for
también son útiles para iterar a través de los elementos de un arreglo. Por ejemplo, es común iterar a través de un arreglo que contiene información sobre dónde o qué dibujar:
// Create an array of x-coordinates.Let xCoordinates = [20, 40, 60];\nfor (let i = 0; i < xCoordinates.length; i += 1) { // Update the element. xCoordinates[i] += random(-1, 1); // Draw a circle. circle(xCoordinates[i], 50, 20); }
Si los valores del array no se modifican, la declaración for...of
puede simplificar el código. Son similares a los bucles for
en Python y los bucles for-each
en C++ y Java. Los siguientes bucles tienen el mismo efecto:
// Draw circles with a for loop let xCoordinates = [20, 40, 60]; for (let i = 0; i < xCoordinates.length; i += 1) {\n circle(xCoordinates [i], 50, 20);\n}
// Draw circles with a for...of statement. let xCoordinates = [20, 40, 60];\n for (let x of xCoordinates) {\n circle(x, 50, 20);\n}
En estos fragmentos de código, las variables i
y x
tienen roles diferentes.
En el primer fragmento, i
cuenta desde 0
hasta 2
, que es uno menos que xCoordinates.length
. i
se utiliza para acceder al elemento en xCoordinates
en el índice i
.
En el segundo fragmento de código, x
no realiza un seguimiento del progreso del bucle o de un índice. Durante cada iteración, x
contiene el siguiente elemento de xCoordinates
. x
comienza desde el principio de xCoordinates
(20
) y actualiza su valor a 40
y luego a 60
durante las siguientes iteraciones.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Five black vertical lines on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw vertical lines using a loop.\n for (let x = 10; x < 100; x += 20) {\n line(x, 25, x, 75);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Five white concentric circles drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw concentric circles using a loop.\n for (let d = 100; d > 0; d -= 20) {\n circle(50, 50, d);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A grid of black dots on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Set the spacing for points on the grid.\n let space = 10;\n\n // Increase the stroke weight.\n strokeWeight(3);\n\n // Loop from the left to the right.\n for (let x = space; x < 100; x += space) {\n // Loop from the top to the bottom.\n for (let y = space; y < 100; y += space) {\n point(x, y);\n }\n }\n}\n
\n\n// Declare the variable xCoordinates and assign it an array of numbers.\nlet xCoordinates = [20, 40, 60, 80];\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Four white circles drawn in a horizontal line on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the element at index i and use it to draw a circle.\n for (let i = 0; i < xCoordinates.length; i += 1) {\n circle(xCoordinates[i], 50, 20);\n }\n}\n
\n\n// Declare the variable xCoordinates and assign it an array of numbers.\nlet xCoordinates = [20, 40, 60, 80];\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Four white circles drawn in a horizontal line on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access each element of the array and use it to draw a circle.\n for (let x of xCoordinates) {\n circle(x, 50, 20);\n }\n}\n
\nUn grupo de declaraciones con nombre.
Las funciones ayudan a organizar y reutilizar código. Por ejemplo, las funciones hacen que sea fácil expresar la idea \"Dibujar una flor.\":
function drawFlower() { // Style the text. textAlign(CENTER, CENTER); textSize(20); // Draw a flower emoji. text('🌸', 50, 50); }
El encabezado de la función comienza con la palabra clave function
. El nombre de la función, drawFlower
, va seguido de paréntesis ()
y llaves {}
. El código entre las llaves corresponde al cuerpo de la función. El cuerpo de la función se ejecuta cuando la función es llamada de la siguiente manera:
drawFlower();
Las funciones pueden aceptar entradas agregando parámetros a sus encabezados. Los parámetros son marcadores de posición para los valores que se proporcionarán cuando se llame a la función. Por ejemplo, la función drawFlower()
, podría incluir un parámetro para definir el tamaño de la flor:
function drawFlower(size) { // Style the text. textAlign(CENTER, CENTER); // Use the size parameter. textSize(size);
// Draw a flower emoji. text('🌸', 50, 50); }
Los parámetros son parte de la declaración de la función. Los argumentos son proporcionados por el código que llama a una función. Cuando se llama a una función, los argumentos se asignan a los parámetros:
// The argument 20 is assigned to the parameter size. drawFlower(20);
\t Las funciones pueden tener varios parámetros separados por comas, y los parámetros pueden ser de cualquier tipo de datos. Por ejemplo, la función drawFlower()
podría aceptar parámetros de tipo Number
(número) para las coordenadas-x y las coordenadas-y de la flor junto con su tamaño:
function drawFlower(x, y, size) { // Style the text. textAlign(CENTER, CENTER); // Use the size parameter. textSize(size);
// Draw a flower emoji. // Use the x and y parameters. text('🌸', x, y); }
Las funciones también pueden producir salidas agregando una declaración return
function double(x) { let answer = 2 * x; return answer; }
La expresión que sigue a return
puede producir una salida que se utiliza en otro lugar. Por ejemplo, la salida de la función double()
se puede asignar a una variable:
let six = double(3); text(`3 x 2 = ${six}`, 50, 50);
\n"],"line":[0,317],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A pink flower on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Call the drawFlower() function.\n drawFlower();\n}\n\n// Declare a function that draws a flower at the\n// center of the canvas.\nfunction drawFlower() {\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(20);\n\n // Draw a flower emoji.\n text('🌸', 50, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A pink flower on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Call the drawFlower() function and pass values for\n // its position and size.\n drawFlower(50, 50, 20);\n}\n\n// Declare a function that draws a flower at the\n// center of the canvas.\nfunction drawFlower(x, y, size) {\n // Style the text.\n textAlign(CENTER, CENTER);\n\n // Use the size parameter.\n textSize(size);\n\n // Draw a flower emoji.\n // Use the x and y parameters.\n text('🌸', x, y);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('The message \"Hello, 🌍!\" written on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Create a greeting.\n let greeting = createGreeting('🌍');\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the greeting.\n text(greeting, 50, 50);\n}\n\n// Return a string with a personalized greeting.\nfunction createGreeting(name) {\n let message = `Hello, ${name}!`;\n return message;\n}\n
\nUna forma de elegir si ejecutar un bloque de código.
\n\nLas declaraciones if
son útiles para ejecutar un bloque de código basado en una condición. Por ejemplo, una declaración if
facilita expresar la idea \"Dibuja un círculo si el mouse está presionado.\":
\n if (mouseIsPressed === true) {\n circle(mouseX, mouseY, 20);\n }\n
\n\n El encabezado de la declaración comienza con la palabra clave if
. La expresión entre paréntesis mouseIsPressed === true
es una expresión booleana que es true
o false
. El código entre llaves {}
es el cuerpo de la declaración if
. El cuerpo solo se ejecuta si la expresión booleana es true
.
La variable de sistema mouseIsPressed siempre es true
o false
, por lo que el fragmento de código anterior también se podría escribir de la siguiente manera:
\n if (mouseIsPressed) {\n circle(mouseX, mouseY, 20);\n }\n
\n\n Una declaración if
-else
agrega un bloque de código que se ejecuta si la expresión booleana es false
. Por ejemplo, aquí hay una declaración if
-else
que expresa la idea \"Dibuja un círculo si el mouse está presionado. De lo contrario, muestra un mensaje.\":
\n if (mouseIsPressed === true) {\n // When true.\n circle(mouseX, mouseY, 20);\n } else {\n // When false.\n text('Haz clic en mí!', 50, 50);\n }\n
\n\n Hay dos posibles caminos, o ramas, en este fragmento de código. El programa debe seguir una rama u otra.
\n\nUna declaración else
-if
hace posible agregar más ramas. Las declaraciones else
-if
ejecutan diferentes bloques de código bajo diferentes condiciones. Por ejemplo, una declaración else
-if
facilita expresar la idea \"Si el mouse está a la izquierda, pinta el lienzo de blanco. Si el mouse está en el medio, pinta el lienzo de gris. De lo contrario, pinta el lienzo de negro.\":
\n if (mouseX < 33) {\n background(255);\n } else if (mouseX < 67) {\n background(200);\n } else {\n background(0);\n }\n
\n\n Las declaraciones if
pueden agregar tantas declaraciones else
-if
como sea necesario. Sin embargo, solo puede haber una declaración else
y debe estar al final.
Las declaraciones if
también pueden verificar múltiples condiciones a la vez. Por ejemplo, el operador booleano &&
(AND) verifica si dos expresiones son ambas true
:
\n if (keyIsPressed === true && key === 'p') {\n text('¡Presionaste la tecla \"p\"!', 50, 50);\n }\n
\n\n Si el usuario está presionando una tecla y esa tecla es 'p'
, entonces se mostrará un mensaje.
El operador booleano ||
(OR) verifica si al menos una de dos expresiones es true
:
\n if (keyIsPressed === true || mouseIsPressed === true) {\n text('¡Hiciste algo!', 50, 50);\n }\n
\n\n Si el usuario presiona una tecla, o presiona un botón del mouse, o ambos, entonces se mostrará un mensaje.
\n\nEl cuerpo de una declaración if
puede contener otra declaración if
. Esto se llama una \"declaración if
anidada\". Por ejemplo, las declaraciones if
anidadas facilitan expresar la idea \"Si se presiona una tecla, entonces verifica si la tecla es 'r'. Si la tecla presionada es ‘r’, entonces establece el color de relleno como rojo.\":
\n if (keyIsPressed === true) {\n if (key === 'r') {\n fill('red');\n }\n }\n
\n\n Consulta Boolean y Number para aprender más sobre estos tipos de datos y las operaciones que admiten.
\n"],"line":[0,110],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// Click the mouse to show the circle.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A white circle on a gray background. The circle follows the mouse user clicks on the canvas.'\n );\n}\n\nfunction draw() {\n background(200);\n\n if (mouseIsPressed === true) {\n circle(mouseX, mouseY, 20);\n }\n}\n
\n\n// Click the mouse to show different shapes.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A white ellipse on a gray background. The ellipse becomes a circle when the user presses the mouse.'\n );\n}\n\nfunction draw() {\n background(200);\n\n if (mouseIsPressed === true) {\n circle(50, 50, 20);\n } else {\n ellipse(50, 50, 20, 50);\n }\n}\n
\n\n// Move the mouse to change the background color.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A square changes color from white to black as the user moves the mouse from left to right.'\n );\n}\n\nfunction draw() {\n if (mouseX < 33) {\n background(255);\n } else if (mouseX < 67) {\n background(200);\n } else {\n background(0);\n }\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A white circle drawn on a gray background. The circle changes color to red when the user presses the \"r\" key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n if (keyIsPressed === true) {\n if (key === 'r') {\n fill('red');\n }\n }\n\n circle(50, 50, 40);\n}\n
\nDeclara una nueva variable.
\nUna variable es un contenedor para un valor. Por ejemplo, una variable podría contener la coordenada x de una criatura como un Number
o su nombre como un String
. Las variables pueden cambiar de valor reasignándolas de la siguiente manera:
\n // Declare the variable x and assign it the value 10.\n let x = 10;\n // Reassign x to 50\n x = 50;
\n
Las variables tienen alcance de bloque. Cuando se declara una variable entre llaves {}
, esta solo existe dentro del bloque definido por esas llaves. Por ejemplo, el siguiente código arrojaría un ReferenceError
porque x
está declarado dentro del bloque de la función setup()
:
\n function setup() {\n createCanvas(100, 100);\n let x = 50;
\n }\n\n function draw() {\n background(200);\n
// x was declared in setup(), so it can't be referenced here.\n circle(x, 50, 20);\n
\n }\n
Las variables declaradas fuera de todas las llaves {}
están en el alcance global. Una variable que está en el alcance global se puede usar y cambiar en cualquier lugar de un boceto:
\n let x = 50;\n function setup() {\n createCanvas(100, 100);\n }
\n\n function draw() {\n background(200);\n
// Change the value of x.\n x += 10;
\n circle(x, 50, 20);\n
\n }\n
\n"],"line":[0,7],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(220);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Create the message variable.\n let message = 'Hello, 🌍!';\n\n // Display the message.\n text(message, 50, 50);\n\n describe('The text \"Hello, 🌍!\" written on a gray background.');\n}\n
\n\nlet x = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle moves from left to right against a gray background.');\n}\n\nfunction draw() {\n background(220);\n\n // Change the value of x.\n x += 1;\n\n circle(x, 50, 20);\n}\n
\nUn número que puede ser positivo, negativo o cero.
\n\nEl tipo de datos Number
es útil para describir valores como posición, tamaño y color. Un número puede ser un número entero como 20 o un número decimal como 12.34. Por ejemplo, la posición y el tamaño de un círculo pueden describirse con tres números:
\n circle(50, 50, 20);\n
\n \n circle(50, 50, 12.34);\n
\n\n Los números admiten operaciones aritméticas básicas y siguen el orden estándar de operaciones: Paréntesis, Exponentes, Multiplicación, División, Suma y Resta. Por ejemplo, es común usar operadores aritméticos con variables del sistema de p5.js que son números:
\n\n\n // Draw a circle at the center. \n circle(width / 2, height / 2, 20);\n
\n \n // Draw a circle that moves from left to right.\n circle(frameCount * 0.01, 50, 20);\n
\n\n Aquí tienes una descripción rápida de los operadores aritméticos:
\n\n\n 1 + 2 // Add\n 1 - 2 // Substract\n 1 * 2 // Multiply\n 1 / 2 // Divide\n 1 % 2 // Remainder\n 1 ** 2 // Exponentiate\n
\n\n Es común actualizar una variable numérica usando aritmética. Por ejemplo, la ubicación de un objeto se puede actualizar así:
\n\n\n x = x + 1;\n
\n\n La declaración anterior suma 1 a la variable x
usando el operador +
. El operador de asignación de suma +=
expresa la misma idea:
\n x += 1;\n
\n\n Aquí tienes una descripción rápida de los operadores de asignación:
\n\n\n x += 2 // Addition assignment\n x -= 2 // Subtraction assignment \n x *= 2 // Multiplication assignment\n x /= 2 // Division assignment\n x %= 2 // Remainder assignment\n
\n\n Los números se pueden comparar usando los operadores de comparación >
, <
, >=
, <=
, ===
y !==
. Por ejemplo, el frameCount de un boceto se puede usar como temporizador:
\n if (frameCount > 1000) {\n text('Game over!', 50, 50);\n }\n
\n\n Una expresión como frameCount > 1000
evalúa a un valor Boolean
que es true
o false
. Todos los operadores relacionales producen valores Boolean
:
\n 2 > 1 // true\n 2 < 1 // false\n 2 >= 2 // true\n 2 <= 2 // true\n 2 === 2 // true\n 2 !== 2 // false\n
\n\n Consulta Boolean para obtener más información sobre comparaciones y condiciones.
\n\nNota: También existen los operadores ==
y !=
con un solo =
. No los uses.
Las expresiones con números también pueden producir valores especiales cuando algo sale mal:
\n\n\n sqrt(-1) // NaN\n 1 / 0 // Infinity\n
\n\n El valor NaN
significa Not-A-Number. NaN
aparece cuando los cálculos o conversiones no funcionan. Infinity
es un valor que es mayor que cualquier número. Aparece durante ciertos cálculos.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw a circle at the center.\n circle(50, 50, 70);\n\n // Draw a smaller circle at the center.\n circle(width / 2, height / 2, 30);\n\n describe('Two concentric, white circles drawn on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle travels from left to right on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n circle(frameCount * 0.01, 50, 20);\n}\n
\nUn contenedor para datos almacenados como pares clave-valor.
Los objetos ayudan a organizar datos relacionados de cualquier tipo, incluidos otros objetos. Un valor almacenado en un objeto puede ser accedido por nombre, llamado su clave. Cada par clave-valor se llama \"propiedad\". Los objetos son similares a los diccionarios en Python y a los mapas en Java y Ruby.
Por ejemplo, un objeto podría contener la ubicación, tamaño y apariencia de un perro:
\n // Declare the dog variable and assign it an object.\n let dog = { x: 50, y: 50, size: 20, emoji: '🐶' };\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(dog.size);
\n // Draw the dog.\n text(dog.emoji, dog.x, dog.y);
\n
\nLa variable dog
se asigna a un objeto con cuatro propiedades. Los objetos se declaran con llaves {}
. Los valores pueden ser accedidos usando el operador de punto, como en dog.size
. En el ejemplo anterior, la clave size
corresponde al valor 20
. Los objetos también pueden estar vacíos al principio:
\n // Declare a cat variable and assign it an empty object.\n let cat = {};\n // Add properties to the object.\n cat.x = 50;\n cat.y = 50;\n cat.size = 20;\n cat.emoji = '🐱';
\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(cat.size);
\n // Draw the cat.\n text(cat.emoji, cat.x, cat.y);
\n
\nLos datos de un objeto pueden actualizarse mientras se ejecuta un boceto. Por ejemplo, el cat
podría huir del dog
actualizando su ubicación:
\n // Run to the right.\n cat.x += 5;\n
\nSi es necesario, los valores de un objeto pueden ser accedidos usando corchetes []
y cadenas en lugar de la notación de punto:
\n // Run to the right.\n cat[\"x\"] += 5;\n
\nEsta sintaxis puede ser útil cuando el nombre de la clave tiene espacios, como en cat['height (m)']
.
\n// Declare the variable data and assign it an object with three properties.\nlet data = { x: 50, y: 50, d: 20 };\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the object's values using the . operator.\n circle(data.x, data.y, data.d);\n}\n
\n\n// Declare the variable data and assign it an object with three properties.\nlet data = { x: 50, y: 50, d: 20 };\n\n// Add another property for color.\ndata.color = 'deeppink';\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A pink circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the object's values using the . operator.\n fill(data.color);\n circle(data.x, data.y, data.d);\n}\n
\n\n\n// Declare the variable data and assign it an object with three properties.\nlet data = { x: 50, y: 50, d: 20 };\n\n// Add another property for color.\ndata.color = 'deeppink';\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the object's values using the . operator.\n fill(data.color);\n circle(data.x, data.y, data.d);\n\n // Update the object's x and y properties.\n data.x += random(-1, 1);\n data.y += random(-1, 1);\n}\n
\nUna secuencia de caracteres de texto
El tipo de datos String
es útil para trabajar con texto. Por ejemplo una cadena podría contener un mensaje de bienvenida:
// Use a string literal. text('Hello!', 10, 10);
// Create a string variable. let message = 'Hello!';
// Use the string variable. text(message, 10, 10);
La forma más común de crear cadenas es usando algún tipo de comillas: text(\"hi\", 50, 50);
text('hi', 50, 50);
text(`hi`, 50, 50);
\"hi\"
, 'hi'
, and hi
son todos \"literales\" de cadena. Un \"literal\" es un elemento que representa directamente un valor, por ejemplo text('hi', 50, 50)
. En cambio, text(message, 50, 50)
usa la variable message
, por lo que no es un literal de cadena.
Las comillas simples ''
y las comillas dobles \"\"
significan lo mismo. Es bueno tener la opción para casos en los que una cadena contiene un tipo de comilla:
text(\"What's up?\", 50, 50);
text('Air quotes make you look \"cool.\"', 50, 50);
Las comillas invertidas ```` crean plantillas de literales . Las plantillas de literales tienen muchos usos. Por ejemplo, pueden contener tanto comillas simples como dobles según sea necesario:
text(`\"Don't you forget about me\"`, 10, 10);
Las plantillas de literales son útiles cuando las cadenas se crean a partir de variables de la siguiente manera:
let size = random(10, 20); circle(50, 50, size); text(The circle's diameter is ${size} pixels.
, 10, 10);
El valor de la variable size
reemplazará ${size}
cuando se cree la cadena. ${}
is a placeholder for any value. es un marcador de posición para cualquier valor. Eso significa que se puede usar una expresión, como ${round(PI, 3)}
. Todos los siguientes son plantillas de literales válidos:
text(`π is about {mouseX < width / 2} that I'm on the left half of the canvas.`, 10, 30);
Las plantillas de literales pueden incluir distintas variables:
let x = random(0, 100); let y = random(0, 100); let size = random(10, 20); circle(x, y, size); text(The circle at (${x}, ${y}) has a diameter of ${size} pixels.
, 10, 10);
Las plantillas de literales también son útiles para crear texto de varias líneas como:
let poem = `My sketch doesn't run; it waits for me patiently while bugs point the way.`; text(poem, 10, 10);
\n"],"line":[0,709],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(20);\n\n // Display a welcome message.\n text('Hello!', 50, 50);\n\n describe('The text \"Hello!\" written on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(20);\n\n // Create a string variable.\n let world = '🌍';\n\n // Display a welcome message using a template string.\n text(`Hello, ${world}!`, 50, 50);\n\n describe('The text \"Hello, 🌍!\" written on a gray background.');\n}\n
\nUna forma de repetir un bloque de código.
Los bucles while
son útiles para repetir declaraciones mientras una condición sea true
. Son como declaraciones if
que se repiten. Por ejemplo, un bucle while
facilita expresar la idea \"dibujar varias líneas\" de la siguiente manera:
\n // Declare a variable to keep track of iteration.\n let x = 10;\n // Repeat as long as x < 100\n while (x < 100) {\n line(x, 25, x, 75);\n
\n // Increment by 20.\n x += 20;\n }
\n
\nEl encabezado del bucle comienza con la palabra clave while
. Los bucles generalmente cuentan hacia arriba o hacia abajo mientras se repiten, o iteran. La declaración entre paréntesis x < 100
es una condición que el bucle verifica cada vez que itera. Si la condición es true
, el bucle ejecuta el código entre las llaves {}
. El código entre las llaves corresponde al cuerpo del bucle. Si la condición es false
, se salta el cuerpo y se detiene el bucle.
Es común crear bucles infinitos accidentalmente. Por ejemplo, el siguiente bucle nunca deja de iterar porque no cuenta hacia arriba:
\n // Declare a variable to keep track of iteration.\n let x = 10;\n // Repeat as long as x < 100\n while (x < 100) {\n line(x, 25, x, 75);\n }
\n // This should be in the loop's body!\n x += 20;\n
\n
\nLa declaración x += 20
aparece después del cuerpo del bucle. Eso significa que la variable x
está atascada en 10
, que siempre es menor que 100
.
Los bucles while
son útiles cuando el número de iteraciones no se conoce de antemano. Por ejemplo, se podrían dibujar círculos concéntricos en incrementos aleatorios:
\n let d = 100;\n let minSize = 5;\n while (d > minSize) {\n circle(50, 50, d);\n d -= random(10);\n }
\n
\n"],"line":[0,1908],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Five black vertical lines on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Declare a variable to keep track of iteration.\n let x = 10;\n\n // Repeat as long as x < 100\n while (x < 100) {\n line(x, 25, x, 75);\n\n // Increment by 20.\n x += 20\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(5);\n\n describe(\n \"A gray square with several concentric circles at the center. The circles' sizes decrease at random increments.\"\n );\n}\n\nfunction draw() {\n background(200);\n\n let d = 100;\n let minSize = 5;\n\n while (d > minSize) {\n circle(50, 50, d);\n d -= random(5, 15);\n }\n}\n
\nPrints a message to the web browser's console.
\nThe console\nobject is helpful for printing messages while debugging. For example, it's\ncommon to add a console.log()
statement while studying how a section of\ncode works:
if (isPlaying === true) {\n // Add a console.log() statement to make sure this block of code runs.\n console.log('Got here!');\n\n // Game logic.\n}\n
\nconsole.error()
is helpful for tracking errors because it prints\nformatted messages. For example, it's common to encounter errors when\nloading media assets:
// Logs an error message with special formatting.\nfunction handleFailure(error) {\n console.error('Oops!', error);\n}\n\n// Try to load an image and call handleError() if it fails.\nloadImage('https://example.com/cat.jpg', handleImage, handleError);\n
\n"],"line":[0,2028],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n noCanvas();\n\n // Prints \"Hello!\" to the console.\n console.log('Hello!');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Try to load an image from a fake URL.\n // Call handleError() if the image fails to load.\n loadImage('https://example.com/cat.jpg', handleImage, handleError);\n}\n\n// Displays the image.\nfunction handleImage(img) {\n image(img, 0, 0);\n\n describe('A cat on a gray background.');\n}\n\n// Prints the error.\nfunction handleError(error) {\n console.error('Oops!', error);\n\n describe('A gray square.');\n}\n
\nA list that keeps several pieces of data in order.
\nArrays are helpful for storing related data. They can contain data of any\ntype. For example, an array could contain a list of someone's favorite\ncolors as strings. Arrays are created as follows:
\nlet myArray = ['deeppink', 'darkorchid', 'magenta'];\n
\nEach piece of data in an array is called an element. Each element has an\naddress, or index, within its array. The variable myArray
refers to an\narray with three String elements, 'deeppink'
,\n'darkorchid'
, and 'magenta'
. Arrays are zero-indexed, which means\nthat 'deeppink'
is at index 0, 'darkorchid'
is at index 1, and\n'magenta'
is at index 2. Array elements can be accessed using their\nindices as follows:
let zeroth = myArray[0]; // 'deeppink'\nlet first = myArray[1]; // 'darkorchid'\nlet second = myArray[2]; // 'magenta'\n
\nElements can be added to the end of an array by calling the\npush()\nmethod as follows:
\nmyArray.push('lavender');\n\nlet third = myArray[3]; // 'lavender'\n
\nSee MDN\nfor more information about arrays.
\n"],"line":[0,1140],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// Declare the variable xCoordinates and assign it an array\n// with three numeric elements.\nlet xCoordinates = [25, 50, 75];\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'Three white circles drawn in a horizontal line on a gray background.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Access the element at index 0, which is 25.\n circle(xCoordinates[0], 50, 20);\n\n // Access the element at index 1, which is 50.\n circle(xCoordinates[1], 50, 20);\n\n // Access the element at index 2, which is 75.\n circle(xCoordinates[2], 50, 20);\n}\n
\n\n// Declare the variable xCoordinates and assign it an array with three numeric elements.\nlet xCoordinates = [20, 40, 60];\n\n// Add another element to the end of the array.\nxCoordinates.push(80);\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Four white circles drawn in a horizontal line on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the element at index 0, which is 20.\n circle(xCoordinates[0], 50, 20);\n\n // Access the element at index 1, which is 40.\n circle(xCoordinates[1], 50, 20);\n\n // Access the element at index 2, which is 60.\n circle(xCoordinates[2], 50, 20);\n\n // Access the element at index 3, which is 80.\n circle(xCoordinates[3], 50, 20);\n}\n
\n\n// Declare the variable xCoordinates and assign it an empty array.\nlet xCoordinates = [];\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Add elements to the array using a loop.\n for (let x = 20; x < 100; x += 20) {\n xCoordinates.push(x);\n }\n\n describe('Four white circles drawn in a horizontal line on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the element at index i and use it to draw a circle.\n for (let i = 0; i < xCoordinates.length; i += 1) {\n circle(xCoordinates[i], 50, 20);\n }\n}\n
\n\n// Declare the variable xCoordinates and assign it an empty array.\nlet xCoordinates = [];\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Add elements to the array using a loop.\n for (let x = 20; x < 100; x += 20) {\n xCoordinates.push(x);\n }\n\n describe('Four white circles drawn in a horizontal line on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access each element of the array and use it to draw a circle.\n for (let x of xCoordinates) {\n circle(x, 50, 20);\n }\n}\n
\n\n// Declare the variable xCoordinates and assign it an empty array.\nlet xCoordinates = [];\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Add elements to the array using a loop.\n for (let x = 20; x < 100; x += 20) {\n xCoordinates.push(x);\n }\n\n describe(\n 'Four white circles in a horizontal line on a gray background. The circles move randomly.'\n );\n}\n\nfunction draw() {\n background(200);\n\n for (let i = 0; i < xCoordinates.length; i += 1) {\n // Update the element at index i.\n xCoordinates[i] += random(-1, 1);\n\n // Use the element at index i to draw a circle.\n circle(xCoordinates[i], 50, 20);\n }\n}\n
\nA value that's either true
or false
.
Boolean
values help to make decisions in code. They appear any time a\nlogical condition is checked. For example, the condition\n\"Is a mouse button being pressed?\" must be either true
or\nfalse
:
// If the user presses the mouse, draw a circle at\n// the mouse's location.\nif (mouseIsPressed === true) {\n circle(mouseX, mouseY, 20);\n}\n
\nThe if
statement checks whether\nmouseIsPressed is true
and draws a\ncircle if it is. Boolean
expressions such as mouseIsPressed === true
\nevaluate to one of the two possible Boolean
values: true
or false
.
The ===
operator (EQUAL) checks whether two values are equal. If they\nare, the expression evaluates to true
. Otherwise, it evaluates to\nfalse
.
Note: There's also a ==
operator with two =
instead of three. Don't use\nit.
The mouseIsPressed system variable is\nalways true
or false
, so the code snippet above could also be written\nas follows:
if (mouseIsPressed) {\n circle(mouseX, mouseY, 20);\n}\n
\nThe !==
operator (NOT EQUAL) checks whether two values are not equal, as\nin the following example:
if (2 + 2 !== 4) {\n text('War is peace.', 50, 50);\n}\n
\nStarting from the left, the arithmetic expression 2 + 2
produces the\nvalue 4
. The Boolean
expression 4 !== 4
evaluates to false
because\n4
is equal to itself. As a result, the if
statement's body is skipped.
Note: There's also a !=
operator with one =
instead of two. Don't use\nit.
The Boolean
operator &&
(AND) checks whether two expressions are both\ntrue
:
if (keyIsPressed === true && key === 'p') {\n text('You pressed the \"p\" key!', 50, 50);\n}\n
\nIf the user is pressing a key AND that key is 'p'
, then a message will\ndisplay.
The Boolean
operator ||
(OR) checks whether at least one of two\nexpressions is true
:
if (keyIsPressed === true || mouseIsPressed === true) {\n text('You did something!', 50, 50);\n}\n
\nIf the user presses a key, or presses a mouse button, or both, then a\nmessage will display.
\nThe following truth table summarizes a few common scenarios with &&
and\n||
:
true && true // true\ntrue && false // false\nfalse && false // false\ntrue || true // true\ntrue || false // true\nfalse || false // false\n
\nThe relational operators >
, << code=\"\">,
>=
, and <=< code=\"\"> also produce
<>Boolean
\nvalues:=<>
2 > 1 // true\n2 < 1 // false\n2 >= 2 // true\n2 <= 2=\"\" true=\"\" <=\"\" code=\"\"/>
\nSee if for more information about if
statements and\nNumber for more information about Number
s.
\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A gray square. When the user presses the mouse, a circle appears at that location.');\n}\n\nfunction draw() {\n background(200);\n\n // If the user presses the mouse, draw a circle at that location.\n if (mouseIsPressed) {\n circle(mouseX, mouseY, 20);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A gray square. When the user presses the mouse, a circle appears at that location.');\n}\n\nfunction draw() {\n background(200);\n\n // If the user presses the mouse, draw a circle at that location.\n if (mouseIsPressed === true) {\n circle(mouseX, mouseY, 20);\n }\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A gray square that turns pink when the user presses the mouse or a key.');\n}\n\nfunction draw() {\n background(200);\n\n // If the user presses the mouse, change the background color.\n if (mouseIsPressed === true || keyIsPressed === true) {\n background('deeppink');\n }\n}\n
\n\n// Click the canvas to begin detecting key presses.\n\n// Create a Boolean variable.\nlet isPlaying = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'The message \"Begin?\\nY or N\" written in green on a black background. The message \"Good luck!\" appears when they press the \"y\" key.'\n );\n}\n\nfunction draw() {\n background(0);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textFont('Courier New');\n textSize(16);\n fill(0, 255, 0);\n\n // Display a different message when the user begins playing.\n if (isPlaying === false) {\n text('Begin?', 50, 40);\n text('Y or N', 50, 60);\n } else {\n text('Good luck!', 50, 50);\n }\n}\n\n// Start playing when the user presses the 'y' key.\nfunction keyPressed() {\n if (key === 'y') {\n isPlaying = true;\n }\n}\n
\nA number that can be positive, negative, or zero.
\nThe Number
data type is useful for describing values such as position,\nsize, and color. A number can be an integer such as 20 or a decimal number\nsuch as 12.34. For example, a circle's position and size can be described\nby three numbers:
circle(50, 50, 20);\n
\ncircle(50, 50, 12.34);\n
\nNumbers support basic arithmetic and follow the standard order of\noperations: Parentheses, Exponents, Multiplication, Division, Addition,\nand Subtraction (PEMDAS). For example, it's common to use arithmetic\noperators with p5.js' system variables that are numbers:
\n// Draw a circle at the center.\ncircle(width / 2, height / 2, 20);\n
\n// Draw a circle that moves from left to right.\ncircle(frameCount * 0.01, 50, 20);\n
\nHere's a quick overview of the arithmetic operators:
\n1 + 2 // Add\n1 - 2 // Subtract\n1 * 2 // Multiply\n1 / 2 // Divide\n1 % 2 // Remainder\n1 ** 2 // Exponentiate\n
\nIt's common to update a number variable using arithmetic. For example, an\nobject's location can be updated like so:
\nx = x + 1;\n
\nThe statement above adds 1 to a variable x
using the +
operator. The\naddition assignment operator +=
expresses the same idea:
x += 1;\n
\nHere's a quick overview of the assignment operators:
\nx += 2 // Addition assignment\nx -= 2 // Subtraction assignment\nx *= 2 // Multiplication assignment\nx /= 2 // Division assignment\nx %= 2 // Remainder assignment\n
\nNumbers can be compared using the\nrelational operators\n>
, << code=\"\">,
>=
, <=< code=\"\">,
<>===
, and !==
. For example, a sketch's\nframeCount can be used as a timer:=<>
if (frameCount > 1000) {\n text('Game over!', 50, 50);\n}\n
\nAn expression such as frameCount > 1000
evaluates to a Boolean
value\nthat's either true
or false
. The relational operators all produce\nBoolean
values:
2 > 1 // true\n2 < 1 // false\n2 >= 2 // true\n2 <= 2=\"\" true=\"\" !=\"=\" false=\"\" <=\"\" code=\"\"/>
\nSee Boolean for more information about comparisons and conditions.
\nNote: There are also ==
and !=
operators with one fewer =
. Don't use them.
Expressions with numbers can also produce special values when something\ngoes wrong:
\nsqrt(-1) // NaN\n1 / 0 // Infinity\n
\nThe value NaN
stands for\nNot-A-Number.\nNaN
appears when calculations or conversions don't work. Infinity
is a\nvalue that's larger than any number. It appears during certain\ncalculations.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw a circle at the center.\n circle(50, 50, 70);\n\n // Draw a smaller circle at the center.\n circle(width / 2, height / 2, 30);\n\n describe('Two concentric, white circles drawn on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle travels from left to right on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n circle(frameCount * 0.05, 50, 20);\n}\n
\nA container for data that's stored as key-value pairs.
\nObjects help to organize related data of any type, including other objects.\nA value stored in an object can be accessed by name, called its key. Each\nkey-value pair is called a \"property.\" Objects are similar to dictionaries\nin Python and maps in Java and Ruby.
\nFor example, an object could contain the location, size, and appearance of\na dog:
\n// Declare the dog variable and assign it an object.\nlet dog = { x: 50, y: 50, size: 20, emoji: '🐶' };\n\n// Style the text.\ntextAlign(CENTER, CENTER);\ntextSize(dog.size);\n\n// Draw the dog.\ntext(dog.emoji, dog.x, dog.y);\n
\nThe variable dog
is assigned an object with four properties. Objects\nare declared with curly braces {}
. Values can be accessed using the dot\noperator, as in dog.size
. In the example above, the key size
\ncorresponds to the value 20
. Objects can also be empty to start:
// Declare a cat variable and assign it an empty object.\nlet cat = {};\n\n// Add properties to the object.\ncat.x = 50;\ncat.y = 50;\ncat.size = 20;\ncat.emoji = '🐱';\n\n// Style the text.\ntextAlign(CENTER, CENTER);\ntextSize(cat.size);\n\n// Draw the cat.\ntext(cat.emoji, cat.x, cat.y);\n
\nAn object's data can be updated while a sketch runs. For example, the cat
\ncould run away from the dog
by updating its location:
// Run to the right.\ncat.x += 5;\n
\nIf needed, an object's values can be accessed using square brackets []
\nand strings instead of dot notation:
// Run to the right.\ncat[\"x\"] += 5;\n
\nThis syntax can be helpful when the key's name has spaces, as in\ncat['height (m)']
.
\n// Declare the variable data and assign it an object with three properties.\nlet data = { x: 50, y: 50, d: 20 };\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the object's values using the . operator.\n circle(data.x, data.y, data.d);\n}\n
\n\n// Declare the variable data and assign it an object with three properties.\nlet data = { x: 50, y: 50, d: 20 };\n\n// Add another property for color.\ndata.color = 'deeppink';\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A pink circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the object's values using the . operator.\n fill(data.color);\n circle(data.x, data.y, data.d);\n}\n
\n\n// Declare the variable data and assign it an object with three properties.\nlet data = { x: 50, y: 50, d: 20 };\n\n// Add another property for color.\ndata.color = 'deeppink';\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the object's values using the . operator.\n fill(data.color);\n circle(data.x, data.y, data.d);\n\n // Update the object's x and y properties.\n data.x += random(-1, 1);\n data.y += random(-1, 1);\n}\n
\nA sequence of text characters.
\nThe String
data type is helpful for working with text. For example, a\nstring could contain a welcome message:
// Use a string literal.\ntext('Hello!', 10, 10);\n
\n// Create a string variable.\nlet message = 'Hello!';\n\n// Use the string variable.\ntext(message, 10, 10);\n
\nThe most common way to create strings is to use some form of quotations as\nfollows:
\ntext(\"hi\", 50, 50);\n
\ntext('hi', 50, 50);\n
\ntext(`hi`, 50, 50);\n
\n\"hi\"
, 'hi'
, and hi
are all string literals. A \"literal\" means a\nvalue was actually written, as in text('hi', 50, 50)
. By contrast,\ntext(message, 50, 50)
uses the variable message
, so it isn't a string\nliteral.
Single quotes ''
and double quotes \"\"
mean the same thing. It's nice to\nhave the option for cases when a string contains one type of quote:
text(\"What's up?\", 50, 50);\n
\ntext('Air quotes make you look \"cool.\"', 50, 50);\n
\nBackticks ``
create template literals. Template literals have many uses.\nFor example, they can contain both single and double quotes as needed:
text(`\"Don't you forget about me\"`, 10, 10);\n
\nTemplate literals are helpful when strings are created from variables like\nso:
\nlet size = random(10, 20);\ncircle(50, 50, size);\n\ntext(`The circle's diameter is ${size} pixels.`, 10, 10);\n
\nThe size
variable's value will replace ${size}
when the string is\ncreated. ${}
is a placeholder for any value. That means an expression can\nbe used, as in ${round(PI, 3)}
. All of the following are valid template\nliterals:
text(`π is about ${round(PI, 2)} pixels.`, 10, 10);\ntext(`It's ${mouseX < width / 2} that I'm on the left half of the canvas.`, 10, 30);\n
\nTemplate literals can include several variables:
\nlet x = random(0, 100);\nlet y = random(0, 100);\nlet size = random(10, 20);\ncircle(x, y, size);\n\ntext(`The circle at (${x}, ${y}) has a diameter of ${size} pixels.`, 10, 10);\n
\nTemplate literals are also helpful for creating multi-line text like so:
\nlet poem = `My sketch doesn't run;\nit waits for me patiently\nwhile bugs point the way.`;\n\ntext(poem, 10, 10);\n
\n"],"line":[0,710],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(20);\n\n // Display a welcome message.\n text('Hello!', 50, 50);\n\n describe('The text \"Hello!\" written on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(20);\n\n // Create a string variable.\n let world = '🌍';\n\n // Display a welcome message using a template string.\n text(`Hello, ${world}!`, 50, 50);\n\n describe('The text \"Hello, 🌍!\" written on a gray background.');\n}\n
\n