\n\n\n
第四个和第五个参数,dw
和dh
是可选的。他们设定了绘制目标图像的宽度和高度。默认情况下,image()
按原始尺寸绘制完整的源图像。
第六和第七个参数,sx
和 sy
也是可选的。\n\n\n这些坐标定义了从源图像中绘制的分段左上角。
第八个和第九个参数,sw
和 sh
也是可选的。\n\n\n这些坐标定义了从源图像中绘制的分段宽度和高度。默认情况下,image()
绘制从 (sx, sy)
开始并延伸到源图像边缘的完整分段。
第九个参数,fit
,也是可选的。在不影响其纵横比的情况下,它绘制了源图像的分段。如果 CONTAIN
通过了,在目标矩形中会出现完整的分段。如果 COVER
通过了,则该分段将完全覆盖目标矩形。这可能会产生分段放大的效果。
第十个和第十一个参数,xAlign
和\nyAlign
,也是可选的。他们确定如何对齐拟合的分段。\nxAlign
可以设置为 LEFT
、RIGHT
或\nCENTER
。 yAlign
可以设置为\n\n\nTOP
、BOTTOM
或 CENTER
。默认情况下,xAlign
和 yAlign
设置为 CENTER
。
要显示的图像。
"],"type":[0,"p5.Image|p5.Element|p5.Texture|p5.Framebuffer|p5.FramebufferTexture"]}],[0,{"name":[0,"x"],"description":[0,"\n图像左上角的 x 坐标。
"],"type":[0,"数字"]}],[0,{"name":[0,"y"],"description":[0,"\n图像左上角的 y 坐标。
"],"type":[0,"数字"]}],[0,{"name":[0,"width"],"description":[0,"\n绘制图像的宽度。
"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"height"],"description":[0,"\n绘制图像的高度。
"],"type":[0,"数字"],"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,"\n目标矩形 x 坐标\n\n 在其中绘制源图像的矩形
"],"type":[0,"数字"]}],[0,{"name":[0,"dy"],"description":[0,"\n目标矩形 y 坐标\n\n 在其中绘制源图像的矩形
"],"type":[0,"数字"]}],[0,{"name":[0,"dWidth"],"description":[0,"\n目标矩形的宽度
"],"type":[0,"数字"]}],[0,{"name":[0,"dHeight"],"description":[0,"\n目标矩形的高度
"],"type":[0,"数字"]}],[0,{"name":[0,"sx"],"description":[0,"\n要绘制到目标矩形的源图形分段 x 坐标
"],"type":[0,"数字"]}],[0,{"name":[0,"sy"],"description":[0,"\n要绘制到目标矩形的源图形分段 y 坐标
"],"type":[0,"数字"]}],[0,{"name":[0,"sWidth"],"description":[0,"\n要绘制到目标矩形的源图形分段的宽度
"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"sHeight"],"description":[0,"\n要绘制到目标矩形的源图形分段的高度
"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"fit"],"description":[0,"\nCONTAINER 或 COVER
"],"type":[0,"常量"],"optional":[0,true]}],[0,{"name":[0,"xAlign"],"description":[0,"\nLEFT、RIGHT 或 CENTER。默认请款下为 CENTER
"],"type":[0,"常量"],"optional":[0,true]}],[0,{"name":[0,"yAlign"],"description":[0,"\nTOP、BOTTOM 或 CENTER。默认情况下为 CENTER
"],"type":[0,"常量"],"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
\n调用 image() 更改图像的绘制位置。
\n\n\n默认情况下,image() 前两个参数是图像左上角的 x 和 y 坐标。接下来的参数是\n它的宽度和高度。和上面相同,调用\nimageMode(CORNER)
。
imageMode(CORNERS)
也使用 image() 前两个参数作为图像左上角的 x 和 y 坐标。第三个和第四个参数是它右下角的坐标。
imageMode(CENTER)
使用前两个参数 image() 作为图像中心的 x 和 y 坐标。接下来的参数是它的宽度和高度。
CORNER 、CORNERS或CENTER。
"],"type":[0,"常量"]}]]],"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
\n加载图像来创建一个 p5.Image 对象。
\n\n\nloadImage()
的第一个参数有三种方式来解释。\n\"如果传入一个图片路径,loadImage()
将加载它。本地文件应该使用相对路径,例如'/assets/thundercat.jpg'
。网址例如 'https\":\"//example.com/thundercat.jpg'
可能因浏览器安全原因被屏蔽。原始图像数据也可以通过 'data:image/png;base64,arandomsequenceofcharacters'
作为 base64 编码图像传递。
第二个参数是可选的。如果传入一个函数,图像加载后,它会被调用。回调函数可以选择使用\n\n\n新的 p5.Image 对象。
\n\n\n第三个参数也是可选的。如果传入一个函数,图像加载失败时它会被调用。这个回调函数可以选择使用错误事件。
\n\n\n加载图像可能需要一些时间。在 preload() 中调用 loadImage()
, 可以确保图像在 setup() 或 draw() 使用之前先加载。
要加载的图片或base64编码图片的路径。
"],"type":[0,"字符串"]}],[0,{"name":[0,"successCallback"],"description":[0,"\n一旦图像加载,用 p5.Image 调用函数。
"],"type":[0,"函数(p5.Image)"],"optional":[0,true]}],[0,{"name":[0,"failureCallback"],"description":[0,"\n如果图像加载失败,通过事件错误调用函数。
"],"type":[0,"函数(事件)"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"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
\n删除用 tint() 设定的当前色调。
\n\nnoTint()
将图像恢复成其原始颜色。
\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
\n从绘图生成 GIF 并将其保存到文件中。
\n\n\n可以在 setup() 或任何绘图运行时的点调用 saveGif()
。
第一个参数,fileName
,设置 GIF 的文件名。
第二个参数,duration
,设置 GIF 的持续秒时间。
第三个参数options
是可选的。如果一个对象通过了, saveGif()
将使用其属性来自定义 GIF。\nsaveGif()
识别属性delay
、units
、\nsilent
,\nnotificationDuration
和 notificationID
。
GIF 文件名。
"],"type":[0,"字符串"]}],[0,{"name":[0,"duration"],"description":[0,"\n从绘图中捕获的持续时间以秒为单位。
"],"type":[0,"数字"]}],[0,{"name":[0,"options"],"description":[0,"\n一个对象可以包含另外五个属性:\n\n delay
,一个数字,指定录制前等待的时间;\n\n units
,一个字符串,可以是“秒”或“帧”。默认为“秒”;\n\n silent
,一个布尔定义进度通知的存在。默认为 false
;\n\n notificationDuration
,一个数字,定义最终通知的时长以秒为单位会活下去。默认情况下它是0
,这意味着通知永远不会被删除;\n\n\"notificationID
,一个指定通知 DOM 的元素 id 的字符串。默认情况下它是'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
\n使用颜色对图像进行着色。
\n\n\n带有一个参数的 tint()
版本可以用以下四种方式之一来解释。\n\n\n如果参数是数字,则将其解释为灰度值。如果\n参数是一个字符串,则将其解释为 CSS 颜色字符串。一个 [R, G, B, A]
数组或 p5.Color 对象\n也可用于设置色调颜色。
带有两个参数的 tint()
版本使用第一个参数作为一个灰度值,第二个作为 alpha 值。例如,调用 tint(255, 128)
可以使图像 50% 透明。
取决于当前的 colorMode() 具有三个参数的 tint()
版本可以将它们解释为\nRGB 或 HSB 值。可选的第四个参数设置 alpha 值。例如, tint(255, 0, 0, 100)
将图片设置成红色调并使它们透明。
红色或色调值。
"],"type":[0,"数字"]}],[0,{"name":[0,"v2"],"description":[0,"\n绿色或饱和度值。
"],"type":[0,"数字"]}],[0,{"name":[0,"v3"],"description":[0,"\n蓝色或亮度。
"],"type":[0,"数字"]}],[0,{"name":[0,"alpha"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"\nCSS 颜色字符串。
"],"type":[0,"字符串"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gray"],"description":[0,"\n灰度值。
"],"type":[0,"数字"]}],[0,{"name":[0,"alpha"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"values"],"description":[0,"\n包含红、绿、蓝的数组 & 颜色的 Alpha 分量。
"],"type":[0,"数字[]"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"\n色调
"],"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
\n创建一个新的 p5.Image 对象。
\n\ncreateImage()
使用 width
和 height
参数来设置新的 \n\n p5.Image 对象的像素尺寸。新的 \n\n p5.Image 可以通过更新 \n\n pixels 数组或调用 \n\n get() 和 \n\n set() 方法来修改。在读取或修改像素值之前,必须调用 \n\n loadPixels() 方法。必须调用 \n\n updatePixels() 方法,使更新生效。
注意:默认状况下,新的 p5.Image 对象是透明的。
"],"line":[0,15],"params":[1,[[0,{"name":[0,"width"],"description":[0,"\n宽度以像素为单位。
"],"type":[0,"整数"]}],[0,{"name":[0,"height"],"description":[0,"\n高度以像素为单位。
"],"type":[0,"整数"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"新的 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
\n将当前画布另存为图像。
\n\n\n在默认情况下,saveCanvas()
将画布保存为 PNG 图像并命名为untitled.png
。
第一个参数filename
是可选的。它是一个字符串用来设置文件名。如果包含文件扩展名,例如saveCanvas('drawing.png')
,图像将使用其格式保存。
第二个参数extension
也是可选的。它设置了文件格式。\n\n\"可以使用 'png'
或 'jpg'
。例如,\"\n\"saveCanvas('drawing', 'jpg')
\"\n会将画布保存到名为 drawing.jpg
的文件中。
注意:浏览器将立即保存文件或弹出对话窗口,提示用户。
"],"line":[0,153],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"selectedCanvas"],"description":[0,"\n参考 特定的 HTML5 画布元素。
"],"type":[0,"p5.Framebuffer|p5.Element|HTMLCanvasElement"]}],[0,{"name":[0,"filename"],"description":[0,"\n文件名。默认为“无标题”。
"],"type":[0,"字符串"],"optional":[0,true]}],[0,{"name":[0,"extension"],"description":[0,"\n文件扩展名,“jpg” 或 “png”。默认为 “png”。
"],"type":[0,"字符串"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"filename"],"description":[0,""],"type":[0,"字符串"],"optional":[0,true]}],[0,{"name":[0,"extension"],"description":[0,""],"type":[0,"字符串"],"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
\n从画布中捕获一系列帧,可以另存为图片。
\n\nsaveFrames()
创建一个帧对象数组。每一帧存储为一个对象,其文件类型、文件名和图像数据为字符串。例如,第一个保存的帧可以具有以下属性:
{ ext: \"'png', filename: 'frame0', imageData:\"\n\"'data\":\"image/octet-stream;base64, abc123'}
。
第一个参数filename
设置文件的前缀名称。例如,将前缀设置为 'frame'
会生成图像\"\n文件frame0.png
、frame1.png
等。
第二个参数extension
将文件类型设置为\n\"'png'
或 'jpg'
.
第三个参数duration
设置录制时间,以秒计算。\n\n最长持续时间为 15 秒。
第四个参数framerate
,设置每秒录制帧数。最大帧速率值为 22。有限制duration
和 framerate
以避免使用过多内存。录制大画布很容易使绘图甚至网络浏览器崩溃。
第五个参数,callback
,是可选的。如果传入回调函数,\n在默认情况下,系统不会保存图像文件。我们可以通过这个回调函来处理这个数组里的所有数据。它包含了所有捕捉到的帧,每一帧也包含了具有三个属性的对象:imageData
、filename
和\nextension
。
注意:在默认情况下,帧会作为单独的图像文件下载。
"],"line":[0,558],"params":[1,[[0,{"name":[0,"filename"],"description":[0,"\n文件名前缀。
"],"type":[0,"字符串"]}],[0,{"name":[0,"extension"],"description":[0,"\n文件扩展名,“jpg” 或 “png”。
"],"type":[0,"字符串"]}],[0,{"name":[0,"duration"],"description":[0,"\n录制的持续时间以秒为单位。该参数将被限制为小于或等于 15。
"],"type":[0,"数字"]}],[0,{"name":[0,"framerate"],"description":[0,"\n每秒保存的帧数。该参数将被限制为小于或等于 22。
"],"type":[0,"数字"]}],[0,{"name":[0,"callback"],"description":[0,"\n回调函数将被用来处理图像数据。这个函数应该接受一个数组作为参数。这数组将包含指定数量对象的帧。每个对象有三个属性:imageData
、filename
和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
\n改变光标样式。
\n\n\n第一个参数,type
,设置要显示的光标类型。内置选项有: ARROW
、CROSS
、\nHAND
、MOVE
、TEXT
和\nWAIT
。\n\n\n\"cursor()
也可以识别以字符串形式传递的标准 CSS 光标属性: 'help'
,'wait'
,'crosshair'
,\"\n\"'not-allowed'
,'zoom-in'
和 'grab'
。\"\n\n如果传递的是图像路径,例如:\n\"cursor('/assets/target.png')
,那么光标将以图像的形式展现出来。\"\n\n图像格式必须是 .cur、.gif、.jpg、.jpeg 或 .png,要以这样的形式传递: ,最高像素为 32x32。
x
和 y
都是可选项。如果用图像作光标,x
和 y
用来设置图像中指向的位置。 它们初始值都是 0,此时光标指向图像左上角。并且 x
和 y
的值必须分别小于图像的宽高。
内置:ARROW、CROSS、HAND、MOVE、TEXT、 WAIT\n\n \n原生 CSS 属性:'grab'、'progress'等\n\n \n光标图片路径
"],"type":[0,"字符串|常量"]}],[0,{"name":[0,"x"],"description":[0,"\n光标在水平方向的位置
"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"y"],"description":[0,"\n光标在垂直方向的位置
"],"type":[0,"数字"],"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
\nNumber
变量用来记录绘制上一帧所需的毫秒数。
deltaTime
包含了在上一帧中执行 draw() 函数所需的时间。这对于物理模拟非常有用。
\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
\n创建屏幕阅读器可访问的画布描述。
\n\n第一个参数,text
,是对画布的描述。
第二个参数,display
是可选项,它决定了画布描述的展示方式。如果它的值是 LABEL
,例如:describe('A description.', LABEL)
,描述将会展示在画布旁边的 div 元素中。如果是 FALLBACK
,例如:describe('A description.', FALLBACK)
,描述仅对屏幕阅读器可见,这是默认模式。
了解更多关于制作无障碍绘图的信息,请参阅 编写无障碍的画布描述。\n
"],"line":[0,18],"params":[1,[[0,{"name":[0,"text"],"description":[0,"\n对画布的描述
"],"type":[0,"字符串"]}],[0,{"name":[0,"display"],"description":[0,"\nLABEL 或 FALLBACK
"],"type":[0,"常量"],"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
\n在画布中创建屏幕阅读器可访问的元素描述。
\n\n\n元素是有实际意义的图形或图形组合。\n\n例如,几个重叠的圆可以构成“眼睛”这个元素。
\n\n\n第一个参数,name
,是元素的名称。
第二个参数,text
,是对元素的描述。
第三个参数,display
,是可选项。它决定了描述的展示方式。如果它的值是 LABEL
,例如:describe('A description.', LABEL)
,描述将会展示在画布旁边的 div 元素中。使用 LABEL
并没有实际用处,它只是屏幕阅读器中的重复项。仅在开发环境中使用 LABEL
。如果是 FALLBACK
,例如:describe('A description.',\"\nFALLBACK)
,描述仅对屏幕阅读器可见,这是默认模式。
了解更多关于制作无障碍绘图的信息,请参阅 编写无障碍的画布描述。\n
"],"line":[0,162],"params":[1,[[0,{"name":[0,"name"],"description":[0,"\n元素名称
"],"type":[0,"字符串"]}],[0,{"name":[0,"text"],"description":[0,"\n对元素的描述
"],"type":[0,"字符串"]}],[0,{"name":[0,"display"],"description":[0,"\nLABEL 或 FALLBACK
"],"type":[0,"常量"],"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
\n返回显示器当前像素密度。
"],"line":[0,1069],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"显示器当前像素密度。"],"type":[0,"数字"]}],"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 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
\nNumber
变量用于存储显示屏的高度。
displayHeight
对于运行全屏程序非常有用,它的值取决于当前像素密度 pixelDensity()。
注意:实际屏幕高度计算公式: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
\nNumber
变量用于保存屏幕的宽度。
displayWidth
对于运行全屏程序非常有用,它的值取决于当前像素密度 pixelDensity()。
注意:实际屏幕宽度计算公式: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
\n布尔值
为 true
,否则为 false
。
注意:只有当浏览器窗口获得焦点时才能接收输入。
"],"line":[0,174],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\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
\nNumber
变量用来记录绘图启动以来已绘制的帧数。
frameCount
的值在 setup() 函数中为 0,每次 draw()\n\n函数中的代码执行完毕后,它的值就增加 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
\n设置每秒绘制的帧数。
\n\n\n调用 frameRate()
时,传入一个数字参数,例如:\nframeRate(30)
,\n\n表示每秒绘制 30 帧(FPS)。目标帧率是否能达到,由绘图处理需求决定。大多数计算机默认帧率是 60 FPS。24 FPS及以上的帧率就足够实现流畅的动画。
调用 frameRate()
返回当前帧率的近似值。
每秒绘制的帧数
"],"type":[0,"数字"]}]]]}],[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
\n切换全屏模式或返回当前模式。
\n\n\n调用 fullscreen(true)
将绘图切换为全屏模式,调用 fullscreen(false)
将绘图恢复原始大小。
调用 fullscreen()
不传参数时,如果绘图是全屏模式,返回 true
,否则返回 false
。
注意:由于浏览器的限制, fullscreen()
只能在有用户输入时调用,比如点击鼠标的时候。
绘图是否处于全屏模式
"],"type":[0,"布尔"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"当前全屏状态"],"type":[0,"布尔"]}],"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返回目标帧率。
\n\n该值要么是系统帧率,要么是上次传递给 frameRate() 的值。
"],"line":[0,447],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"_targetFrameRate"],"type":[0,"数字"]}],"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
\n返回当前绘图的\n\n\nURL,\n\n\n数据类型是 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
\n返回当前\n\n\nURL 参数,\n\n\n数据类型是 Object
。
例如:在托管在URL上的绘图中调用getURLParams()
,\n\nURL 为:https://p5js.org?year=2014&month=May&day=15
,返回\n\n\n{ 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
\n返回当前\n\n\nURL\n\n的路径,数据类型是包含若干 String
的 Array
。
例如,一个托管在以下网址的绘图:\n\n\nhttps://example.com/sketchbook
,调用 getURLPath()
\n返回\n\n\"['sketchbook']
。\"\n\n如果是托管在以下网址的绘图:\n\n\nhttps://example.com/sketchbook/monday
, 调用 getURLPath()
\n返回\n\n\n\"['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
\n创建一个屏幕阅读器可访问的画布图形描述。
\n\ngridOutput()
在网页中添加概括性描述、图形列表以及图形表格。概括性描述包含画布尺寸、画布颜色和图形数量。例如:gray canvas, 100 by 100 pixels, contains 2 shapes: 1 circle 1\nsquare
。
gridOutput()
将图形表格用作网格。网格中的每个图形都放在一个单元格中,该单元格的行和列就是图形在画布上的位置。网格单元格描述了该位置的颜色和图形类型。例如:red circle
,选中这些描述可以获取更多详细信息。这不同于 textOutput(),它是将图形表用作列表。
然后是图形列表,它描述了图形的颜色、类型、位置和面积。例如:red circle, location = middle, area = 3 %
。
display
参数是可选项,它决定了描述的展示方式。如果它的值是 LABEL
,例如:gridOutput(LABEL)
描述将会展示在画布旁边的 div 元素中。 LABEL
并没有实际用处,它只是屏幕阅读器中的重复项。仅在开发环境中使用 LABEL
。如果是 FALLBACK
,例如:gridOutput(FALLBACK)
,描述仅对屏幕阅读器可见,这是默认模式。
了解更多关于制作无障碍绘图的信息,请参阅 编写无障碍的画布描述。
"],"line":[0,144],"params":[1,[[0,{"name":[0,"display"],"description":[0,"\nFALLBACK 或 LABEL
"],"type":[0,"常量"],"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
\nNumber
变量存储画布高度,单位是像素。
height
的默认值是 100,调用 createCanvas() 或 resizeCanvas() 会改变 height
的值。 调用 noCanvas() 将其值设为 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隐藏光标。
"],"line":[0,482],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\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
\n设置像素密度或返回当前像素密度。
\n\n\n计算机显示器是由 像素 组成的网格。\n\n\n显示器的 像素密度 描述了它在一个区域内包含多少个像素。\n\n像素更小的显示器具有更高的像素密度,因此创建的图像更清晰。
\n\n\npixelDensity()
为高像素密度显示器设置像素缩放。\n\n\n默认情况下,像素密度设置为与显示器密度相匹配的值。\n\n\n调用 pixelDensity(1)
关闭此功能。
调用 pixelDensity()
且不传参数,会返回当前像素密度。
想要的像素密度
"],"type":[0,"数字"],"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在网络浏览器的控制台中显示文本。
\n\n\n在调试过程中,print()
可以帮助我们打印值。每次调用 print()
都会创建一行新的文本。
注意: \"调用 print('\\n')
可打印空行。不带参数的情况下,调用 print()
会打开浏览器的打印文档对话框。
显示在控制台的内容
"],"type":[0,"任何类型"]}]]],"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
\n在画布上创建屏幕阅读器可访问的图形描述。
\n\n\ntextOutput()
在网页中添加概括性描述、图形列表以及图形表格。 概括性描述包含画布尺寸、画布颜色和图形数量。例如:\n\n\nYour output is a, 100 by 100 pixels, gray canvas containing the\nfollowing 2 shapes:
。
然后添加图形列表,它描述了图形的颜色、位置和面积。例如:\n\n\na red circle at middle covering 3% of the canvas
。选中图形可获取更多详细信息。
textOutput()
将图形表格用作列表,表格描述了形状、颜色、位置、坐标和面积。例如:\n\nred circle location = middle area = 3%
。这不同于\n\ngridOutput(), 它是将图形表格用作网格。
display
这个参数是可选项,它决定了描述的展示方式。\n\n如果它的值是 LABEL
,例如:\ntextOutput(LABEL)
, 描述将会展示在画布旁边的 div 元素中。\n\nLABEL
并没有实际用处,它只是屏幕阅读器中的重复项。\n仅在开发环境中使用 LABEL
。\n\n如果是 FALLBACK
, 例如:\ntextOutput(FALLBACK)
, 描述仅对屏幕阅读器可见,这是默认模式。
了解更多关于制作无障碍绘图的信息,请参阅 编写无障碍的画布描述。
"],"line":[0,10],"params":[1,[[0,{"name":[0,"display"],"description":[0,"\nFALLBAC 或 LABEL
"],"type":[0,"常量"],"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
\n 带有 WebGL 版本的 String
变量
webglVersion
的值是以下字符串常量之一:\n\n
WEBGL2
,其值是 'webgl2'
,WEBGL
,其值是 'webgl'
,或者P2D
,其值是 'p2d'
。这是 2D 绘图的默认值。了解设置 WebGL 版本的方法,请参阅 setAttributes()。
"],"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
\nNumber
变量存储画布宽度,单位是像素。
width
的默认值是 0,调用 createCanvas() 或\nresizeCanvas() 会改变 width
的值。 调用 noCanvas() 将其值设为 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
\nNumber
变量存储浏览器视口高度。
布局视口\n\n\n是指浏览器中可供绘制的区域。
"],"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
\n浏览器窗口大小发生变化时,调用该函数。
\n\n\n浏览器窗口大小发生变化时,写在 windowResized()
中的代码将会运行。 比较好的做法是将 resizeCanvas() 放在其代码块中,或者进行其他调整以适应新窗口大小。
event
参数是可选项,如果将它添加到函数声明中,可用于调试或其他目的。
可选的调整尺寸的 Event
"],"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
\nNumber
变量存储浏览器视口宽度。
布局视口\n\n是指浏览器中可供绘制的区域。
"],"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
\nA class to describe a camera for viewing a 3D sketch.
\nEach p5.Camera
object represents a camera that views a section of 3D\nspace. It stores information about the camera’s position, orientation, and\nprojection.
In WebGL mode, the default camera is a p5.Camera
object that can be\ncontrolled with the camera(),\nperspective(),\northo(), and\nfrustum() functions. Additional cameras can be\ncreated with createCamera() and activated\nwith setCamera().
Note: p5.Camera
’s methods operate in two coordinate systems:
myCamera.setPosition()
places the camera in 3D space using\n\"world\" coordinates.myCamera.move()
moves the camera along its own axes.Get 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
\n添加网格和轴标志以帮助明确 3D 绘图中的方向。
\ndebugMode()
函数添加一个网格, 显示绘图中“地面”的位置。默认情况下,网格将通过绘图的原点 (0, 0, 0)
沿着 XZ 平面运行。 debugMode()
还添加了一个沿着正 x、y 和 z 轴指向的坐标轴图标。调用 debugMode()
会显示网格和坐标轴图标, 以及它们的默认大小和位置。
>有四种调用 debugMode()
的方式,可选参数用于自定义调试环境。
第一种调用 debugMode()
的方式有一个参数,mode
。 如果传递了系统常量 GRID
, 例如debugMode(GRID)
, 那么将显示网格并隐藏坐标轴图标。 如果传递了常量AXES
,例如 debugMode(AXES)
, 则会显示坐标轴图标并隐藏网格。
第二种调用 debugMode()
的方式有六个参数。第一个参数 mode
, 选择要显示的 GRID
或 AXES
。 接下来的五个参数, gridSize
, gridDivisions
, xOff
, yOff
, 和 zOff
是可选的。 它们是用于设置网格外观 (gridSize
和 gridDivisions
) 以及放置坐标轴图标 (xOff
, yOff
, 和 zOff
) 的数字。 例如,调用debugMode(20, 5, 10, 10, 10)
将 gridSize
设置为 20 个像素, 并将 gridDivisions
设置为 5, 并且沿着 x、y 和 z 轴偏移坐标轴图标 1 0像素。
第三种调用 debugMode()
的方式有五个参数。 第一个参数 mode
选择要显示的 GRID
或 AXES
。接下来的四个参数, axesSize
, xOff
, yOff
, 和 zOff
是可选的。它们是用于设置坐标轴图标大小 ( axesSize
) 以及其放置位置 ( xOff
、 yOff
和 zOff
)的数字。
第四种调用 debugMode()
的方式有九个可选参数。前五个参数 gridSize
、 gridDivisions
、 gridXOff
、 gridYOff
和 gridZOff
是用于设置网格外观的数字。例如,调用 debugMode(100, 5, 0, 0, 0)
将 gridSize
设置为 100,将 gridDivisions
设置为 5,并将所有偏移量设置为 0,以便网格居中于原点。接下来的四个参数 axesSize
、 xOff
、 yOff
和 zOff
是用于设置坐标轴图标大小的数字( axesSize
)以及其放置位置( axesXOff
、 axesYOff
和 axesZOff
)。例如,调用 debugMode(100, 5, 0, 0, 0, 50, 10, 10, 10)
将 gridSize
设置为 100,将 gridDivisions
设置为 5,并将所有偏移量设置为 0,以便网格居中于原点。然后将 axesSize
设置为 50,并将图标沿每个轴偏移 10 像素。
GRID 或 AXES
\n"],"type":[0,"常数"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"mode"],"description":[0,""],"type":[0,"常数"]}],[0,{"name":[0,"gridSize"],"description":[0,"网格的边长。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"gridDivisions"],"description":[0,"网格的分割数。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"xOff"],"description":[0,"沿 x 轴的偏移量。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"yOff"],"description":[0,"沿 y 轴的偏移量。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"zOff"],"description":[0,"沿 z 轴的偏移量。
\n"],"type":[0,"数字"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"mode"],"description":[0,""],"type":[0,"常数"]}],[0,{"name":[0,"axesSize"],"description":[0,"坐标轴图标标记的长度。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"xOff"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"yOff"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"zOff"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gridSize"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"gridDivisions"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"gridXOff"],"description":[0,"沿x轴偏移的网格。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"gridYOff"],"description":[0,"沿y轴偏移的网格。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"gridZOff"],"description":[0,"沿z轴偏移的网格。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"axesSize"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"axesXOff"],"description":[0,"沿x轴偏移的坐标轴图标。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"axesYOff"],"description":[0,"沿y轴偏移的坐标轴图标。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"axesZOff"],"description":[0,"沿z轴偏移的坐标轴图标。
\n"],"type":[0,"数字"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// 点击并拖动鼠标以从不同角度查看场景。\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // 启用调试模式。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 设定盒子样式。\n normalMaterial();\n\n // 绘制盒子。\n box(20, 40);\n}\n
\n\n// 点击并拖动鼠标以从不同角度查看场景。\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // 启用调试模式。\n // 只显示坐标轴图标。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 设定盒子样式。\n normalMaterial();\n\n // 绘制盒子。\n box(20, 40);\n}\n
\n\n// 点击并拖动鼠标以从不同角度查看场景。\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // 启用调试模式。\n // 只显示网格并进行自定义设置:\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 设定盒子样式。\n normalMaterial();\n\n // 绘制盒子。\n box(20, 40);\n}\n
\n\n// 点击并拖动鼠标以从不同角度查看场景。\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // 启用调试模式。\n // 显示网格和坐标轴图标,并进行自定义设置:\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 设定盒子样式。\n normalMaterial();\n\n // 绘制盒子。\n box(20, 40);\n}\n
\n在 3D 绘图中关闭 debugMode()。
\n"],"line":[0,725],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// 单击并拖动鼠标以从不同角度查看场景。\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // 启用调试模式。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 设定盒子样式。\n normalMaterial();\n\n // 绘制盒子。 box(20, 40);\n}\n\n// 当用户双击时禁用调试模式。\nfunction doubleClicked() {\n noDebugMode();\n}\n
\n允许用户使用鼠标、触控板或触摸屏围绕 3D 绘图进行旋转。
\n通过一个虚拟的摄像机可以查看 3D 绘图。在 draw() 函数中调用 orbitControl()
允许用户改变摄像机的位置:
\nfunction draw() {\n background(200);\n\n // 使用鼠标进行轨道控制。\n orbitControl();
\n // 绘图的其余部分。\n}\n
\n左键点击并拖动或滑动将使摄像机围绕绘图中心旋转。右键点击并拖动或多点滑动可以在不旋转摄像机的情况下平移其位置。使用鼠标滚轮(滚动)或进行捏合动作可以使摄像机远离或靠近绘图中心。
\n前三个参数,sensitivityX
、sensitivityY
和 sensitivityZ
都是可选的。它们是设置绘图对每个轴向移动的灵敏度的数字。例如,调用orbitControl(1, 2, -1)
会保持 x 轴的移动在默认值,并使得绘图对 y 轴的移动灵敏度加倍,以及使 z 轴反向移动。在默认情况下,所有灵敏度的值均为 1。
第四个参数, options
,也是可选的。这是一个改变旋转行为的对象。例如,调用 orbitControl(1, 1, 1, options)
可以在保持默认灵敏度值的同时,改变由 options
设置的行为。该对象可以具有以下属性:
\nlet options = {\n // 将此设置为 false 可以防止在旋转时意外与页面交互,\n // 从而让移动交互更加顺畅。\n // 默认情况下,此值为 true。\n disableTouchActions: true,\n\n // 将此设置为 true 会使摄像机总是按照\n // 鼠标/触摸的移动方向旋转。\n // 默认情况下,此值为 false。\n freeRotation: false\n};
\norbitControl(1, 1, 1, options);\n
\n"],"line":[0,11],"params":[1,[[0,{"name":[0,"sensitivityX"],"description":[0,"沿 x 轴移动的灵敏度,默认为1。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"sensitivityY"],"description":[0,"沿 y 轴移动的灵敏度,默认为1。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"sensitivityZ"],"description":[0,"沿 z 轴移动的灵敏度,默认为1。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"options"],"description":[0,"具有两个可选属性的对象, disableTouchActions
和 freeRotation
。 两者都是 Boolean
。 disableTouchActions
默认为 true
, freeRotation
默认为 false
。
\n// 点击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 设定盒子样式。\n normalMaterial();\n\n // 绘制盒子。\n box(30, 50);\n}\n
\n\n// 点击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n // 使交互的灵敏度提高3倍。\n orbitControl(3, 3, 3);\n\n // 设定盒子样式。\n normalMaterial();\n\n // 绘制盒子。\n box(30, 50);\n}\n
\n\n// 点击并拖动鼠标来查看场景的不同角度。\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 // 创建一个 options 对象。\n let options = {\n disableTouchActions: false,\n freeRotation: true\n };\n\n // 使用鼠标进行轨道控制。\n // 防止触摸屏设备上的意外触控操作\n // 并启用自由旋转。\n orbitControl(1, 1, 1, options);\n\n // 设定盒子样式。\n normalMaterial();\n\n // 绘制盒子。\n box(30, 50);\n}\n
\n创建一个向所有方向发光的光源。
\n环境光不是来自一个方向。相反,3D 形状从所有方向均匀地受到照亮。环境光几乎总是与其他类型的光一起使用。
\n有三种调用 ambientLight()
的方式,可以通过可选参数设置光的颜色。
第一种调用 ambientLight()
的方式有两个参数,gray
和 alpha
。 alpha
是可选的。可以传递介于 0 和 255 之间的灰度和 alpha 值来设置环境光的颜色, 例如 ambientLight(50)
或 ambientLight(50, 30)
。
第二种调用 ambientLight()
的方式有一个参数,就是颜色。可以传递一个 p5.Color 对象、一个颜色值数组或一个 CSS 颜色字符串,例如 ambientLight('magenta')
,来设置环境光的颜色。
第三种调用 ambientLight()
的方式有四个参数,v1
、 v2
、 v3
和 alpha
。 alpha
是可选的。可以传递 RGBA、 HSBA 或 HSLA 值来设置环境光的颜色,例如 ambientLight(255, 0, 0)
或 ambientLight(255, 0, 0, 30)
。颜色值将根据当前的 colorMode() 进行诠释。
当前 colorMode() 中的红色或色相值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"v2"],"description":[0,"当前 colorMode() 中的绿色或饱和度值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"v3"],"description":[0,"当前 colorMode() 中的蓝色、亮度或明度值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"alpha"],"description":[0,"当前 colorMode() 中的 alpha(透明度)值。
\n"],"type":[0,"数字"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gray"],"description":[0,"介于 0 和 255 之间的灰度值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"alpha"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"作为 CSS 字符串的颜色。
\n"],"type":[0,"字符串"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"values"],"description":[0,"作为 RGBA、HSBA 或 HSLA 值数组的颜色。
\n"],"type":[0,"数字[]"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"作为 p5.Color 对象的颜色。
\n"],"type":[0,"p5.Color"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// 单击并拖动鼠标以从不同角度查看场景。\n// 双击画布以打开灯光。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 控制灯光。\n if (isLit === true) {\n // 使用的灰度值为 80。\n ambientLight(80);\n }\n\n // 绘制球体。\n sphere(30);\n}\n\n// 当用户双击时打开环境光。\nfunction doubleClicked() {\n isLit = true;\n}\n
\n\n// 单击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 打开灯光。\n // 使用一个 p5.Color 对象。\n let c = color('orchid');\n ambientLight(c);\n\n // 绘制球体。\n sphere();\n}\n
\n\n// 单击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 打开灯光。\n // 使用一个 CSS 颜色字符串。\n ambientLight('#DA70D6');\n\n // 绘制球体。\n sphere(30);\n}\n
\n\n// 单击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 打开灯光。\n // 使用 RGB 值\n ambientLight(218, 112, 214);\n\n // 绘制球体。\n sphere(30);\n}\n
\n创建一个朝单一方向照射的光。
\n方向光不是从特定点发出的。它们就像一轮太阳,从屏幕外的某个地方照射进来。光的方向由三个介于 -1 和 1 之间的 (x, y, z)
值设置。例如,将光的方向设置为
(1, 0, 0)
将从左侧照亮
有四种调用 directionalLight()
的方法,用于设置光源的颜色和方向。
调用 directionalLight()
的第一种方式有六个参数。前三个参数 v1
、 v2
和 v3
使用当前的 colorMode() 来设置光的颜色。最后三个参数 x
、 y
和 z
设置光的方向。例如, directionalLight(255, 0, 0, 1, 0, 0)
创建一个红色 (255, 0, 0)
的光,朝向右边 (1, 0, 0)
。
调用 directionalLight()
的第二种方式有四个参数。前三个参数 v1
、 v2
和 v3
使用当前的 colorMode() 来设置光的颜色。最后一个参数 direction
使用一个 p5.Geometry 对象来设置光的方向。例如, directionalLight(255, 0, 0, lightDir)
创建一个红色 (255, 0, 0)
的光,其方向是 lightDir
向量所指的方向。
调用 directionalLight()
的第三种方式有四个参数。第一个参数 color
使用一个 x
、 y
和 z
设置光的方向。例如, directionalLight(myColor, 1, 0, 0)
创建一个颜色为 myColor
的光,朝向右边 (1, 0, 0)
。
调用 directionalLight()
的第四种方式有两个参数。第一个参数 color
使用一个 direction
使用一个 directionalLight(myColor, lightDir)
创建一个颜色为 myColor
的光,其方向是 lightDir
向量所指的方向。
当前 colorMode() 中的红色或色相值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"v2"],"description":[0,"当前 colorMode() 中的绿色或饱和度值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"v3"],"description":[0,"当前 colorMode() 中的蓝色、亮度或明度值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"x"],"description":[0,"光的方向的 x 分量,范围在 -1 到 1 之间。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"y"],"description":[0,"光的方向的 y 分量,范围在 -1 到 1 之间。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"z"],"description":[0,"光的方向的 z 分量,范围在 -1 到 1 之间。
\n"],"type":[0,"数字"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"v2"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"v3"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"direction"],"description":[0,"光的方向作为一个
颜色作为一个 p5.Color 的对象,一个颜色值数组,或者一个 CSS 字符串。
\n"],"type":[0,"p5.Color|数字[]|字符串"]}],[0,{"name":[0,"x"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"z"],"description":[0,""],"type":[0,"数字"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,""],"type":[0,"p5.Color|数字[]|字符串"]}],[0,{"name":[0,"direction"],"description":[0,""],"type":[0,"p5.Vector"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// 点击并拖动鼠标以从不同角度查看场景。\n// 双击以打开定向光。\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 // 启用鼠标轨道控制。\n orbitControl();\n\n // 控制光线。\n if (isLit === true) {\n // 从上方添加红色定向光。\n // 使用 RGB 值和 XYZ 方向。\n directionalLight(255, 0, 0, 0, 1, 0);\n }\n\n // 设定球体样式。\n noStroke();\n\n // 绘制球体。\n sphere(30);\n}\n
\n\n// 点击并拖动鼠标以从不同角度查看场景。\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 // 启用鼠标轨道控制。\n orbitControl();\n\n // 从上方添加红色定向光。\n // 使用一个 p5.Color 对象和 XYZ 方向。\n let c = color(255, 0, 0);\n directionalLight(c, 0, 1, 0);\n\n // 设定球体样式。\n noStroke();\n\n // 绘制球体。\n sphere(30);\n}\n
\n\n// 点击并拖动鼠标以从不同角度查看场景。\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 // 启用鼠标轨道控制。\n orbitControl();\n\n // 从上方添加红色定向光。\n // 使用一个 p5.Color 对象和一个 p5.Vector 对象。\n let c = color(255, 0, 0);\n let lightDir = createVector(0, 1, 0);\n directionalLight(c, lightDir);\n\n // 设定球体样式。\n noStroke();\n\n // 绘制球体。\n sphere(30);\n}\n
\n从图像创建一个环境光。
\nimageLight()
模拟了从所有方向照射的光。效果就像将绘图放置在一个以图像为纹理的巨大球体的中心。图像的漫反射光会受到 fill() 的影响,而镜面反射则受到 specularMaterial() 和 shininess() 的影响。
参数 img
是要用作光源的 p5.Image 的对象。
使用作为光源的图像。
\n"],"type":[0,"p5.image"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// 点击并拖动鼠标以从不同角度查看场景。\n\nlet img;\n\n// 加载图像并创建一个 p5.Image 对象。\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 // 启用鼠标轨道控制。\n orbitControl();\n\n // 将图像绘制为全景图像(360˚ 背景)。\n panorama(img);\n\n // 添加一个柔和的环境光。\n ambientLight(50);\n\n // 添加来自图像的光源。\n imageLight(img);\n\n // 设定球体样式。\n specularMaterial(20);\n shininess(100);\n noStroke();\n\n // 绘制球体。\n sphere(30);\n}\n
\n设置 pointLight() 和 spotLight() 的衰减率。
\n光的衰减描述了其在距离上的光束强度。例如,一个灯笼具有缓慢的衰减,手电筒具有中等的衰减,激光笔具有迅速的衰减。
\nlightFalloff()
有三个参数, constant
, linear
和 quadratic
。它们是用于计算距离 d
的衰减的数字,如下所示:
falloff = 1 / (constant + d * linear + (d * d) * quadratic)
注意: constant
, linear
和 quadratic
应始终设置为大于 0 的值。
用于计算衰减的常数值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"linear"],"description":[0,"用于计算衰减的线性值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"quadratic"],"description":[0,"用于计算衰减的二次值。
\n"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// 单击并拖动鼠标以从不同角度查看场景。\n// 双击以更改衰减率。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 设置光的衰减。\n if (useFalloff === true) {\n lightFalloff(2, 0, 0);\n }\n\n // 从正面添加一个白色点光源。\n pointLight(255, 255, 255, 0, 0, 100);\n\n // 设置球体样式。\n noStroke();\n\n // 绘制球体。\n sphere(30);\n}\n\n// 当用户双击时更改衰减值。\nfunction doubleClicked() {\n useFalloff = true;\n}\n
\n在场景中放置环境光和定向光。光源被设置为 ambientLight(128, 128, 128) 和 directionalLight(128, 128, 128, 0, 0, -1)。
\n注意:光源需要在 draw() 函数内被调用(直接或间接调用)以保持在循环程序中持续存在。将它们放置在 setup() 函数内将导致它们只在循环的第一次运行时产生效果。
\n"],"line":[0,1076],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// 单击并拖动鼠标以从不同角度查看场景。\n// 双击以打开灯光。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 控制灯光。\n if (isLit === true) {\n lights();\n }\n\n // 绘制盒子。\n box();\n}\n\n// 当用户双击时打开灯光。\nfunction doubleClicked() {\n isLit = true;\n}\n
\n\n// 单击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 打开灯光。\n ambientLight(128, 128, 128);\n directionalLight(128, 128, 128, 0, 0, -1);\n\n // 绘制盒子。\n box();\n}\n
\n从绘图中移除所有光源。
\n调用 noLights()
会移除通过 lights(), ambientLight(), directionalLight(), pointLight(), 或 spotLight() 创建的任何光源。在调用nolights()
后,可以调用这些函数来创建新的光照方案。
\n// 单击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 打开灯光。\n lights();\n\n // 设定球体样式。\n noStroke();\n\n // 绘制顶部球体。\n push();\n translate(0, -25, 0);\n sphere(20);\n pop();\n\n // 关闭灯光。\n noLights();\n\n // 添加一个指向屏幕内部的红色定向光。\n directionalLight(255, 0, 0, 0, 0, -1);\n\n // 绘制底部球体。\n push();\n translate(0, 25, 0);\n sphere(20);\n pop();\n}\n
\n创建一个沉浸式的 3D 背景。
\npanorama()
将包含 360˚ 内容的图像,例如地图或 HDRIs,转换为沉浸式的 3D 背景,围绕在绘图周围。探索空间需要通过诸如orbitControl() 或 camera() 等函数来改变相机的视角。
用作背景的360˚图像。
\n"],"type":[0,"p5.Image"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// 单击并拖动鼠标以从不同角度查看场景。\n\nlet img;\n\n// 加载图像并创建一个 p5.Image 对象。\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 // 添加全景图。\n panorama(img);\n\n // 启用鼠标轨道控制。\n orbitControl();\n\n // 使用图像作为光源。\n imageLight(img);\n\n // 为球体添加样式。\n noStroke();\n specularMaterial(50);\n shininess(200);\n metalness(100);\n\n // 绘制球体。\n sphere(30);\n}\n
\n创建一个从一个点朝所有方向发光的光源。
\n点光源就像发光的灯泡,它们向所有方向发光。 它们可以放置在不同的位置以实现不同的光照效果。最多可以同时激活 5 个点光源。
\n有四种方法可以调用 pointLight()
来设置光的颜色和位置。
调用 pointLight()
的第一种方式有六个参数。前三个参数 v1
、 v2
和 v3
使用当前的 colorMode() 来设置光的颜色。最后三个参数 x
、 y
和z
设置光的位置。例如, pointLight(255, 0, 0, 50, 0, 0)
创建一个红色 (255, 0, 0)
的光,从坐标 (50, 0, 0)
发光。
调用 pointLight()
的第二种方式有四个参数。前三个参数 v1
、 v2
和 v3
使用当前的 colorMode() 来设置光的颜色。最后一个参数 position 使用一个 p5.Vector 对象来设置光的位置。例如, pointLight(255, 0, 0, lightPos)
创建一个红色 (255, 0, 0)
的光,从由 lightPos
向量设置的位置发出。
调用 pointLight()
的第三种方式有四个参数。第一个参数 color
使用一个 p5.Color 对象或颜色值数组来设置光的颜色。最后三个参数 x
、 y
和 z
设置光的位置。例如, pointLight(myColor, 50, 0, 0)
创建一个颜色为 myColor
的光,从坐标 (50, 0, 0)
发光。
调用 pointLight()
的第四种方式有两个参数。第一个参数 color
使用一个 p5.Color 对象或颜色值数组来设置光的颜色。第二个参数 position
使用一个 p5.Vector 对象来设置光的位置。例如, pointLight(myColor, lightPos)
创建一个从由 lightPos
向量设置的位置发光,其颜色为 myColor
。
当前 colorMode() 中的红色或色相值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"v2"],"description":[0,"当前 colorMode() 中的绿色或饱和度值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"v3"],"description":[0,"当前 colorMode() 中的蓝色、亮度或明度值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"x"],"description":[0,"光的 x 坐标。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"y"],"description":[0,"光的 y 坐标。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"z"],"description":[0,"光的 z 坐标。
\n"],"type":[0,"数字"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"v2"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"v3"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"position"],"description":[0,"光的位置作为一个 p5.Vector 对象。
\n"],"type":[0,"p5.Vector"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"颜色作为一个 p5.Color 对象,一个颜色值数组,或者一个 CSS 字符串。
\n"],"type":[0,"p5.Color|数字[]|字符串"]}],[0,{"name":[0,"x"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"z"],"description":[0,""],"type":[0,"数字"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,""],"type":[0,"p5.Color|数字[]|字符串"]}],[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// 点击并拖动鼠标以从不同角度查看场景。\n// 双击以打开点光源。\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 // 启用鼠标轨道控制。\n orbitControl();\n\n // 控制光线。\n if (isLit === true) {\n // 添加一个上方的红色点光源。\n // 使用 RGB 值和 XYZ 坐标。\n pointLight(255, 0, 0, 0, -150, 0);\n }\n\n // 设定球体样式。\n noStroke();\n\n // 绘制球体。\n sphere(30);\n}\n\n// 当用户双击时打开点光源。\nfunction doubleClicked() {\n isLit = true;\n}\n
\n\n// 点击并拖动鼠标以从不同角度查看场景。\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 // 启用鼠标轨道控制。\n orbitControl();\n\n // 从上方添加红色点光源。\n // 使用 p5.Color 对象和 XYZ 方向。\n let c = color(255, 0, 0);\n pointLight(c, 0, -150, 0);\n\n // 设定球体样式。\n noStroke();\n\n // 绘制球体。\n sphere(30);\n}\n
\n\n// 点击并拖动鼠标以从不同角度查看场景。\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 // 启用鼠标轨道控制。\n orbitControl();\n\n // 从上方添加红色点光源。\n // 使用 p5.Color 对象和一个 p5.Vector 对象。\n let c = color(255, 0, 0);\n let lightPos = createVector(0, -150, 0);\n pointLight(c, lightPos);\n\n // 设定球体样式。\n noStroke();\n\n // 绘制球体。\n sphere(30);\n}\n
\n\n// 点击并拖动鼠标以从不同角度查看场景。\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 // 启用鼠标轨道控制。\n orbitControl();\n\n // 添加一个指向场景中心的红色点光源。\n // 使用 p5.Color 对象和一个 p5.Vector 对象。\n let c = color(255, 0, 0);\n let lightPos = createVector(0, 0, 65);\n pointLight(c, lightPos);\n\n // 设定球体样式。\n noStroke();\n\n // 向上和向左绘制一个球体。\n push();\n translate(-25, -25, 25);\n sphere(10);\n pop();\n\n // 向上和向右绘制一个盒子。\n push();\n translate(25, -25, 25);\n sphere(10);\n pop();\n\n // 向下和向左绘制一个球体。\n push();\n translate(-25, 25, 25);\n sphere(10);\n pop();\n\n // 向下和向右绘制一个盒子。\n push();\n translate(25, 25, 25);\n sphere(10);\n pop();\n}\n
\n设置灯光的高光颜色。
\nspecularColor()
影响那些在表面上以首选方向反射的光线。这些光线包括 directionalLight(), pointLight(), 和 spotLight()。 该函数有助于在使用 specularMaterial() 样式化的 p5.Geometry 对象上创建高光。如果几何体不使用 specularMaterial(),那么 specularColor()
将不起作用。
注意: specularColor()
不影响所有方向反射的光线,包括 ambientLight() 和 imageLight()。
有三种调用 specularColor()
的方式,可以通过可选参数设置高光颜色。
第一种调用 specularColor()
有两个可选参数, gray
和 alpha
。 介于 0 和 255 之间的灰度和 alpha 值, 例如 specularColor(50)
或 specularColor(50, 80)
, 可以传递来设置高光颜色。
第二种调用 specularColor()
有一个可选参数,color
。可以传递一个 p5.Color 对象,一个颜色值数组,或一个 CSS 颜色字符串来设置高光颜色。
调用 specularColor()
的第三种方式具有四个可选参数, v1
, v2
, v3
, 和 alpha
。 RGBA、 HSBA、 或 HSLA 值,例如 specularColor(255, 0, 0, 80)
, 可用于设置高光颜色。颜色值将使用当前的 colorMode() 进行解释。
当前 colorMode() 中的红色或色相值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"v2"],"description":[0,"当前 colorMode() 中的绿色或饱和度值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"v3"],"description":[0,"当前 colorMode() 中的蓝色、亮度或明度值。
\n"],"type":[0,"数字"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gray"],"description":[0,"介于 0 和 255 之间的灰度值。
\n"],"type":[0,"数字"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"value"],"description":[0,"作为 CSS 字符串的颜色。
\n"],"type":[0,"字符串"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"values"],"description":[0,"作为 RGBA、HSBA 或 HSLA 值数组的颜色。
\n"],"type":[0,"数字[]"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"作为 p5.Color 对象的颜色。
\n"],"type":[0,"p5.Color"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// 单击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 无镜面颜色。\n // 绘制球体。\n sphere(30);\n}\n
\n\n// 单击并拖动鼠标以从不同角度查看场景。\n// 双击画布以添加一个点光源。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 设定球体样式。\n noStroke();\n specularColor(100);\n specularMaterial(255, 255, 255);\n\n // 控制灯光。\n if (isLit === true) {\n // 从右上方添加一个白色点光源。\n pointLight(255, 255, 255, 30, -20, 40);\n }\n\n // 绘制球体。\n sphere(30);\n}\n\n// 当用户双击时打开点光源。\nfunction doubleClicked() {\n isLit = true;\n}\n
\n\n// 单击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 添加一个镜面高光。\n // 使用一个 p5.Color 对象。\n let c = color('dodgerblue');\n specularColor(c);\n\n // 从右上方添加一个白色点光源。\n pointLight(255, 255, 255, 30, -20, 40);\n\n // 设定球体样式。\n noStroke();\n\n // 添加一个白色的镜面材质。\n specularMaterial(255, 255, 255);\n\n // 绘制球体。\n sphere(30);\n}\n
\n\n// 单击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 添加一个镜面高光。\n // 使用 CSS 颜色字符串。\n specularColor('#1E90FF');\n\n // 从右上方添加一个白色点光源。\n pointLight(255, 255, 255, 30, -20, 40);\n\n // 为球体设置样式。\n noStroke();\n\n // 添加一个白色的镜面材质。\n specularMaterial(255, 255, 255);\n\n // 绘制球体。\n sphere(30);\n}\n
\n\n// 单击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 添加一个镜面高光。\n // 使用 RGB 值。\n specularColor(30, 144, 255);\n\n // 从右上方添加一个白色点光源。\n pointLight(255, 255, 255, 30, -20, 40);\n\n // 为球体设置样式。\n noStroke();\n\n // 添加一个白色的高光材质。\n specularMaterial(255, 255, 255);\n\n // 绘制球体。\n sphere(30);\n}\n
\n创建一个从一个点朝单一方向发出光线的灯光。
\n聚光灯类似于手电筒,只朝一个方向发出光线,形成一个锥形光束。可以使用角度和集中度参数来控制锥形的形状。最多可以同时激活 5 个聚光灯。
\n有八种调用 spotLight()
的方式,它们用于设置光源的颜色、位置和方向。比如,spotLight(255, 0, 0, 0, 0, 0, 1, 0, 0)
创建了一个红色 (255, 0, 0)
的光源, 位于原点 (0, 0, 0)
,指向右侧 (1, 0, 0)
。
angle
参数是可选的。它设置光锥的半径。 例如, spotLight(255, 0, 0, 0, 0, 0, 1, 0, 0, PI / 16)
创建了一个在原点 (0, 0, 0)
的,红色的 (255, 0, 0)
光;该光以 PI / 16
的角度指向了右侧的(1, 0, 0)
。 在默认情况下, angle
是 PI / 3
的弧度。
参数 concentration
也是可选的。它将光聚焦在光锥的中心。例如,spotLight(255, 0, 0, 0, 0, 0, 1, 0, 0, PI / 16, 50)
创建了一个红色的 (255, 0, 0)
光源,位于原点 (0, 0, 0)
,指向右侧 (1, 0, 0)
,以 PI / 16
弧度的角度聚焦度为 50。默认情况下,concentration
为 100。
当前 colorMode() 中的红色或色相值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"v2"],"description":[0,"当前 colorMode() 中的绿色或饱和度值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"v3"],"description":[0,"当前 colorMode() 中的蓝色、亮度或明度值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"x"],"description":[0,"光的x坐标。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"y"],"description":[0,"光的y坐标。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"z"],"description":[0,"光的z坐标。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"rx"],"description":[0,"光方向的x分量,取值范围为-1到1。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"ry"],"description":[0,"光方向的y分量,取值范围为-1到1。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"rz"],"description":[0,"光方向的z分量,取值范围为-1到1。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"angle"],"description":[0,"光锥的角度。默认为 PI / 3
。
光的聚焦度。默认为100。
\n"],"type":[0,"数字"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"可以是 p5.Color 对象、颜色值数组或 CSS 字符串的颜色。
\n"],"type":[0,"p5.Color|数字[]|字符串"]}],[0,{"name":[0,"position"],"description":[0,"作为 p5.Vector 对象的光的位置。
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"direction"],"description":[0,"作为 p5.Vector 对象的光的方向。
\n"],"type":[0,"p5.Vector"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"v2"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"v3"],"description":[0,""],"type":[0,"数字"]}],[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,"数字"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,""],"type":[0,"p5.Color|数字[]|字符串"]}],[0,{"name":[0,"x"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"z"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"direction"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,""],"type":[0,"p5.Color|数字[]|字符串"]}],[0,{"name":[0,"position"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"rx"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"ry"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"rz"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"v2"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"v3"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"x"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"z"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"direction"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"v2"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"v3"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"position"],"description":[0,""],"type":[0,"p5.Vector"]}],[0,{"name":[0,"rx"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"ry"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"rz"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,""],"type":[0,"p5.Color|数字[]|字符串"]}],[0,{"name":[0,"x"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"y"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"z"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"rx"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"ry"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"rz"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"angle"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"concentration"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// 单击并拖动鼠标以从不同角度查看场景。\n// 双击以调整聚光灯。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 打开灯光。\n lights();\n\n // 控制聚光灯。\n if (isLit === true) {\n // 添加一个红色聚光灯,照射到屏幕中。\n // 将其角度设置为 PI / 32 弧度。\n spotLight(255, 0, 0, 0, 0, 100, 0, 0, -1, PI / 32);\n }\n\n // 绘制球体。\n sphere(30);\n}\n\n// 当用户双击时打开聚光灯。\nfunction doubleClicked() {\n isLit = true;\n}\n
\n\n// 单击并拖动鼠标以从不同角度查看场景。\n// 双击以调整聚光灯。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 打开灯光。\n lights();\n\n // 控制聚光灯。\n if (isLit === true) {\n // 添加一个红色聚光灯,照射到屏幕中。\n // 将其角度设置为 PI / 3 弧度(默认)。\n // 将其聚焦度设置为 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 // 绘制球体。\n sphere(30);\n}\n\n// 当用户双击时打开聚光灯。\nfunction doubleClicked() {\n isLit = true;\n}\n
\n设置形状表面材质的环境颜色。
\nambientMaterial()
颜色设置形状将反射的 ambientLight() 颜色的组件。例如,调用 ambientMaterial(255, 255, 0)
将使形状反射红色和绿色光,但不反射蓝色光。
ambientMaterial()
可以通过不同的参数以三种方式调用来设置材质的颜色。
第一种调用 ambientMaterial()
的方式有一个参数 gray
。可以传递介于 0 和 255 之间的灰度值,如 ambientMaterial(50)
,来设置材质的颜色。较高的灰度值会使形状看起来更亮。
第二种调用 ambientMaterial()
的方式有一个参数 color
。可以传递一个 p5.Color 对象、一个颜色值数组或一个 CSS 颜色字符串,如 ambientMaterial('magenta')
,来设置材质的颜色。
第三种调用 ambientMaterial()
的方式有三个参数 v1
、v2
和 v3
。可以传递 RGB、HSB 或 HSL 值,如 ambientMaterial(255, 0, 0)
,来设置材质的颜色。颜色值将根据当前的 colorMode() 进行解释。
注意:ambientMaterial()
只能在 WebGL 模式下使用。
当前 colorMode() 中的红色或色调值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"v2"],"description":[0,"当前 colorMode() 中的绿色或饱和度值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"v3"],"description":[0,"当前 colorMode() 中的蓝色、亮度或明度值。
\n"],"type":[0,"数字"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gray"],"description":[0,"介于 0 (黑色)和 255 (白色)之间的灰度值。
\n"],"type":[0,"数字"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"作为 p5.Color 对象、颜色值数组或 CSS 字符串的颜色。
\n"],"type":[0,"p5.Color|数字[]|字符串"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// 单击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 打开一个品红色的环境光。\n ambientLight(255, 0, 255);\n\n // 绘制立方体。\n box();\n}\n
\n\n// 单击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 打开一个品红色的环境光。\n ambientLight(255, 0, 255);\n\n // 添加一个深灰色的环境材质。\n ambientMaterial(150);\n\n // 绘制立方体。\n box();\n}\n
\n\n// 单击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 打开一个品红色的环境光。\n ambientLight(255, 0, 255);\n\n // 使用 RGB 值添加一个黄色的环境材质。\n ambientMaterial(255, 255, 0);\n\n // 绘制立方体。\n box();\n}\n
\n\n// 单击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 打开一个品红色的环境光。\n ambientLight(255, 0, 255);\n\n // 使用 p5.Color 对象添加一个黄色的环境材质。\n let c = color(255, 255, 0);\n ambientMaterial(c);\n\n // 绘制立方体。\n box();\n}\n
\n\n// 单击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 打开一个品红色的环境光。\n ambientLight(255, 0, 255);\n\n // 使用颜色字符串添加一个黄色的环境材质。\n ambientMaterial('yellow');\n\n // 绘制立方体。\n box();\n}\n
\n\n// 单击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 打开一个白色的环境光。\n ambientLight(255, 255, 255);\n\n // 使用颜色字符串添加一个黄色的环境材质。\n ambientMaterial('yellow');\n\n // 绘制立方体。\n box();\n}\n
\n创建一个 p5.Shader 对象,与 filter()< /a> 函数。
\ncreateFilterShader()
的工作方式与 createShader() 类似,但包含默认的顶点着色器。 createFilterShader()
旨在与 filter() 一起使用来为画布的内容添加滤镜。 滤镜着色器将应用于整个画布,而不仅仅是 p5.Geometry 对象。
参数 fragSrc
设置片段着色器。 它是一个字符串,包含编写的片段着色器程序 GLSL。
创建的 p5.Shader 对象有一些可以设置的 uniform:
\nsampler2D tex0
,其中包含作为纹理的画布内容。vec2 canvasSize
,即画布的宽度和高度,不包括像素密度。vec2 texelSize
,这是物理像素的大小,包括像素密度。 像素宽度的计算方式为 1.0 / (width * Density)
,像素高度的计算方式为 1.0 / (height * density)
。创建的 p5.Shader 还提供了 varyingvec2 vTexCoord
,这是一个值介于 0 和 1 vTexCoord
之间的坐标,描绘像素在画布上绘制的位置。
有关滤镜和着色器的更多信息,请参阅 Adam Ferriss 的 repo of shader examples 或 Introduction to Shaders 教程。
\n"],"line":[0,429],"params":[1,[[0,{"name":[0,"fragSrc"],"description":[0,"片段着色器的源代码。
\n"],"type":[0,"字符串"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"从片段着色器创建的新着色器对象。"],"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 坐标。\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
\n创建一个新的 p5.Shader 对象。
\n着色器是在图形处理单元 (GPU) 上运行的程序。 它们可以同时处理许多像素,从而可以快速执行许多图形任务。 它们是用 GLSL 语言编写的,并于绘图中运行其余代码。
\n一旦创建了 p5.Shader 对象,它就可以与 一起使用 Shader() 函数,如 shader(myShader)
中。 着色器程序由两部分组成,顶点着色器和片段着色器。 顶点着色器影响 3D 几何体在屏幕上绘制的位置,而片段着色器则影响颜色。
第一个参数 vertSrc
设置顶点着色器。 它是一个字符串,包含用 GLSL 编写的顶点着色器程序。
第二个参数,fragSrc
,设置片段着色器。 它是一个字符串,包含用 GLSL 编写的片段着色器程序。
注意:2D 模式下只能使用滤镜着色器。 而所有着色器都可以在 WebGL 模式下使用。
\n"],"line":[0,173],"params":[1,[[0,{"name":[0,"vertSrc"],"description":[0,"顶点着色器的源代码。
\n"],"type":[0,"字符串"]}],[0,{"name":[0,"fragSrc"],"description":[0,"片段着色器的源代码。
\n"],"type":[0,"字符串"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"new shader object created from the\nvertex and fragment shaders."],"type":[0,"p5.Shader"]}],"example":[1,[[0,"\n\n// 注意:\"uniform\" 是着色器程序中的全局变量。\n\n// 使用顶点着色器程序创建一个字符串。\n// 每个顶点都会调用顶点着色器。\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// 使用片段着色器程序创建一个字符串。\n// 每个像素都会调用片段着色器。\nlet fragSrc = `\nprecision highp float;\n\nvoid main() {\n // 将每个像素的 RGBA 值设置为黄色。\n gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);\n}\n`;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // 创建一个 p5.Shader 对象。\n let shaderProgram = createShader(vertSrc, fragSrc);\n\n // 编译并应用 p5.Shader 对象。\n shader(shaderProgram);\n\n // 设置绘图表面的样式。\n noStroke();\n\n // 添加一个平面作为绘图表面。\n plane(100, 100);\n\n describe('A yellow square.');\n}\n
\n\n// 注意:\"uniform\" 是着色器程序中的全局变量。\n\n// 使用顶点着色器程序创建一个字符串。\n// 每个顶点都会调用顶点着色器。\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// 使用片段着色器程序创建一个字符串。\n// 每个像素都会调用片段着色器。\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 // 创建一个 p5.Shader 对象。\n let mandelbrot = createShader(vertSrc, fragSrc);\n\n // 编译并应用 p5.Shader 对象。\n shader(mandelbrot);\n\n // 将着色器的 uniform p 设置为数组。\n // p 是 Mandelbrot 图像的中心点。\n mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);\n\n // 将着色器的 uniform r 设置为 0.005。\n // r 是 Mandelbrot 空间中图像的大小。\n mandelbrot.setUniform('r', 0.005);\n\n // 设置绘图表面的样式。\n noStroke();\n\n // 添加一个平面作为绘图表面。\n plane(100, 100);\n\n describe('A black fractal image on a magenta background.');\n}\n
\n\n// 注意:\"uniform\" 是着色器程序中的全局变量。\n\n// 使用顶点着色器程序创建一个字符串。\n// 每个顶点都会调用顶点着色器。\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// 使用片段着色器程序创建一个字符串。\n// 每个像素都会调用片段着色器。\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 // 创建一个 p5.Shader 对象。\n mandelbrot = createShader(vertSrc, fragSrc);\n\n // 应用 p5.Shader 对象。\n shader(mandelbrot);\n\n // 将着色器的 uniform p 设置为数组。\n // p 是 Mandelbrot 图像的中心点。\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 // 将着色器的 uniform r 设置为振荡的值\n // 0 到 0.005 之间。\n // r 是 Mandelbrot 空间中图像的大小。\n let radius = 0.005 * (sin(frameCount * 0.01) + 1);\n mandelbrot.setUniform('r', radius);\n\n // 设置绘图表面的样式。\n noStroke();\n\n // 添加一个平面作为绘图表面。\n plane(100, 100);\n}\n
\n设置形状表面材质的自发光颜色。
\nemissiveMaterial()
颜色设置形状以全强度显示的颜色,不受光照影响。这可以使形状看起来发光。但是,自发光材质实际上并不会发出能够影响周围物体的光。
emissiveMaterial()
可以通过不同的参数以三种方式调用来设置材质的颜色。
第一种调用 emissiveMaterial()
的方式有一个参数 gray
。可以传递介于 0 和 255 之间的灰度值,如 emissiveMaterial(50)
,来设置材质的颜色。较高的灰度值会使形状看起来更亮。
第二种调用 emissiveMaterial()
的方式有一个参数 color
。可以传递一个 p5.Color 对象、一个颜色值数组或一个 CSS 颜色字符串,如 emissiveMaterial('magenta')
,来设置材质的颜色。
第三种调用 emissiveMaterial()
的方式有四个参数,v1
、v2
、v3
和 alpha
。 alpha
是可选的。RGBA、HSBA 或 HSLA值可以传递来设置材质的颜色,例如 emissiveMaterial(255, 0, 0)
或 emissiveMaterial(255, 0, 0, 30)
。颜色值将根据当前的 colorMode()进行解释。
注意:emissiveMaterial()
只能在 WebGL 模式下使用。
当前 colorMode() 中的红色或色调值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"v2"],"description":[0,"当前 colorMode() 中的绿色或饱和度值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"v3"],"description":[0,"当前 colorMode() 中的蓝色、亮度或明度值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"alpha"],"description":[0,"当前 colorMode() 中的 alpha 值。
\n"],"type":[0,"数字"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"gray"],"description":[0,"介于 0 (黑色)和 255 (白色)之间的灰度值。
\n"],"type":[0,"数字"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"作为 p5.Color 对象、颜色值数组或 CSS 字符串的颜色。
\n"],"type":[0,"p5.Color|数字[]|字符串"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// 单击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 打开白色环境光。\n ambientLight(255, 255, 255);\n\n // 添加一个使用 RGB值 的红色自发光材质。\n emissiveMaterial(255, 0, 0);\n\n // 绘制立方体。\n box();\n}\n
\n加载顶点和片段着色器以创建一个 p5.Shader 对象。
\n着色器是在图形处理单元(GPU)上运行的程序。它们可以同时处理许多像素,因此对于许多图形任务来说速度很快。它们是用一种叫做 GLSL 的语言编写的,并且与绘图中的其他代码一起运行。
\n一旦创建了 p5.Shader 对象,它就可以与 shader() 函数一起使用,例如:shader(myShader)
。着色器程序由两个文件组成,一个顶点着色器和一个片段着色器。顶点着色器影响 3D 几何体在屏幕上的绘制位置,而片段着色器影响颜色。
loadShader()
从 .vert
和 .frag
文件加载顶点和片段着色器。 例如,调用 loadShader('/assets/shader.vert', '/assets/shader.frag')
加载所需的着色器并返回 p5 .Shader 对象。
第三个参数 successCallback
是可选的。 如果传递一个函数,则着色器加载后就会调用该函数。 回调函数可以使用新的 p5.Shader 对象作为其参数。
第四个参数 failureCallback
也是可选的。 如果传递一个函数,则在着色器加载失败时将调用该函数。 回调函数可以使用事件错误作为其参数。
着色器可能需要一些时间来加载。 在 preload() 中调用 loadShader()
可确保着色器在用于 setup() 或 draw()。
注意:着色器只能在 WebGL 模式下使用。
\n"],"line":[0,12],"params":[1,[[0,{"name":[0,"vertFilename"],"description":[0,"要加载的顶点着色器的路径。
\n"],"type":[0,"字符串"]}],[0,{"name":[0,"fragFilename"],"description":[0,"要加载的片段着色器的路径。
\n"],"type":[0,"字符串"]}],[0,{"name":[0,"successCallback"],"description":[0,"加载着色器后调用的函数。可以传递 p5.Shader 对象。
\n"],"type":[0,"函数"],"optional":[0,true]}],[0,{"name":[0,"failureCallback"],"description":[0,"着色器加载失败时调用的函数。 可以传递 Error
事件对象。
\n// 注意:\"uniform\" 是着色器程序中的全局变量。\n\nlet mandelbrot;\n\n// 加载着色器并创建一个 p5.Shader 对象。\nfunction preload() {\n mandelbrot = loadShader('/assets/shader.vert', '/assets/shader.frag');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // 编译并应用 p5.Shader 对象。\n shader(mandelbrot);\n\n // 将着色器的 uniform p 设置为数组。\n mandelbrot.setUniform('p', [-0.74364388703, 0.13182590421]);\n\n // 将着色器的 uniform r 设置为值 1.5。\n mandelbrot.setUniform('r', 1.5);\n\n // 添加一个四边形作为着色器的显示表面。\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// 注意:\"uniform\" 是着色器程序中的全局变量。\n\nlet mandelbrot;\n\n// 加载着色器并创建一个 p5.Shader 对象。\nfunction preload() {\n mandelbrot = loadShader('/assets/shader.vert', '/assets/shader.frag');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // 使用 p5.Shader 对象。\n shader(mandelbrot);\n\n // 将着色器的 uniform p 设置为数组。\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 // 将着色器的 uniform r 设置为在 0 和 2 之间振荡的值。\n mandelbrot.setUniform('r', sin(frameCount * 0.01) + 1);\n\n // 添加一个四边形作为着色器的显示表面。\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n
\n设置 specularMaterial() 的\"金属度\"。
\nmetalness()
可以使材料看起来更像金属。它影响材料反射光源的方式,包括 directionalLight()、pointLight()、spotLight() 和 imageLight()。
参数 metallic
是一个数字,表示金属度的程度。 metallic
必须大于 1 ,这是它的默认值。较高的值,比如 metalness(100)
,会使高光材料看起来更像金属。
金属感的程度。
\n"],"type":[0,"数字"]}]]],"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 // 打开一个环境光。\n ambientLight(200);\n\n // 获取鼠标的坐标。\n let mx = mouseX - 50;\n let my = mouseY - 50;\n\n // 打开一个跟随鼠标移动的白色点光源。\n pointLight(255, 255, 255, mx, my, 50);\n\n // 设定球体样式。\n noStroke();\n fill(30, 30, 255);\n specularMaterial(255);\n shininess(20);\n\n // 绘制左侧金属感较低的球体。\n translate(-25, 0, 0);\n metalness(1);\n sphere(20);\n\n // 绘制右侧金属感较高的球体。\n translate(50, 0, 0);\n metalness(50);\n sphere(20);\n}\n
\n\n// 单击并拖动鼠标以从不同角度查看场景。\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 // 添加全景图。\n panorama(img);\n\n // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 使用图像作为光源。\n imageLight(img);\n\n // 设定球体样式。\n noStroke();\n specularMaterial(50);\n shininess(200);\n\n // 绘制左侧金属感较低的球体。\n translate(-25, 0, 0);\n metalness(1);\n sphere(20);\n\n // 绘制右侧金属感较高的球体。\n translate(50, 0, 0);\n metalness(50);\n sphere(20);\n}\n
\n设置当前材质为普通材质。
\n普通材质将面对 x 轴的表面设为红色,面对 y 轴的表面设为绿色,面对 z 轴的表面设为蓝色。普通材质不受光线影响。通常在调试时用作占位符材质。
\n注意:normalMaterial()
只能在 WebGL 模式下使用。
\n// 单击并拖动鼠标以从不同角度查看场景。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 设定圆环体的样式。\n normalMaterial();\n\n // 绘制圆环体。\n torus(30);\n}\n
\n恢复默认着色器。
\nresetShader()
停用之前应用的所有着色器 shader()。
注意:着色器只能在 WebGL 模式下使用。
\n"],"line":[0,773],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// 使用顶点着色器程序创建一个字符串。\n// 每个顶点都会调用顶点着色器。\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// 使用片段着色器程序创建一个字符串。\n// 每个像素都会调用片段着色器。\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 // 创建一个 p5.Shader 对象。\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 // 使用 p5.Shader 绘制一个盒子。\n // Shader() 将活动着色器设置为 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 // 使用默认填充着色器绘制一个框。\n // resetShader() 恢复默认的填充着色器。\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
\n设置要在绘制时应用的 p5.Shader 对象。
\n着色器是在图形处理单元 (GPU) 上运行的程序。 它们可以同时处理许多像素或顶点,从而可以快速执行许多图形任务。 它们是用一种名为 GLSL 并与绘图中的其余代码一起运行。p5.Shader 对象可以使用 createShader() 和 loadShader() 函数。
\n\n参数 s
是要应用的 p5.Shader 对象。 例如,调用 shader(myShader)
应用 myShader
来处理画布上的每个像素。 该着色器将用于:
sampler2D
。li>\naNormal
,或者如果它具有以下任何 uniform:uUseLighting
、uAmbientLightCount
、uDirectionalLightCount
、uPointLightCount
、uAmbientColor
、uDirectionalDiffuseColors
、uDirectionalSpecularColors
、uPointLightLocation
、uPointLightDiffuseColors
、uPointLightSpecularColors
、uLightingDirection
,或 uSpecular
。uStrokeWeight
.源代码来自一个 p5.Shader 对象的片段和顶点着色器将在第一次传递给 shader()
时进行编译。参见 MDN 了解有关编译着色器的更多信息。
调用 resetShader() 可恢复绘图的默认着色器。
\n注意:着色器只能在 WebGL 模式下使用。
\n"],"line":[0,571],"params":[1,[[0,{"name":[0,"s"],"description":[0,"应用对象 p5.Shader。
\n"],"type":[0,"p5.Shader"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// 注意:“uniform”是着色器程序中的全局变量。\n\n// 使用顶点着色器程序创建一个字符串。\n// 每个顶点都会调用顶点着色器。\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// 使用片段着色器程序创建一个字符串。\n// 每个像素都会调用片段着色器。\nlet fragSrc = `\nprecision highp float;\n\nvoid main() {\n // 将每个像素的 RGBA 值设置为黄色。\n gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);\n}\n`;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // 创建一个 p5.Shader 对象。\n let shaderProgram = createShader(vertSrc, fragSrc);\n\n // 应用 p5.Shader 对象。\n shader(shaderProgram);\n\n // 设置绘图表面的样式。\n noStroke();\n\n // 添加一个平面作为绘图表面。\n plane(100, 100);\n\n describe('A yellow square.');\n}\n
\n\n// 注意:\"uniform\" 是着色器程序中的全局变量。\n\nlet mandelbrot;\n\n// 加载着色器并创建一个 p5.Shader 对象。\nfunction preload() {\n mandelbrot = loadShader('/assets/shader.vert', '/assets/shader.frag');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // 使用 p5.Shader 对象。\n shader(mandelbrot);\n\n // 将着色器的 uniform p 设置为数组。\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 // 将着色器的 uniform r 设置为在 0 和 2 之间振荡的值。\n mandelbrot.setUniform('r', sin(frameCount * 0.01) + 1);\n\n // 添加一个四边形作为着色器的显示表面。\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n
\n\n// 注意:\"uniform\" 是着色器程序中的全局变量。\n\nlet redGreen;\nlet orangeBlue;\nlet showRedGreen = false;\n\n// 加载着色器并创建两个单独的 p5.Shader 对象。\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 // 初始化红绿着色器。\n shader(redGreen);\n\n // 设置红绿着色器的中心颜色和背景颜色。\n redGreen.setUniform('colorCenter', [1.0, 0.0, 0.0]);\n redGreen.setUniform('colorBackground', [0.0, 1.0, 0.0]);\n\n // 初始化橙蓝色着色器。\n shader(orangeBlue);\n\n // 设置橙蓝色着色器的中心颜色和背景颜色。\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 // 更新每个着色器的偏移值。\n // 垂直移动橙蓝着色器。\n // 水平移动红绿着色器。\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 // 设置绘图表面的样式。\n noStroke();\n\n // 添加四边形作为绘图表面。\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n\n// 当用户双击时在着色器之间切换。\nfunction doubleClicked() {\n showRedGreen = !showRedGreen;\n}\n
\n设置 specularMaterial() 的光泽度(\"shininess\")。
\n有光泽的材料比无光泽的材料更聚焦反射光线。shininess()
影响材料反射光源的方式,包括 directionalLight()、pointLight() 和 spotLight()。
参数 shine
是一个数字,表示光泽度的程度。 shine
必须大于 1,这是它的默认值。
光泽的程度。
\n"],"type":[0,"数字"]}]]],"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 // 打开一个红色环境光。\n ambientLight(255, 0, 0);\n\n // 获取鼠标的坐标。\n let mx = mouseX - 50;\n let my = mouseY - 50;\n\n // 打开一个跟随鼠标移动的白色点光源。\n pointLight(255, 255, 255, mx, my, 50);\n\n // 设定球体样式。\n noStroke();\n\n // 添加一个具有灰度值的高光材质。\n specularMaterial(255);\n\n // 绘制左侧光泽度较低的球体。\n translate(-25, 0, 0);\n shininess(10);\n sphere(20);\n\n // 绘制右侧光泽度较高的球体。\n translate(50, 0, 0);\n shininess(100);\n sphere(20);\n}\n
\n设置形状表面材质的高光颜色。
\nspecularMaterial()
颜色设置形状的光泽涂层将反射的光颜色的组件。例如,调用 specularMaterial(255, 255, 0)
将使形状反射红色和绿色光,但不反射蓝色光。
与 ambientMaterial() 不同,specularMaterial()
将反射包括 directionalLight()、pointLight() 和 spotLight() 在内的光源的全彩光。这就是它赋予形状“闪亮”外观的原因。材质的光泽度可以通过 shininess() 函数控制。
specularMaterial()
可以通过不同的参数以三种方式调用来设置材质的颜色。
调用 specularMaterial()
的第一种方式有一个参数 gray
。可以传递介于 0 和 255 之间的灰度值,如 specularMaterial(50)
,来设置材质的颜色。较高的灰度值会使形状看起来更亮。
调用 specularMaterial()
的第二种方式有一个参数 color
。可以传递一个 p5.Color 对象、一个颜色值数组或一个 CSS 颜色字符串,如 specularMaterial('magenta')
,来设置材质的颜色。
调用 specularMaterial()
的第三种方式有四个参数 v1
、v2
、v3
和 alpha
。 alpha
是可选的。RGBA、HSBA 或 HSLA 值可以传递来设置材质的颜色,例如 specularMaterial(255, 0, 0)
或 specularMaterial(255, 0, 0, 30)
。颜色值将根据当前的 colorMode() 进行解释。
介于 0 (黑色)和 255 (白色)之间的灰度值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"alpha"],"description":[0,"当前 colorMode() 中的 alpha 值。
\n"],"type":[0,"数字"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"v1"],"description":[0,"当前 colorMode() 中的红色或色调值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"v2"],"description":[0,"当前 colorMode() 中的绿色或饱和度值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"v3"],"description":[0,"当前 colorMode() 中的蓝色、亮度或明度值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"alpha"],"description":[0,""],"type":[0,"数字"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"color"],"description":[0,"作为 p5.Color 对象、颜色值数组或 CSS 字符串的颜色。
\n"],"type":[0,"p5.Color|数字[]|字符串"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,true],"example":[1,[[0,"\n\n// 单击并拖动鼠标以从不同角度查看场景。\n// 双击画布以应用高光材质。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 在右上方打开一个白色点光源。\n pointLight(255, 255, 255, 30, -40, 30);\n\n // 如果用户双击,则添加一个有光泽的涂层。\n if (isGlossy === true) {\n specularMaterial(255);\n shininess(50);\n }\n\n // 设定圆环的样式。\n noStroke();\n fill(255, 0, 0);\n\n // 绘制圆环。\n torus(30);\n}\n\n// 当用户双击时,使圆环有光泽。\nfunction doubleClicked() {\n isGlossy = true;\n}\n
\n\n// 单击并拖动鼠标以从不同角度查看场景。\n// 双击画布以应用高光材质。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 在右上方打开一个白色点光源。\n pointLight(255, 255, 255, 30, -40, 30);\n\n // 如果用户双击,则添加一个有光泽的绿色涂层。\n if (isGlossy === true) {\n specularMaterial(0, 255, 0);\n shininess(50);\n }\n\n // 设定圆环的样式。\n noStroke();\n fill(255, 0, 0);\n\n // 绘制圆环。\n torus(30);\n}\n\n// 当用户双击时,使圆环有光泽。\nfunction doubleClicked() {\n isGlossy = true;\n}\n
\n\n// 单击并拖动鼠标以从不同角度查看场景。\n// 双击画布以应用高光材质。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 在右上方打开一个白色点光源。\n pointLight(255, 255, 255, 30, -40, 30);\n\n // 如果用户双击,则添加一个有光泽的绿色涂层。\n if (isGlossy === true) {\n // 创建一个 p5.Color 对象。\n let c = color('green');\n specularMaterial(c);\n shininess(50);\n }\n\n // 设定圆环样式。\n noStroke();\n fill(255, 0, 0);\n\n // 绘制圆环。\n torus(30);\n}\n\n// 当用户双击时,使圆环有光泽。\nfunction doubleClicked() {\n isGlossy = true;\n}\n
\n\n// 单击并拖动鼠标以从不同角度查看场景。\n// 双击画布以应用高光材质。\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 // 使用鼠标进行轨道控制。\n orbitControl();\n\n // 在右上方打开一个白色点光源。\n pointLight(255, 255, 255, 30, -40, 30);\n\n // 如果用户双击,则添加一个有光泽的绿色涂层。\n if (isGlossy === true) {\n specularMaterial('#00FF00');\n shininess(50);\n }\n\n // 设定圆环样式。\n noStroke();\n fill(255, 0, 0);\n\n // 绘制圆环。\n torus(30);\n}\n\n// 当用户双击时,使圆环有光泽。\nfunction doubleClicked() {\n isGlossy = true;\n}\n
\n设置将用于形状的纹理。
\n纹理就像是包裹在形状周围的皮肤。texture()
函数可用于内置的形状,例如 square() 和 sphere(),以及使用 buildGeometry() 等函数创建的自定义形状。要对使用 beginShape() 创建的几何体进行纹理化,必须为每个 vertex() 调用传递 uv 坐标。
参数 tex
是要应用的纹理。texture()
可以使用包括图像、视频和离屏渲染器等来源,例如 p5.Graphics 和 p5.Framebuffer 对象。
要对使用 beginShape() 创建的几何体进行纹理化,你需要在 vertex() 中指定 uv 坐标。
\n注意:texture()
只能在 WebGL 模式下使用。
将媒体用作纹理。
\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// 加载一张图片并创建一个 p5.Image 对象。\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 // 绕 x 轴、y 轴和 z 轴旋转。\n rotateZ(frameCount * 0.01);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n\n // 将图片应用为纹理。\n texture(img);\n\n // 绘制立方体。\n box(50);\n}\n
\n\nlet pg;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // 创建一个 p5.Graphics 对象。\n pg = createGraphics(100, 100);\n\n // 在 p5.Graphics 对象上绘制一个圆形。\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 // 绕 x 轴、y 轴和 z 轴旋转。\n rotateZ(frameCount * 0.01);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n\n // 将 p5.Graphics 对象应用为纹理。\n texture(pg);\n\n // 绘制立方体。\n box(50);\n}\n
\n\nlet vid;\n\n// 加载一个视频并创建一个 p5.MediaElement 对象。\nfunction preload() {\n vid = createVideo('/assets/fingers.mov');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // 隐藏视频。\n vid.hide();\n\n // 设置视频循环播放。\n vid.loop();\n\n describe('A rectangle with video as texture');\n}\n\nfunction draw() {\n background(0);\n\n // 绕 y 轴旋转。\n rotateY(frameCount * 0.01);\n\n // 将视频应用为纹理。\n texture(vid);\n\n // 绘制矩形。\n rect(-40, -40, 80, 80);\n}\n
\n\nlet vid;\n\n// 加载一个视频并创建一个 p5.MediaElement 对象。\nfunction preload() {\n vid = createVideo('/assets/fingers.mov');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // 隐藏视频。\n vid.hide();\n\n // 设置视频循环播放。\n vid.loop();\n\n describe('A rectangle with video as texture');\n}\n\nfunction draw() {\n background(0);\n\n // 绕 y 轴旋转。\n rotateY(frameCount * 0.01);\n\n // 设置纹理模式。\n textureMode(NORMAL);\n\n // 将视频应用为纹理。\n texture(vid);\n\n // 使用 uv 坐标绘制自定义形状。\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
\n更改应用于自定义形状时使用的纹理坐标系统。
\n为了使 texture() 功能有效,一个形状需要一种方法来将其表面的点映射到图像中的像素上。内置形状如 rect() 和 box() 已经根据它们的顶点具有这些纹理映射。使用 vertex() 创建的自定义形状需要将纹理映射作为 uv 坐标传递。
\n每次调用 vertex() 都必须包括 5 个参数,如 vertex(x, y, z, u, v)
,以将坐标 (x, y, z)
上的顶点映射到图像中坐标 (u, v)
上的像素。例如,默认情况下,矩形图像的角落被映射到矩形的角落:
\n// 将图像应用为纹理。\ntexture(img);\n\n// 绘制矩形。\nrect(0, 0, 30, 50);\n
\n如果上面代码片段中的图像尺寸为 300 x 500 像素,可以按照以下方式实现相同的结果:
\n\n// 将图像应用为纹理。\ntexture(img);\n\n// 绘制矩形。\nbeginShape();
\n// 左上角。\n// u: 0, v: 0\nvertex(0, 0, 0, 0, 0);
\n// 右上角。\n// u: 300, v: 0\nvertex(30, 0, 0, 300, 0);
\n// 右下角。\n// u: 300, v: 500\nvertex(30, 50, 0, 300, 500);
\n// 左下角。\n// u: 0, v: 500\nvertex(0, 50, 0, 0, 500);
\nendShape();\n
\ntextureMode()
用于改变 uv 坐标的坐标系统。
参数 mode
接受两种可能的常量。如果传递 NORMAL
,如 textureMode(NORMAL)
中所示,则纹理的 uv 坐标可以在 0 到 1 的范围内提供,而不是图像的尺寸。这对于使用相同的代码处理不同尺寸的多张图像很有帮助。例如,上面的代码片段可以重写如下:
\n// 设置纹理模式以使用标准化坐标。\ntextureMode(NORMAL);\n\n// 将图像应用为纹理。\ntexture(img);
\n// 绘制矩形。\nbeginShape();
\n// 左上角。\n// u: 0, v: 0\nvertex(0, 0, 0, 0, 0);
\n// 右上角。\n// u: 1, v: 0\nvertex(30, 0, 0, 1, 0);
\n// 右下角。\n// u: 1, v: 1\nvertex(30, 50, 0, 1, 1);
\n// 左下角。\n// u: 0, v: 1\nvertex(0, 50, 0, 0, 1);
\nendShape();\n
\n默认情况下,mode
是 IMAGE
,它将 uv 坐标缩放到图像的尺寸。调用 textureMode(IMAGE)
会应用这个默认设置。
注意:textureMode()
只能在 WebGL 模式下使用。
可以是 IMAGE 或 NORMAL。
\n"],"type":[0,"常数"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\nlet img;\n\n// 加载一张图像并创建一个 p5.Image 对象。\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 // 将图像应用为纹理。\n texture(img);\n\n // 绘制自定义形状。\n // 使用图像的宽度和高度作为 uv 坐标。\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// 加载一张图像并创建一个 p5.Image 对象。\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 // 设置纹理模式。\n textureMode(NORMAL);\n\n // 将图像应用为纹理。\n texture(img);\n\n // 绘制自定义形状。\n // 使用归一化的 uv 坐标。\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
\n当形状的 uv 坐标超出纹理时,改变纹理的行为方式。
\n为了使 texture() 正常工作,一个形状需要一种将其表面上的点映射到图像中的像素的方法。内置的形状,如 rect() 和 box(),已经根据它们的顶点具有了这些纹理映射。使用 vertex() 创建的自定义形状需要将纹理映射传递为 uv 坐标。
\n每次调用 vertex() 都必须包括 5 个参数,如 vertex(x, y, z, u, v)
,以将坐标 (x, y, z)
处的顶点映射到图像中坐标 (u, v)
的像素。例如,矩形图像的角落默认映射到矩形的角落:
\n// 应用图像作为纹理。\ntexture(img);\n\n// 绘制矩形。\nrect(0, 0, 30, 50);\n
\n如果上面代码片段中的图像尺寸为 300 x 500 像素,则可以通过以下方式获得相同的结果:
\n\n// 应用图像作为纹理。\ntexture(img);\n\n// 绘制矩形。\nbeginShape();
\n// 左上角。\n// u: 0, v: 0\nvertex(0, 0, 0, 0, 0);
\n// 右上角。\n// u: 300, v: 0\nvertex(30, 0, 0, 300, 0);
\n// 右下角。\n// u: 300, v: 500\nvertex(30, 50, 0, 300, 500);
\n// 左下角。\n// u: 0, v: 500\nvertex(0, 50, 0, 0, 500);
\nendShape();\n
\ntextureWrap()
控制纹理在其 uv 坐标超出纹理时的行为。这样做可以产生有趣的视觉效果,如平铺。例如,上面的自定义形状可能具有超出图像宽度的 u 坐标:
\n// 应用图像作为纹理。\ntexture(img);\n\n// 绘制矩形。\nbeginShape();\nvertex(0, 0, 0, 0, 0);
\n// 右上角。\n// u: 600\nvertex(30, 0, 0, 600, 0);
\n// 右下角。\n// u: 600\nvertex(30, 50, 0, 600, 500);
\nvertex(0, 50, 0, 0, 500);\nendShape();\n
\n600 的 u 坐标大于 300 的纹理图像宽度,这就带来了一些有趣的可能性。
\n第一个参数 wrapX
接受三种可能的常量。如果传递 CLAMP
,如 textureWrap(CLAMP)
中所示,则纹理边缘的像素将延伸到形状的边缘。如果传递 REPEAT
,如 textureWrap(REPEAT)
中所示,则纹理将重复平铺直到达到形状的边缘。如果传递 MIRROR
,如 textureWrap(MIRROR)
中所示,则纹理将重复平铺直到达到形状的边缘,同时在平铺之间翻转其方向。默认情况下,纹理使用 CLAMP
模式。
第二个参数 wrapY
是可选的。它接受相同的三个常量:CLAMP
、REPEAT
和 MIRROR
。如果传递了其中一个常量,如 textureWRAP(MIRROR, REPEAT)
,那么纹理将在水平方向上 MIRROR
,在垂直方向上 REPEAT
。默认情况下,wrapY
将被设置为与 wrapX
相同的值。
注意:textureWrap()
只能在 WebGL 模式下使用。
可以是 CLAMP、REPEAT 或 MIRROR
\n"],"type":[0,"常数"]}],[0,{"name":[0,"wrapY"],"description":[0,"可以是 CLAMP、REPEAT 或 MIRROR
\n"],"type":[0,"常数"],"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 // 设置纹理模式。\n textureMode(NORMAL);\n\n // 设置纹理包裹方式。\n // 注意:CLAMP 是默认模式。\n textureWrap(CLAMP);\n\n // 应用图像作为纹理。\n texture(img);\n\n // 设定形状样式。\n noStroke();\n\n // 绘制形状。\n // 使用大于 1 的 uv 坐标。\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 // 设置纹理模式。\n textureMode(NORMAL);\n\n // 设置纹理包裹方式。\n textureWrap(REPEAT);\n\n // 应用图像作为纹理。\n texture(img);\n\n // 设定形状样式。\n noStroke();\n\n // 绘制形状。\n // 使用大于 1 的 uv 坐标。\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 // 设置纹理模式。\n textureMode(NORMAL);\n\n // 设置纹理包裹方式。\n textureWrap(MIRROR);\n\n // 应用图像作为纹理。\n texture(img);\n\n // 设定形状样式。\n noStroke();\n\n // 绘制形状。\n // 使用大于 1 的 uv 坐标。\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 // 设置纹理模式。\n textureMode(NORMAL);\n\n // 设置纹理包裹方式。\n textureWrap(REPEAT, MIRROR);\n\n // 应用图像作为纹理。\n texture(img);\n\n // 设定形状样式。\n noStroke();\n\n // 绘制形状。\n // 使用大于 1 的 uv 坐标。\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设置 3D 场景中当前相机的位置和方向。
\ncamera()
允许从不同角度查看对象。它有九个可选参数。
前三个参数 x
、y
和 z
是相机位置的坐标。例如,调用 camera(0, 0, 0)
将相机放置在原点 (0, 0, 0)
。默认情况下,相机放置在 (0, 0, 800)
。
接下来的三个参数 centerX
、centerY
和 centerZ
是相机面向的点的坐标。例如,调用 camera(0, 0, 0, 10, 20, 30)
将相机放置在原点 (0, 0, 0)
并将其指向 (10, 20, 30)
。默认情况下,相机指向原点 (0, 0, 0)
。
最后三个参数 upX
、upY
和 upZ
是“上”向量的分量。\"上\" 向量定位相机的 y 轴。例如,调用 camera(0, 0, 0, 10, 20, 30, 0, -1, 0)
将相机放置在原点 (0, 0, 0)
,指向 (10, 20, 30)
,并将 \"上\" 向量设置为 (0, -1, 0)
,就像倒置相机一样。默认情况下,\"上\" 向量是 (0, 1, 0)
。
注意:camera()
只能在 WebGL 模式下使用。
相机的 x 坐标。默认为 0。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"y"],"description":[0,"相机的 y 坐标。默认为 0。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"z"],"description":[0,"相机的z坐标。默认为 0。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"centerX"],"description":[0,"相机面向点的x坐标。默认为 0。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"centerY"],"description":[0,"相机面向点的y坐标。默认为 0。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"centerZ"],"description":[0,"相机面向点的z坐标。默认为 0。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"upX"],"description":[0,"摄像机 \"向上 \"矢量的 x 分量。默认为 0。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"upY"],"description":[0,"摄像机 \"向上 \"矢量的 y 分量。默认为 0。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"upZ"],"description":[0,"摄像机 \"向上 \"矢量的 z 分量。默认为 0。
\n"],"type":[0,"数字"],"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
\n创建一个新的 p5.Camera 对象并将之设置为当前的(活跃的)相机。
\n新摄像机初始化时的默认位置为 (0, 0, 800)
,且默认为透视投影。其属性可通过诸如 myCamera.lookAt(0, 0, 0)
的 p5.Camera 方法控制。
每个 3D 草图开始时都会初始化一个默认摄像头。可以使用 camera()、perspective()、ortho() 和 frustum() 函数进行控制。
\n注意:createCamera()
只能在 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
\n设置 3D 草图中当前摄像机的视锥体。
\n在锥形投影中,距离相机更远的形状比靠近相机的形状看起来更小。这种称为透视缩短的技术可以创建逼真的 3D 场景。
\nfrustum()
通过改变其视锥体来改变相机的透视。视锥体是相机可见的空间体积。视锥体的形状是一个顶部被切掉的金字塔。相机放置在金字塔原来的顶部位置,并朝向金字塔的底部。它查看视锥体内的所有内容。
前四个参数 left
, right
, bottom
, 和 top
设置视锥体的左右个平面、底部平面和顶部平面的坐标。例如,调用 frustum(-100, 100, 200, -200)
创建一个宽度为 200 像素、高度为 400 像素的视锥体。默认情况下,这些坐标根据绘图的宽度和高度设置,如 ortho(-width / 20, width / 20, height / 20, -height / 20)
。
最后两个参数 near
和 far
设置视锥体近面和远面与相机的距离。例如,调用 ortho(-100, 100, 200, -200, 50, 1000)
创建一个宽度为 200 像素、高度为 400 像素的视锥体,距相机 50 像素开始,距相机 1,000 像素结束。默认情况下,近面设置为 0.1 * 800
,即相机与原点之间的默认距离的十分之一。far
设置为 10 * 800
,即相机与原点之间的默认距离的十倍。
注意:frustum()
只能在 WebGL 模式下使用。
视锥体左侧平面的 x 坐标。默认为 -width / 20
。
视锥体右侧平面的 x 坐标。默认为 width / 20
。
视锥体底部平面的 y 坐标。默认为 height / 20
。
视锥体顶部平面的 y 坐标。默认为 -height / 20
。
视锥体近平面的 z 坐标。默认为 0.1 * 800
。
视锥体远平面的 z 坐标。默认为 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
\n启用或禁用 3D 草图中线条的透视功能。
\n在 WebGL 模式中,当线条距离摄像头较远时,可以使用较细的笔触来绘制线条。这样可以让线条看起来更真实。
\n默认情况下,线条会根据所使用的透视类型以不同的方式绘制:
\nperspective()
和 frustum()
用于模拟逼真的透视效果。在这两种模式中,笔触的重量受线条与相机间距离的影响。这样做可以使线条外观更自然。 perspective()
是 3D 草图中的默认模式。ortho()
不会模拟真实的视角。在该模式下,无论线条与摄像机的距离如何,笔划权重都是一致的。这样可以获得更可预测且更一致的外观。linePerspective()
可以覆盖默认的线条绘制模式。
参数 enable
是个可选参数。它是一个 Boolean
值,用于设置线条的绘制方式。如果传入的值为 true
,比如 linePerspective(true)
,那么当线条离摄像机较远时,就会显得较细。如果传入值为 false
,比如 linePerspective(false)
,则无论线条与摄像机的距离如何,其笔画权重都将保持一致。默认情况下,启用 linePerspective()
。
如果启用了 linePerspective()
则调用它而不传递参数将返回 true
。如果未启用,则返回 false
。
注意:linePerspective()
只能在 WebGL 模式下使用。
是否启用线条透视。
\n"],"type":[0,"布尔值"]}]]]}],[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
\n为相机设置正交投影。
\n在正交投影中,相同大小的形状始终呈现相同的大小,无论它们距离相机远近如何。
\northo()
通过将视锥体从截断的金字塔形状更改为矩形棱柱来改变相机的透视。相机放置在视锥体的前方,并查看视锥体内的所有内容。 ortho()
有六个可选参数来定义视锥体。
前四个参数 left
, right
, bottom
, 和 top
设置视锥体的边、底部和顶部的坐标。例如,调用 创建一个宽度为 200 像素、高度为 400 像素的视锥体。默认情况下,这些尺寸根据绘图的宽度和高度设置,如 ortho(-width / 2, width / 2, -height / 2, height / 2)
。
最后两个参数 near
和 far
设置视锥体近面和远面与相机的距离。例如,调用 ortho(-100, 100, 200, 200, 50, 1000)
创建一个宽度为 200 像素、高度为 400 像素的视锥体,距相机 50 像素开始,距相机 1,000 像素结束。默认情况下,near
和 far
分别设置为 0 和 max(width, height) + 800
。
注意:ortho()
只能在 WebGL 模式下使用。
视锥体左侧平面的 x 坐标。默认为 -width / 2
。
视锥体右侧平面的 x 坐标。默认为 width / 2
。
视锥体底部平面的 y 坐标。默认为 height / 2
。
视锥体顶部平面的 y 坐标。默认为 -height / 2
。
视锥体近面的 z 坐标。默认为 0。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"far"],"description":[0,"视锥体远平面的 z 坐标。默认为 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
\n在三维场景中为当前相机设置透视投影。
在透视投影中,距离相机更远的形状比距离相机更近的形状看起来更小。这种技术称为透视缩放,可以创建出逼真的三维场景。在 WebGL 模式下,默认情况下会应用这种技术。
perspective()
通过改变相机的视锥来改变相机的透视效果。视锥是相机可见的空间体积。它的形状是一个顶部被截掉的金字塔。相机放置在金字塔的顶部应该在的位置,并查看视锥的顶部(近)平面和底部(远)平面之间的所有内容。
第一个参数 fovy
是相机的垂直视野。它是一个角度,描述相机的视野有多高或多窄。例如,调用 perspective(0.5)
将相机的垂直视野设置为 0.5 弧度。默认情况下,fovy
是根据绘图的高度和相机的默认 z 坐标(800)计算的。默认 fovy
的公式是 2 * atan(height / 2 / 800)
。
第二个参数 aspect
是相机的宽高比。它是一个数字,描述了顶部平面的宽度与其高度的比率。例如,调用 perspective(0.5, 1.5)
将相机的视野设置为 0.5 弧度,宽高比设置为 1.5,这会使形状在正方形画布上看起来更窄。默认情况下,宽高比被设置为 width / height
。
第三个参数 near
是相机到近平面的距离。例如,调用 perspective(0.5, 1.5, 100)
将相机的视野设置为 0.5 弧度,宽高比设置为 1.5,并将近平面放置在相机的 100 像素处。任何距离相机少于 100 像素的形状都不会可见。默认情况下,near 被设置为 0.1 * 800
,这是相机与原点之间默认距离的十分之一。
第四个参数 far
是相机到远平面的距离。例如,调用 perspective(0.5, 1.5, 100, 10000)
将相机的视野设置为 0.5 弧度,宽高比设置为 1.5,将近平面放置在相机的 100 像素处,并将远平面放置在相机的 10,000 像素处。任何距离相机超过 10,000 像素的形状都不会可见。默认情况下,far 被设置为 10 * 800
,这是相机与原点之间的默认距离的十倍。
注意:perspective()
只能在 WebGL 模式下使用。
相机视锥体的垂直视场角。默认为 2 * atan(height / 2 / 800)
。
相机的宽高比。默认为 width / height
。
相机到近裁剪平面的距离。默认为 0.1 * 800
。
相机到远裁剪平的距离。默认为 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
\n设置 3D 草图的当前(活跃)相机。
\nsetCamera()
可在使用 createCamera() 创建的多个摄像机之间切换。
注意 setCamera()
只能在 WebGL 模式下使用。
应激活的相机。
\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
\nA class to describe a shader program.
\nEach p5.Shader
object contains a shader program that runs on the graphics\nprocessing unit (GPU). Shaders can process many pixels or vertices at the\nsame time, making them fast for many graphics tasks. They’re written in a\nlanguage called\nGLSL\nand run along with the rest of the code in a sketch.
A shader program consists of two files, a vertex shader and a fragment\nshader. The vertex shader affects where 3D geometry is drawn on the screen\nand the fragment shader affects color. Once the p5.Shader
object is\ncreated, it can be used with the shader()\nfunction, as in shader(myShader)
.
Note: createShader(),\ncreateFilterShader(), and\nloadShader() are the recommended ways to\ncreate an instance of this class.
\n"],"line":[0,11],"params":[1,[[0,{"name":[0,"renderer"],"description":[0,"WebGL context for this shader.
\n"],"type":[0,"p5.RendererGL"]}],[0,{"name":[0,"vertSrc"],"description":[0,"source code for the vertex shader program.
\n"],"type":[0,"String"]}],[0,{"name":[0,"fragSrc"],"description":[0,"source code for the fragment shader program.
\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
\nCopies the shader from one drawing context to another.
\nEach p5.Shader
object must be compiled by calling\nshader() before it can run. Compilation happens\nin a drawing context which is usually the main canvas or an instance of\np5.Graphics. A shader can only be used in the\ncontext where it was compiled. The copyToContext()
method compiles the\nshader again and copies it to another drawing context where it can be\nreused.
The parameter, context
, is the drawing context where the shader will be\nused. The shader can be copied to an instance of\np5.Graphics, as in\nmyShader.copyToContext(pg)
. The shader can also be copied from a\np5.Graphics object to the main canvas using\nthe window
variable, as in myShader.copyToContext(window)
.
Note: A p5.Shader object created with\ncreateShader(),\ncreateFilterShader(), or\nloadShader()\ncan be used directly with a p5.Framebuffer\nobject created with\ncreateFramebuffer(). Both objects\nhave the same context as the main canvas.
\n"],"path":[0,"p5.Shader/copyToContext"]}],"setUniform":[0,{"description":[0,"Sets the shader’s uniform (global) variables.
\nShader programs run on the computer’s graphics processing unit (GPU).\nThey live in part of the computer’s memory that’s completely separate\nfrom the sketch that runs them. Uniforms are global variables within a\nshader program. They provide a way to pass values from a sketch running\non the CPU to a shader program running on the GPU.
\nThe first parameter, uniformName
, is a string with the uniform’s name.\nFor the shader above, uniformName
would be 'r'
.
The second parameter, data
, is the value that should be used to set the\nuniform. For example, calling myShader.setUniform('r', 0.5)
would set\nthe r
uniform in the shader above to 0.5
. data should match the\nuniform’s type. Numbers, strings, booleans, arrays, and many types of\nimages can all be passed to a shader with setUniform()
.
Copies the shader from one drawing context to another.
\nEach p5.Shader
object must be compiled by calling\nshader() before it can run. Compilation happens\nin a drawing context which is usually the main canvas or an instance of\np5.Graphics. A shader can only be used in the\ncontext where it was compiled. The copyToContext()
method compiles the\nshader again and copies it to another drawing context where it can be\nreused.
The parameter, context
, is the drawing context where the shader will be\nused. The shader can be copied to an instance of\np5.Graphics, as in\nmyShader.copyToContext(pg)
. The shader can also be copied from a\np5.Graphics object to the main canvas using\nthe window
variable, as in myShader.copyToContext(window)
.
Note: A p5.Shader object created with\ncreateShader(),\ncreateFilterShader(), or\nloadShader()\ncan be used directly with a p5.Framebuffer\nobject created with\ncreateFramebuffer(). Both objects\nhave the same context as the main canvas.
\n"],"line":[0,211],"params":[1,[[0,{"name":[0,"context"],"description":[0,"WebGL context for the copied shader.
\n"],"type":[0,"p5|p5.Graphics"]}]]],"itemtype":[0,"method"],"class":[0,"p5.Shader"],"chainable":[0,false],"return":[0,{"description":[0,"new shader compiled for the target context."],"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
\nSets the shader’s uniform (global) variables.
\nShader programs run on the computer’s graphics processing unit (GPU).\nThey live in part of the computer’s memory that’s completely separate\nfrom the sketch that runs them. Uniforms are global variables within a\nshader program. They provide a way to pass values from a sketch running\non the CPU to a shader program running on the GPU.
\nThe first parameter, uniformName
, is a string with the uniform’s name.\nFor the shader above, uniformName
would be 'r'
.
The second parameter, data
, is the value that should be used to set the\nuniform. For example, calling myShader.setUniform('r', 0.5)
would set\nthe r
uniform in the shader above to 0.5
. data should match the\nuniform’s type. Numbers, strings, booleans, arrays, and many types of\nimages can all be passed to a shader with setUniform()
.
name of the uniform. Must match the name\n used in the vertex and fragment shaders.
\n"],"type":[0,"String"]}],[0,{"name":[0,"data"],"description":[0,"value to assign to the uniform. Must match the uniform’s data type.
\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,"数学"],"subcats":[1,[[0,{"name":[0],"entry":[0],"entries":[1,[]]}],[0,{"name":[0,"三角函数"],"entry":[0],"entries":[1,[[0,{"id":[0,"zh-Hans/p5/acos.mdx"],"slug":[0,"zh-hans/p5/acos"],"body":[0,"\n\n# acos\n"],"collection":[0,"reference"],"data":[0,{"title":[0,"acos()"],"module":[0,"数学"],"submodule":[0,"三角函数"],"file":[0,"src/math/trigonometry.js"],"description":[0,"计算一个数字的反余弦值。
\nacos()
是 cos() 的逆函数。它期望的参数范围是 -1 到 1。默认情况下,acos()
返回的值范围是 0 到 π(约3.14)。如果 angleMode()是DEGREES
,那么返回的值范围是 0 到 180。
要返回其反余弦值的数值。
\n"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"给定值的反余弦值。"],"type":[0,"数字"]}],"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
\n更改用于测量角度的单位系统。
\n度和弧度都是测量角度的单位。一次完整的旋转等于 360 度。一次完整的旋转是 2 × π(约6.28)弧度。
\n如 rotate()
和 sin()
等函数默认使用弧度来测量角度。调用 angleMode(DEGREES)
切换到度数。调用 angleMode(RADIANS)
切换回弧度。
不带参数调用 angleMode()
会返回当前角度模式,可能是 RADIANS
或 DEGREES
。
可以是 RADIANS 或 DEGREES。
\n"],"type":[0,"常量"]}]]]}],[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
\n计算一个数字的反正弦值。
\nasin()
是 sin() 的逆函数。它期望输入值在 -1 到 1 的范围内。默认情况下,asin()
返回的值范围是 -π ÷ 2(约-1.57)到 π ÷ 2(约1.57)。如果 angleMode() 设置为 DEGREES
,则返回的值范围是 -90 到 90。
要返回其反正弦值的数值。
\n"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"给定值的反正弦值。"],"type":[0,"数字"]}],"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
\n计算一个数字的反正切值。
\natan()
是 tan() 的逆函数。它期望输入值在 -Infinity 到 Infinity 的范围内。默认情况下,atan()
返回的值范围是 -π ÷ 2(约-1.57)到 π ÷ 2(约1.57)。如果 angleMode() 设置为 DEGREES
,则返回的值范围是 -90 到 90。
要返回其反正切值的数值。
\n"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"给定值的反正切值。"],"type":[0,"数字"]}],"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
\n计算由一个点,作为原点和正 x 轴形成的角度。
\natan2()
最常用于将几何图形定向到鼠标的位置,如 atan2(mouseY, mouseX)
。第一个参数是点的 y 坐标,第二个参数是其 x 坐标。
默认情况下,atan2()
返回的值范围是 -π(约-3.14)到 π(3.14)。如果 angleMode() 设置为 DEGREES
,则返回的值范围是 -180 到 180。
点的 y 坐标。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"x"],"description":[0,"点的 x 坐标。
\n"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"给定点的反正切。"],"type":[0,"数字"]}],"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
\n计算一个角度的余弦值。
\ncos()
在创意编程中的许多几何运算中都非常有用。随着输入角度的增加,返回的值在 -1 和 1 之间振荡。cos()
考虑了当前的 angleMode()。
角度。
\n"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"角度的余弦值。"],"type":[0,"数字"]}],"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
\n将以弧度表示的角度转换为以度表示的值。
\n角度和弧度都是用于测量角度的单位。一个完整的旋转有 360˚。一个完整的旋转是 2 × π(约 6.28)弧度。
\n同一个角度可以用任何一个单位来表示。例如,90° 是一个完整旋转的四分之一。同一个角度可以表示为 2 × π ÷ 4(约 1.57)弧度。
"],"line":[0,479],"params":[1,[[0,{"name":[0,"radians"],"description":[0,"\n要转换为度数的弧度值。
"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"转换后的角度。"],"type":[0,"数字"]}],"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
\n将角度单位从度转换为弧度。
\n\n度和弧度都是测量角度的单位。一次完整的旋转等于 360 度。一次完整的旋转是 2 × π(约6.28)弧度。
\n\n同一个角度可以用这两种单位来表示。例如,90° 是四分之一次完整的旋转。同样的角度是 2 × π ÷ 4(约1.57)弧度。
\n"],"line":[0,515],"params":[1,[[0,{"name":[0,"degrees"],"description":[0,"要转换为弧度的度数值。
\n"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"转换后的角度。"],"type":[0,"数字"]}],"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
\n计算一个角度的正弦值。
\nsin()
在创意编程里的许多几何任务中都非常有用。随着输入角度的增加,返回的值在 -1 和 1 之间振荡。sin()
会考虑当前的 angleMode()。
角度。
"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"角度的正弦值。"],"type":[0,"数字"]}],"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
\n计算一个角度的正切值。
\ntan()
在创意编程里的许多几何任务中都非常有用。返回的值范围从负无穷到正无穷,并随着输入角度的增加而周期性地重复。tan()
会考虑当前的 angleMode()。
角度。
"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"角度的正切值。"],"type":[0,"数字"]}],"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
\n创建一个新的 p5.Vector 对象。
\n向量可以用不同的方式来理解。在一个视角中,向量就像是空间中指向某方向的箭头。向量既有大小(长度)也有方向。这种视角对于编程运动非常有帮助。
\n向量的组成决定了它的大小和方向。例如,调用 createVector(3, 4)
会创建一个新的 p5.Vector 对象,其 x 部分为 3,y 部分为 4。从原点出发,这个向量的尖端向右 3 个单位,向下 4 个单位。
p5.Vector 对象常用于编程运动,因为它们简化了数学计算。例如,一个移动的球有一个位置和一个速度。位置描述了球在空间中的位置。球的位置向量从原点延伸到球的中心。速度描述了球的速度和移动的方向。如果球直线向上移动,它的速度向量就直线向上。向球的位置向量添加球的速度向量,就可以移动它,如 pos.add(vel)
。向量数学依赖于 p5.Vector 类内的方法。
向量的 x 组成部分。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"y"],"description":[0,"向量的 y 组成部分。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"z"],"description":[0,"向量的 z 组成部分。
\n"],"type":[0,"数字"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"新的 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
\n返回可以调整以呈现自然感觉的随机数。
\n通过 random() 和 randomGaussian() 返回的值,在函数调用之间可以有很大的变化。相比之下,noise()
返回的值可以被制成“平滑”的。对 noise()
的相似输入调用将产生相似的输出。noise()
用于创建纹理、运动、形状、地形等。Ken Perlin 在 1980 年代为最初的 Tron 电影制作动画时发明了 noise()
。
>noise()
总是返回 0 到 1 之间的值。在绘图运行时,它为给定的输入返回相同的值。noise()
每次绘图运行时产生不同的结果。noiseSeed() 函数可以用来每次绘图运行时生成相同的 Perlin 噪声值序列。
可以通过两种方式调整噪声的特性。第一种方式是缩放输入。noise()
将输入解释为坐标。当输入坐标更接近时,噪声值的序列会更平滑。第二种方式是使用 noiseDetail() 函数。
带有一个参数的 noise()
版本在一个维度上计算噪声值。这个维度可以被认为是空间,如 noise(x)
,或时间,如noise(t)
。
带有两个参数的 noise()
版本在两个维度上计算噪声值。这些维度可以被认为是空间,如 noise(x, y)
,或空间和时间,如 noise(x, t)
。
带有三个参数的 noise()
版本在三个维度上计算噪声值。这些维度可以被认为是空间,如 noise(x, y, z)
,或空间和时间,如 noise(x, y, t)
。
噪声空间中的x坐标。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"y"],"description":[0,"噪声空间中的y坐标。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"z"],"description":[0,"噪声空间中的z坐标。
\n"],"type":[0,"数字"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"指定坐标的 Perlin 噪声值。"],"type":[0,"数字"]}],"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
\n调整由 noise() 函数产生的噪声的特性。
\nPerlin 噪声值是通过叠加多层噪声生成的。这些噪声层被称为倍频,类似于音乐中的和声。较低的倍频对输出信号的贡献更大,它们定义了噪声的整体强度。而较高的倍频则创造出更细腻的细节。
\n默认情况下,噪声值是通过组合四个倍频创建的。每个更高的倍频贡献的量是其前一个的一半(少了50%)。noiseDetail()
可以改变倍频的数量和衰减量。例如,调用 noiseDetail(6, 0.25)
会确保 noise() 使用六个倍频。每个更高的倍频将贡献的量为其前一个的25%(少了75%)。衰减值在 0 到 1 之间是有效的。然而,衰减值大于 0.5 可能会导致噪声值大于 1。
噪声使用的倍频数量。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"falloff"],"description":[0,"每个倍频的衰减因子。
\n"],"type":[0,"数字"]}]]],"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
\n为 noise() 函数设置种子值。
\n默认情况下,noise() 每次运行绘图时都会产生不同的结果。使用常量参数调用 noiseSeed()
,例如 noiseSeed(99)
,使 noise() 每次运行绘图时产生相同的结果。
噪声种子值。
\n"],"type":[0,"数字"]}]]],"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
\n计算一个数的绝对值。
\n一个数的绝对值是它在数轴上距离零的距离。-5 和 5 都距离零五个单位,所以调用 abs(-5)
和 abs(5)
都会返回 5。一个数的绝对值始终是正数。
要计算的数值。
"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"给定数的绝对值。"],"type":[0,"数字"]}],"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
\n计算最接近给定数且大于或等于它的整数值。
\n例如,调用 ceil(9.03)
和 ceil(9.97)
都会返回值 10。
要向上取整的数字。
"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"向上取整后的数字。"],"type":[0,"整数"]}],"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
\n将一个数字限制在最小值和最大值之间。
"],"line":[0,91],"params":[1,[[0,{"name":[0,"n"],"description":[0,"\n需要限制的数字。
"],"type":[0,"数字"]}],[0,{"name":[0,"low"],"description":[0,"\n最小限制。
"],"type":[0,"数字"]}],[0,{"name":[0,"high"],"description":[0,"\n最大限制。
"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"受限制的数字。"],"type":[0,"数字"]}],"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
\n计算两点之间的距离。
\n带有四个参数的 dist()
版本计算二维空间中的距离。
带有六个参数的 dist()
版本计算三维空间中的距离。
使用 p5.Vector.dist() 来计算两个 p5.Vector 对象之间的距离。
\n"],"line":[0,155],"overloads":[1,[[0,{"params":[1,[[0,{"name":[0,"x1"],"description":[0,"第一个点的x坐标。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"y1"],"description":[0,"第一个点的y坐标。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"x2"],"description":[0,"第二个点的x坐标。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"y2"],"description":[0,"第二个点的y坐标。
\n"],"type":[0,"数字"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"x1"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"y1"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"z1"],"description":[0,"第一个点的z坐标。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"x2"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"y2"],"description":[0,""],"type":[0,"数字"]}],[0,{"name":[0,"z2"],"description":[0,"第二个点的z坐标。
\n"],"type":[0,"数字"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"两点之间的距离。"],"type":[0,"数字"]}],"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
\n计算自然常数 e(2.71828...)的一个数次方。
"],"line":[0,230],"params":[1,[[0,{"name":[0,"n"],"description":[0,"\n要进行指数运算的指数。
"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"e^n"],"type":[0,"数字"]}],"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
\n计算最接近给定数字且小于或等于它的整数值。
"],"line":[0,294],"params":[1,[[0,{"name":[0,"n"],"description":[0,"\n需要向下取整的数字。
"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"向下取整后的数字。"],"type":[0,"整数"]}],"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
\n计算一个数字的小数部分。
\n一个数字的小数部分包括其小数值。例如,\nfract(12.34)
返回 0.34。
将被计算的数字的小数部分。
"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"n的小数部分。"],"type":[0,"数字"]}],"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
\n在特定增量下计算两个数字之间的数值。
\namt
参数是在两个数字之间插值的量。0.0 等于第一个数字,0.1 非常接近第一个数字,0.5 是中间值,1.0 等于第二个数字。lerp()
函数方便用于沿直线路径创建运动和绘制虚线。
如果 amt
的值小于 0 或大于 1,lerp()
将返回原始区间之外的数字。例如,调用 lerp(0, 10, 1.5)
将返回 15。
第一个值。
"],"type":[0,"数字"]}],[0,{"name":[0,"stop"],"description":[0,"\n第二个值。
"],"type":[0,"数字"]}],[0,{"name":[0,"amt"],"description":[0,"\n数字。
"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"插值后的值。"],"type":[0,"数字"]}],"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
\n计算一个数的自然对数(以 e 为底的对数)。
\nlog()
函数期望参数 n
的值大于 0,因为自然对数是这样定义的。
大于 0 的数。
"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"n 的自然对数。"],"type":[0,"数字"]}],"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
\n计算一个向量的大小或长度。
\n向量可以用不同的方式来理解。在一种观点中,向量是空间中的一个点。向量的组成部分,x
和y
,是点的坐标(x, y)
。向量的大小是从原点(0, 0)
到(x, y)
的距离。mag(x, y)
是调用dist(0, 0, x, y)
的快捷方式。
向量也可以被认为是空间中指向某方向的箭头。这种视角对编程运动很有帮助。更多细节请参见p5.Vector。
\n可以使用p5.Vector.mag()来计算p5.Vector对象的大小。
\n"],"line":[0,481],"params":[1,[[0,{"name":[0,"x"],"description":[0,"向量的第一个组成部分。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"y"],"description":[0,"向量的第二个组成部分。
\n"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"向量的大小。"],"type":[0,"数字"]}],"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(2, 0, 10, 0, 100)
返回 20。前三个参数设置原始值为 2,原始范围从 0 到 10。最后两个参数设置目标范围从 0 到 100。20 在目标范围 [0, 100] 中的位置与 2 在原始范围 [0, 10] 中的位置成比例。\n\n第六个参数 withinBounds
是可选的。默认情况下,map()
可以返回目标范围之外的值。例如,map(11, 0, 10, 0, 100)
返回 110。将 true
作为第六个参数传递可以将重新映射的值限制在目标范围内。例如,map(11, 0, 10, 0, 100, true)
返回 100。"],"line":[0,534],"params":[1,[[0,{"name":[0,"value"],"description":[0,"\n要重新映射的值。
"],"type":[0,"数字"]}],[0,{"name":[0,"start1"],"description":[0,"\n当前范围的下限值。
"],"type":[0,"数字"]}],[0,{"name":[0,"stop1"],"description":[0,"\n当前范围的上限值。
"],"type":[0,"数字"]}],[0,{"name":[0,"start2"],"description":[0,"\n目标范围的下限值。
"],"type":[0,"数字"]}],[0,{"name":[0,"stop2"],"description":[0,"\n目标范围的上限值。
"],"type":[0,"数字"]}],[0,{"name":[0,"withinBounds"],"description":[0,"\n将数值约束在新映射的范围内。
"],"type":[0,"布尔"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"重新映射后的数字。"],"type":[0,"数字"]}],"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
\n返回一组数字中的最大值。
\n带有一个参数的 max()
版本将其解释为一组数字,并返回最大的数字。
带有两个或更多参数的 max()
版本将它们解释为单独的数字,并返回最大的数字。
要比较的第一个数字。
"],"type":[0,"数字"]}],[0,{"name":[0,"n1"],"description":[0,"\n要比较的第二个数字。
"],"type":[0,"数字"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"nums"],"description":[0,"\n要比较的数字。
"],"type":[0,"数字[]"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"最大值。"],"type":[0,"数字"]}],"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
\n返回数字序列中的最小值。
\n带有一个参数的 min()
版本将其解释为数字数组,并返回最小的数字。
带有两个或更多参数的 min()
版本将它们解释为单独的数字,并返回最小的数字。
要比较的第一个数字。
"],"type":[0,"数字"]}],[0,{"name":[0,"n1"],"description":[0,"\n要比较的第二个数字。
"],"type":[0,"数字"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"nums"],"description":[0,"\n要比较的数字。
"],"type":[0,"数字[]"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"最小值。"],"type":[0,"数字"]}],"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
\n将一个数字从一个范围映射到 0 到 1 之间的值。
\n例如,norm(2, 0, 10)
返回 0.2。数字 2 在原始范围 [0, 10] 中的位置与 0.2 在范围 [0, 1] 中的位置成比例。这与调用 map(2, 0, 10, 0, 1)
是相同的。
超出原始范围的数字不会被限制在 0 和 1 之间。超出范围的值通常是有意的并且很有用。
"],"line":[0,772],"params":[1,[[0,{"name":[0,"value"],"description":[0,"\n要进行归一化的输入值。
"],"type":[0,"数字"]}],[0,{"name":[0,"start"],"description":[0,"\n数值当前范围的下界。
"],"type":[0,"数字"]}],[0,{"name":[0,"stop"],"description":[0,"\n数值当前范围的上界。
"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"归一化后的数值。"],"type":[0,"数字"]}],"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
\n计算指数表达式,例如 23。
\n\n例如,pow(2, 3)
计算表达式\n\n2 × 2 × 2。 pow(2, -3)
计算 1 ÷\n\n(2 × 2 × 2)。
指数表达式的底数。
"],"type":[0,"数字"]}],[0,{"name":[0,"e"],"description":[0,"\n用来对底数进行乘方的指数。
"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"n 的 e 次方。"],"type":[0,"数字"]}],"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
\n计算最接近一个数字的整数。
\n\n例如,round(133.8)
返回值为 134。
第二个参数 decimals
是可选的。它设置舍入时要使用的小数位数。例如,round(12.34, 1)
返回值为 12.3。默认情况下,decimals
为 0。
把数字四舍五入。
"],"type":[0,"数字"]}],[0,{"name":[0,"decimals"],"description":[0,"\n要四舍五入的小数位数,默认为 0。
"],"type":[0,"数字"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"四舍五入后的数字。"],"type":[0,"整数"]}],"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
\n计算一个数的平方。
\n\n对一个数求平方意味着将该数乘以自身。例如,sq(3)
计算的是 3 × 3,结果是 9。\nsq(-3)
计算的是 -3 × -3,结果也是 9。两个负数相乘会得到一个正数。\nsq()
返回的值始终为正数。
要进行平方运算的数。
"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"平方数。"],"type":[0,"数字"]}],"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
\n计算一个数字的平方根。
\n一个数字的平方根乘以它自身可以产生原来的数字。例如,sqrt(9)
返回 3,因为 3 × 3 = 9。sqrt()
总是返回一个正值。sqrt()
不能用于负数参数,比如 sqrt(-9)
。
做平方根运算的非负数。
\n"],"type":[0,"数字"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"该数字的平方根。"],"type":[0,"数字"]}],"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
\n返回一个随机数字或数组中的一个随机元素。
\nrandom()
遵循均匀分布,这意味着所有结果都同样可能发生。当 random()
用于生成数字时,输出范围内的所有数字都同样可能被返回。当 random()
用于从数组中选择元素时,所有元素都同样可能被选中。
默认情况下,random()
每次运行绘图时都会产生不同的结果。randomSeed()函数可以用来每次运行绘图时生成相同的数字序列或选择序列。
random() 返回一个从 0 开始到 1 但不包括 1 的随机数字。
\n带有一个参数的 random()
版本有两种运行方式。如果传入的参数是一个数字,那么 random()
会返回一个从 0 开始到但不包括该数字的随机数字。例如,调用 random(5)
返回 0 到 5 之间的值。如果传递的参数是一个数组,random()
返回该数组中的一个随机元素。例如,调用 random(['\\U0001F981', '\\U0001F42F', '\\U0001F43B'])
会返回一个狮子、老虎或熊的表情符号。
带有两个参数的 random()
版本会返回一个给定范围内的随机数字。传入的参数设置范围的下限和上限。例如,调用 random(-5, 10.2)
会返回从 -5 到但不包括 10.2 之间的值。
下限(包含边界值)。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"max"],"description":[0,"上限(不包含边界值)。
\n"],"type":[0,"数字"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"choices"],"description":[0,"待选择的数组。
\n"],"type":[0,"数组"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"随机数字。"],"type":[0,"数字"]}],"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\n function 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\n function 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\n function 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
\n返回符合高斯(正态)分布的随机数字。
\n正态分布绘制出来像钟形曲线。正态分布的值围绕一个称为均值的中心值聚集。聚集的标准差描述了它的扩散。
\n默认情况下,randomGaussian()
每次运行绘图时都会产生不同的结果。randomSeed() 函数可以用来每次运行绘图时生成相同的数字序列。
randomGaussian()
可能返回的值没有最小值或最大值。远离均值的值非常不可能,接近均值的值非常可能。
无参数版本的 randomGaussian()
返回的值具有 0 的均值和 1 的标准差。
带有一个参数的 randomGaussian()
版本将传递的参数解释为均值。标准差为 1。
带有两个参数的 randomGaussian()
版本将第一个传递的参数解释为均值,第二个为标准差。
均值。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"sd"],"description":[0,"标准差。
\n"],"type":[0,"数字"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"随机数字"],"type":[0,"数字"]}],"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
\n为 random() 和 randomGaussian() 函数设置种子值。
\n默认情况下,random() 和 randomGaussian() 每次运行绘图时都会产生不同的结果。使用常量参数调用 randomSeed()
,例如 randomSeed(99)
,会让这些函数每次运行绘图时产生相同的结果。
随机种子值
\n"],"type":[0,"数字"]}]]],"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
\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
\n当元素发生变化时调用一个函数。
\n调用myElement.changed(false)
会禁用该函数。
元素变化时调用的函数。false
会禁用该函数。
\nlet dropdown;\n\nfunction 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.\nfunction paintBackground() {\n let c = dropdown.value();\n background(c);\n}\n
\n\nlet checkbox;\n\nfunction 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.\nfunction repaint() {\n background(200);\n if (checkbox.checked() === true) {\n circle(50, 50, 30);\n }\n}\n
\n创建一个 <a></a>
元素,链接到另一个网页。
第一个参数,href
,是一个字符串,设置链接页面的 URL。
第二个参数,html
,是一个字符串,设置链接的内部 HTML。常见的做法是使用文本、图片或按钮作为链接。
第三个参数,target
,是可选的。它是一个字符串,告诉网页浏览器在哪里打开链接。默认情况下,链接在当前浏览器标签页中打开。传递'_blank'
将使链接在新的浏览器标签页中打开。MDN 描述了一些其他选项。
链接页面的 URL。
\n"],"type":[0,"字符串"]}],[0,{"name":[0,"html"],"description":[0,"链接元素显示的内部 HTML。
\n"],"type":[0,"字符串"]}],[0,{"name":[0,"target"],"description":[0,"新链接应该在哪个目标中打开,可以是 '_blank'
、'_self'
、'_parent'
或 '_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
\n创建一个用于简单音频播放的隐藏<audio>
元素。
createAudio()
返回一个新的p5.MediaElement对象。
第一个参数src
是音频的路径。如果传递了单个字符串,如'assets/video.mp4'
,则加载单个音频。字符串数组可用于以不同格式加载同一音频。例如,['assets/video.mp4', 'assets/video.ogv', 'assets/video.webm']
。这对于确保音频能够在不同的浏览器中播放很有用,因为不同的浏览器具有不同的功能。有关支持的格式的更多信息,请参见MDN。
第二个参数callback
是可选的。它是一旦音频准备好播放就会调用的函数。
音频文件的路径,或者为了支持不同浏览器的多个路径数组。
\n"],"type":[0,"字符串|字符串[]"],"optional":[0,true]}],[0,{"name":[0,"callback"],"description":[0,"一旦音频准备好播放即调用的函数。
\n"],"type":[0,"函数"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"新的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
\n创建一个 <button></button>
元素。
第一个参数,label
,是一个字符串,设置按钮上显示的标签。
第二个参数,value
,是可选的。它是一个字符串,设置按钮的值。更多详情请参见\nMDN。
按钮上显示的标签。
\n"],"type":[0,"字符串"]}],[0,{"name":[0,"value"],"description":[0,"按钮的值。
\n"],"type":[0,"字符串"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"新的 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
\n创建一个 <video>
元素,用于“捕获”来自\n网络摄像头和麦克风的音频/视频流。
createCapture()
返回一个新的\np5.MediaElement 对象。视频默认显示,\n可以通过调用 capture.hide()
来隐藏,并使用 image() 绘制到\n画布上。
第一个参数,type
,是可选的。它设置要使用的捕获类型。\n默认情况下,createCapture()
捕获音频和视频。 如果传入 VIDEO
,\n如 createCapture(VIDEO)
,则只捕获视频。\n如果传入 AUDIO
,如 createCapture(AUDIO)
,则只捕获\n音频。也可以传入一个约束对象来自定义流。\n查看 \nW3C 文档 了解可能的属性。不同的浏览器支持\n不同的属性。
'flipped' 属性是一个可选属性,可以设置为 {flipped:true}
\n来镜像视频输出。如果为 true,则意味着视频将被\n镜像或翻转,如果没有提及,则默认为 false
。
第二个参数,callback
,是可选的。它是一个准备好使用时调用的函数。回调函数应该有一个\n参数,stream
,是一个\nMediaStream 对象。
注意:createCapture()
只在本地运行草图或使用 HTTPS 时有效。了解更多\n这里\n和 这里。
捕获的类型,可以是 AUDIO 或 VIDEO,\n 或一个约束对象。默认情况下,视频和音频\n 流都被捕获。
\n"],"type":[0,"字符串|常数|对象"],"optional":[0,true]}],[0,{"name":[0,"flipped"],"description":[0,"翻转捕获的视频并镜像输出, {flipped:true}
。默认情况下为 false。
流加载完成后调用的函数。
\n"],"type":[0,"函数"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"新的 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
\n创建一个复选框<input></input>
元素。
复选框扩展了p5.Element类,增加了一个checked()
方法。调用myBox.checked()
如果复选框被选中则返回true
,否则返回false
。
第一个参数,label
,是可选的。它是一个字符串,用于设置显示在复选框旁边的标签。
第二个参数,value
,也是可选的。它是一个布尔值,用于设置复选框的值。
复选框后显示的标签。
\n"],"type":[0,"字符串"],"optional":[0,true]}],[0,{"name":[0,"value"],"description":[0,"复选框的值。选中为true
,未选中为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
\n创建一个颜色选择器元素。
\n参数value
是可选的。如果传递了颜色字符串或p5.Color对象,则会设置默认颜色。
颜色选择器扩展了p5.Element类,增加了一些管理颜色的有用方法:
\nmyPicker.value()
以十六进制字符串格式'#rrggbb'
返回当前颜色。myPicker.color()
以p5.Color对象形式返回当前颜色。默认颜色,为CSS颜色字符串。
\n"],"type":[0,"字符串|p5.Color"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"新的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
\n创建一个<div></div>
元素。
<div></div>
元素通常用作其他元素的容器。
参数html
是可选的。它接受一个字符串,该字符串设置了新<div></div>
的内部HTML。
新<div></div>
元素的内部HTML。
\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
\n创建一个新的p5.Element对象。
\n第一个参数tag
是一个HTML标签的字符串,例如'h5'
。
第二个参数content
是可选的。它是一个字符串,用于设置要插入新元素的HTML内容。新元素默认没有内容。
新元素的标签。
\n"],"type":[0,"字符串"]}],[0,{"name":[0,"content"],"description":[0,"要插入元素的HTML内容。
\n"],"type":[0,"字符串"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"新的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
\n创建一个类型为 'file'
的 <input></input>
元素。
createFileInput()
允许用户选择本地文件用于草图中。\n它返回一个 p5.File 对象。
第一个参数,callback
,是一个文件\n加载时调用的函数。回调函数应该有一个参数,file
, 是一个\np5.File 对象。
第二个参数,multiple
,是可选的。它是一个布尔值,\n如果设置为 true
,允许加载多个文件。如果 true
,callback
\n将被每个文件调用一次。
文件加载后调用的函数。
\n"],"type":[0,"函数"]}],[0,{"name":[0,"multiple"],"description":[0,"允许选择多个文件。
\n"],"type":[0,"布尔"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"新的 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
\n创建一个可以在画布外显示的 <img>
元素。
第一个参数,src
,是一个包含图像文件路径的字符串。src
应该是一个相对路径,如 '/assets/image.png'
,或一个 URL,如 'https://example.com/image.png'
。
第二个参数,alt
,是一个包含图像的 替代文本的字符串。对于不显示的图像,可以使用空字符串''
。
第三个参数,crossOrigin
,是可选的。它是一个字符串,设置图像的 crossOrigin 属性。使用 'anonymous'
或'use-credentials'
来获取具有跨域访问权限的图像。
第四个参数,callback
,也是可选的。它设置一个函数,在图像加载后调用。新图像作为一个 p5.Element 对象传递给回调函数。
图像的相对路径或 URL。
\n"],"type":[0,"字符串"]}],[0,{"name":[0,"alt"],"description":[0,"图像的替代文本。
\n"],"type":[0,"字符串"]}]]]}],[0,{"params":[1,[[0,{"name":[0,"src"],"description":[0,""],"type":[0,"字符串"]}],[0,{"name":[0,"alt"],"description":[0,""],"type":[0,"字符串"]}],[0,{"name":[0,"crossOrigin"],"description":[0,"获取图像时使用的 crossOrigin 属性。
\n"],"type":[0,"字符串"],"optional":[0,true]}],[0,{"name":[0,"successCallback"],"description":[0,"图像加载完成后调用的函数。新图像将作为一个 p5.Element 对象传递给函数。
\n"],"type":[0,"函数"],"optional":[0,true]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"新的 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
\n创建一个文本<input></input>
元素。
调用myInput.size()
来设置文本框的长度。
第一个参数value
是可选的。它是一个字符串,用于设置输入框的默认值。默认情况下,输入框为空。
第二个参数type
也是可选的。它是一个字符串,指定输入文本的类型。参见MDN以获取完整的选项列表。默认值为'text'
。
输入框的默认值。默认为空字符串''
。
输入类型。默认为'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
\n创建一个<p></p>
元素。
<p></p>
元素通常用于段落长度的文本。
参数html
是可选的。它接受一个字符串,该字符串设置了新<p></p>
的内部HTML。
新<p></p>
元素的内部HTML。
\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
\n创建一个单选按钮元素。
\n参数是可选的。如果传递了一个字符串,如\nlet myRadio = createSelect('food')
,那么每个单选选项将\n有 \"food\"
作为其 name
参数:<input name=\"food\"></input>
。\n如果传递了一个现有的 <div></div>
或 <span></span>
\n元素,如 let myRadio = createSelect(container)
, 它将\n成为单选按钮的父元素。
单选按钮扩展了 p5.Element 类,增加了一些\n有用的方法来管理选项:
\nmyRadio.option(value, [label])
向菜单添加一个选项。 第一个参数,value
,是一个字符串,设置选项的 值和标签。第二个参数,label
,是可选的。如果提供,它设置显示的标签为 value
。如果一个选项 的 value
已经存在,其标签将被更改��返回其值。myRadio.value()
返回当前选中选项的 值。myRadio.selected()
返回当前选中的 选项。myRadio.selected(value)
选择给定的选项并将 它作为一个 HTMLInputElement
返回。myRadio.disable(shouldDisable)
如果传递 true
则启用整个单选按钮,如果传递 false
则禁用它。容器 HTML 元素,可以是 <div></div>
\n或 <span></span>
。
分配给每个选项的 <input></input>
元素的 name 参数。
\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
\n创建一个下拉菜单<select></select>
元素。
参数是可选的。如果传递了true
,如let mySelect = createSelect(true)
,则下拉菜单将支持多选。如果传递了一个现有的<select></select>
元素,如let mySelect = createSelect(otherSelect)
,则现有元素将被包装在一个新的p5.Element对象中。
下拉菜单扩展了p5.Element类,增加了一些管理选项的有用方法:
\nmySelect.option(name, [value])
向菜单添加一个选项。第一个参数,name
,是一个字符串,设置选项的名称和值。第二个参数,value
,是可选的。如果提供了,它将设置对应于键name
的值。如果一个选项的name
已经存在,其值将被更改为value
。mySelect.value()
返回当前选中选项的值。mySelect.selected()
返回当前选中的选项。mySelect.selected(option)
默认选择给定的选项。mySelect.disable()
将整个下拉菜单元素标记为禁用。mySelect.disable(option)
将给定的选项标记为禁用。mySelect.enable()
将整个下拉菜单元素标记为启用。mySelect.enable(option)
将给定的选项标记为启用。支持多选。
\n"],"type":[0,"布尔"],"optional":[0,true]}]]]}],[0,{"params":[1,[[0,{"name":[0,"existing"],"description":[0,"要包装的现有select元素,可以是p5.Element或\n HTMLSelectElement。
\n"],"type":[0,"对象"]}]]]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"新的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
\n创建一个滑块<input></input>
元素。
范围滑块对于快速从给定范围选择数字很有用。
\n前两个参数,min
和max
,是设置滑块最小值和最大值的数字。
第三个参数,value
,是可选的。它是一个数字,设置滑块的默认值。
第四个参数,step
,也是可选的。它是一个数字,设置滑块范围内每个值的间隔。将step
设置为0允许滑块从min
平滑移动到max
。
滑块的最小值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"max"],"description":[0,"滑块的最大值。
\n"],"type":[0,"数字"]}],[0,{"name":[0,"value"],"description":[0,"滑块的默认值。
\n"],"type":[0,"数字"],"optional":[0,true]}],[0,{"name":[0,"step"],"description":[0,"滑块范围内每一步的大小。
\n"],"type":[0,"数字"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"新的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
\n创建一个<span></span>
元素。
<span></span>
元素通常用作内联元素的容器。例如,一个<span></span>
可以包含句子的一部分,这部分句子具有不同的样式。
参数html
是可选的。它接受一个字符串,该字符串设置了新<span></span>
的内部HTML。
新<span></span>
元素的内部HTML。
\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
\n创建一个用于简单音频/视频播放的 <video>
元素。
createVideo()
返回一个新的 p5.MediaElement 对象。默认情况下,视频是可见的。通过调用 video.hide()
可以将其隐藏,并使用 image() 绘制到画布上。
第一个参数 src
是视频的路径。如果传递了单个字符串,如 '/assets/topsecret.mp4'
,则加载单个视频。字符串数组可用于以不同格式加载同一视频。例如,['/assets/topsecret.mp4', '/assets/topsecret.ogv', '/assets/topsecret.webm']
。这对于确保视频能够在不同的浏览器中播放很有用,因为不同的浏览器具有不同的功能。有关支持的格式的更多信息,请参见MDN。
第二个参数 callback
是可选的。它是一旦视频准备好播放就会调用的函数。
视频文件的路径,或者为了支持不同浏览器的多个路径数组。
\n"],"type":[0,"字符串|字符串[]"]}],[0,{"name":[0,"callback"],"description":[0,"一旦视频准备好播放即调用的函数。
\n"],"type":[0,"函数"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"新的 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
\n当元素接收到输入时调用一个函数。
\n\nmyElement.input()
通常用于文本输入和滑块。调用\n\n myElement.input(false)
会禁用该函数。
在元素内检测到输入时调用的函数。false
会禁用该函数。
\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
\n移除由p5.js创建的所有元素,包括任何事件处理程序。
有两个例外:通过createCanvas()创建的画布元素和通过createGraphics()创建的p5.Render对象。
\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
\n在页面中搜索第一个与给定的CSS 选择器字符串匹配的元素。
\n选择器字符串可以是 ID、类、标签名或它们的组合。select()
如果找到匹配项,则返回一个p5.Element对象;如果没有找到,则返回null
。
第二个参数container
是可选的。它指定了一个要在其中搜索的容器。container
可以是 CSS 选择器字符串,一个p5.Element对象,或一个HTMLElement对象。
要搜索的元素的 CSS 选择器字符串。
\n"],"type":[0,"字符串"]}],[0,{"name":[0,"container"],"description":[0,"CSS 选择器字符串,p5.Element,或HTMLElement以在其内部搜索。
\n"],"type":[0,"字符串|p5.Element|HTMLElement"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"包含元素的p5.Element。"],"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
\n在页面中搜索所有与给定的CSS选择器字符串匹配的元素。
\n选择器字符串可以是ID、类、标签名或它们的组合。selectAll()
如果找到任何匹配项,则返回一个p5.Element对象的数组;如果没有找到,则返回一个空数组。
第二个参数container
是可选的。它指定了一个要在其中搜索的容器。container
可以是CSS选择器字符串、一个p5.Element对象,或一个HTMLElement对象。
要搜索的元素的CSS选择器字符串。
\n"],"type":[0,"字符串"]}],[0,{"name":[0,"container"],"description":[0,"CSS选择器字符串、p5.Element或HTMLElement,用于在其内部搜索。
\n"],"type":[0,"字符串|p5.Element|HTMLElement"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"包含找到的任何元素的p5.Element数组。"],"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
\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
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
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
\nA function that's called repeatedly while the sketch runs.
\nDeclaring the function draw()
sets a code block to run repeatedly\nonce the sketch starts. It’s used to create animations and respond to\nuser inputs:
function draw() {\n // Code to run repeatedly.\n}\n
\nThis is often called the \"draw loop\" because p5.js calls the code in\ndraw()
in a loop behind the scenes. By default, draw()
tries to run\n60 times per second. The actual rate depends on many factors. The\ndrawing rate, called the \"frame rate\", can be controlled by calling\nframeRate(). The number of times draw()
\nhas run is stored in the system variable\nframeCount().
Code placed within draw()
begins looping after\nsetup() runs. draw()
will run until the user\ncloses the sketch. draw()
can be stopped by calling the\nnoLoop() function. draw()
can be resumed by\ncalling the loop() function.
\nfunction setup() {\n createCanvas(100, 100);\n\n // Paint the background once.\n background(200);\n\n describe(\n 'A white circle on a gray background. The circle follows the mouse as the user moves, leaving a trail.'\n );\n}\n\nfunction draw() {\n // Draw circles repeatedly.\n circle(mouseX, mouseY, 40);\n}\n
\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.'\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\n// Double-click the canvas to change the circle's color.\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 circle changes color to pink 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// Change the fill color when the user double-clicks.\nfunction doubleClicked() {\n fill('deeppink');\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
\nA function that's called once when the sketch begins running.
\nDeclaring the function setup()
sets a code block to run once\nautomatically when the sketch starts running. It's used to perform\nsetup tasks such as creating the canvas and initializing variables:
function setup() {\n // Code to run once at the start of the sketch.\n}\n
\nCode placed in setup()
will run once before code placed in\ndraw() begins looping. If the\npreload() is declared, then setup()
will\nrun immediately after preload() finishes\nloading assets.
Note: setup()
doesn’t have to be declared, but it’s common practice to do so.
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw the circle.\n circle(50, 50, 40);\n\n describe('A white circle on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Paint the background once.\n background(200);\n\n describe(\n 'A white circle on a gray background. The circle follows the mouse as the user moves, leaving a trail.'\n );\n}\n\nfunction draw() {\n // Draw circles repeatedly.\n circle(mouseX, mouseY, 40);\n}\n
\n\nlet img;\n\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(\n 'A white circle on a brick wall. The circle follows the mouse as the user moves, leaving a trail.'\n );\n}\n\nfunction draw() {\n // Style the circle.\n noStroke();\n\n // Draw the circle.\n circle(mouseX, mouseY, 10);\n}\n
\n一个 String
常量,用于设置 angleMode()。
rotate() 和 sin() 等函数默认以弧度为单位测量。 调用 angleMode(DEGREES)
可以确保以角度为单位测量。
注意:TWO_PI
弧度等于 360˚。
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw a red arc from 0 to HALF_PI radians.\n fill(255, 0, 0);\n arc(50, 50, 80, 80, 0, HALF_PI);\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Draw a blue arc from 90˚ to 180˚.\n fill(0, 0, 255);\n arc(50, 50, 80, 80, 90, 180);\n\n describe('The bottom half of a circle drawn on a gray background. The bottom-right quarter is red. The bottom-left quarter is blue.');\n}\n
\n一个Number
常量,约为 1.5708。
HALF_PI
是数学常数 π 的一半。它在许多涉及旋转和振荡的任务中非常有用。例如,调用 rotate(HALF_PI)
会将坐标系旋转 HALF_PI
弧度,即一个四分之一的转向(90˚)。
注意:TWO_PI
弧度等于 360˚,PI
弧度等于 180˚,HALF_PI
弧度等于 90˚,QUARTER_PI
弧度等于 45˚。
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw an arc from 0 to HALF_PI.\n arc(50, 50, 80, 80, 0, HALF_PI);\n\n describe('The bottom-right quarter of a circle drawn in white on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw a line.\n line(0, 0, 40, 0);\n\n // Rotate a quarter turn.\n rotate(HALF_PI);\n\n // Draw the same line, rotated.\n line(0, 0, 40, 0);\n\n describe('Two black lines on a gray background. One line extends from the center to the right. The other line extends from the center to the bottom.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A red circle and a blue circle oscillate from left to right on a gray background. The red circle appears to chase the blue circle.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Calculate the x-coordinates.\n let x1 = 40 * sin(frameCount * 0.05);\n let x2 = 40 * sin(frameCount * 0.05 + HALF_PI);\n\n // Style the oscillators.\n noStroke();\n\n // Draw the red oscillator.\n fill(255, 0, 0);\n circle(x1, 0, 20);\n\n // Draw the blue oscillator.\n fill(0, 0, 255);\n circle(x2, 0, 20);\n}\n
\n一个 Number
常量,约为 3.1416。
PI
是数学常数 π。它在许多涉及旋转和振荡的任务中非常有用。例如,调用 rotate(PI)
会将坐标系旋转 PI
弧度,即一个半转向(180˚)。
注意:TWO_PI
弧度等于 360˚,PI
弧度等于 180˚,HALF_PI
弧度等于 90˚,QUARTER_PI
弧度等于 45˚。
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw an arc from 0 to PI.\n arc(50, 50, 80, 80, 0, PI);\n\n describe('The bottom half of a circle drawn in white on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw a line.\n line(0, 0, 40, 0);\n\n // Rotate a half turn.\n rotate(PI);\n\n // Draw the same line, rotated.\n line(0, 0, 40, 0);\n\n describe('A horizontal black line on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A red circle and a blue circle oscillate from left to right on a gray background. The circles drift apart, then meet in the middle, over and over again.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Calculate the x-coordinates.\n let x1 = 40 * sin(frameCount * 0.05);\n let x2 = 40 * sin(frameCount * 0.05 + PI);\n\n // Style the oscillators.\n noStroke();\n\n // Draw the red oscillator.\n fill(255, 0, 0);\n circle(x1, 0, 20);\n\n // Draw the blue oscillator.\n fill(0, 0, 255);\n circle(x2, 0, 20);\n}\n
\n一个 Number
常量,约为 0.7854。
QUARTER_PI
是数学常数 π 的四分之一。它在许多涉及旋转和振荡的任务中非常有用。例如,调用 rotate(QUARTER_PI)
会将坐标系旋转 QUARTER_PI
弧度,即一个八分之一的转向(45˚)。
注意:TWO_PI
弧度等于 360˚,PI
弧度等于 180˚,HALF_PI
弧度等于 90˚,QUARTER_PI
弧度等于 45˚。
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw an arc from 0 to QUARTER_PI.\n arc(50, 50, 80, 80, 0, QUARTER_PI);\n\n describe('A one-eighth slice of a circle drawn in white on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw a line.\n line(0, 0, 40, 0);\n\n // Rotate an eighth turn.\n rotate(QUARTER_PI);\n\n // Draw the same line, rotated.\n line(0, 0, 40, 0);\n\n describe('Two black lines that form a \"V\" opening towards the bottom-right corner of a gray square.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A red circle and a blue circle oscillate from left to right on a gray background. The red circle appears to chase the blue circle.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Calculate the x-coordinates.\n let x1 = 40 * sin(frameCount * 0.05);\n let x2 = 40 * sin(frameCount * 0.05 + QUARTER_PI);\n\n // Style the oscillators.\n noStroke();\n\n // Draw the red oscillator.\n fill(255, 0, 0);\n circle(x1, 0, 20);\n\n // Draw the blue oscillator.\n fill(0, 0, 255);\n circle(x2, 0, 20);\n}\n
\n一个 String
常量,用于设置 angleMode()。
rotate() 和 sin() 等函数默认以弧度为单位测量。 调用 angleMode(RADIANS)
可以确保以弧度为单位测量。在 angleMode() 已设置为 DEGREES 的情况下,这样做可以很有用。
注意:TWO_PI
弧度等于 360˚。\n"],"line":[0,587],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Use degrees.\n angleMode(DEGREES);\n\n // Draw a red arc from 0˚ to 90˚.\n fill(255, 0, 0);\n arc(50, 50, 80, 80, 0, 90);\n\n // Use radians.\n angleMode(RADIANS);\n\n // Draw a blue arc from HALF_PI to PI.\n fill(0, 0, 255);\n arc(50, 50, 80, 80, HALF_PI, PI);\n\n describe('The bottom half of a circle drawn on a gray background. The bottom-right quarter is red. The bottom-left quarter is blue.');\n}\n
\n一个 Number
常量,约为 6.2382。
TAU
是数学常数 π 的两倍。它在许多涉及旋转和振荡的任务中非常有用。例如,调用 rotate(TAU)
会将坐标系旋转 TAU
弧度,即一个完整的转向(360˚)。TAU
和 TWO_PI
相等。
注意:TAU
弧度等于 360˚,PI
弧度等于 180˚,HALF_PI
弧度等于 90˚,QUARTER_PI
弧度等于 45˚。
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw an arc from 0 to TAU.\n arc(50, 50, 80, 80, 0, TAU);\n\n describe('A white circle drawn on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw a line.\n line(0, 0, 40, 0);\n\n // Rotate a full turn.\n rotate(TAU);\n\n // Style the second line.\n strokeWeight(5);\n\n // Draw the same line, shorter and rotated.\n line(0, 0, 20, 0);\n\n describe(\n 'Two horizontal black lines on a gray background. A thick line extends from the center toward the right. A thin line extends from the end of the thick line.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A red circle with a blue center oscillates from left to right on a gray background.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Calculate the x-coordinates.\n let x1 = 40 * sin(frameCount * 0.05);\n let x2 = 40 * sin(frameCount * 0.05 + TAU);\n\n // Style the oscillators.\n noStroke();\n\n // Draw the red oscillator.\n fill(255, 0, 0);\n circle(x1, 0, 20);\n\n // Draw the blue oscillator, smaller.\n fill(0, 0, 255);\n circle(x2, 0, 10);\n}\n
\n一个 Number
常量,约为 6.2382。
TWO_PI
是数学常数 π 的两倍。它在许多涉及旋转和振荡的任务中非常有用。例如,调用 rotate(TWO_PI)
会将坐标系旋转 TWO_PI
弧度,即一个完整的转向(360˚)。TWO_PI
和 TAU
相等。
注意:TWO_PI
弧度等于 360˚,PI
弧度等于 180˚,HALF_PI
弧度等于 90˚,QUARTER_PI
弧度等于 45˚。
\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw an arc from 0 to TWO_PI.\n arc(50, 50, 80, 80, 0, TWO_PI);\n\n describe('A white circle drawn on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Draw a line.\n line(0, 0, 40, 0);\n\n // Rotate a full turn.\n rotate(TWO_PI);\n\n // Style the second line.\n strokeWeight(5);\n\n // Draw the same line, shorter and rotated.\n line(0, 0, 20, 0);\n\n describe(\n 'Two horizontal black lines on a gray background. A thick line extends from the center toward the right. A thin line extends from the end of the thick line.'\n );\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A red circle with a blue center oscillates from left to right on a gray background.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Translate the origin to the center.\n translate(50, 50);\n\n // Calculate the x-coordinates.\n let x1 = 40 * sin(frameCount * 0.05);\n let x2 = 40 * sin(frameCount * 0.05 + TWO_PI);\n\n // Style the oscillators.\n noStroke();\n\n // Draw the red oscillator.\n fill(255, 0, 0);\n circle(x1, 0, 20);\n\n // Draw the blue oscillator, smaller.\n fill(0, 0, 255);\n circle(x2, 0, 10);\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