\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
\n计算一个数字的反余弦值。
\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
\n每当屏幕触摸结束时调用的函数。
\n声明函数 touchEnded()
会设置一个代码块,在用户停止触摸触屏设备时自动运行:
\nfunction touchEnded() {\n // Code to run.\n}\n
\n\n当 p5.js 调用 touchEnded()
时,touches 数组将被更新为最新的触摸点:
\nfunction touchEnded() {\n // Paint over the background.\n background(200);\n\n // Mark each remaining touch point when the user stops\n // a touch.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n
\n参数 event 是可选的。touchEnded()
将被传递一个 TouchEvent 对象,该对象具有描述触摸事件的属性:
\nfunction touchEnded(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n\n在屏幕设备上,如果未声明 touchEnded()
,当用户的触摸结束时,mouseReleased() 将运行。如果声明了 touchEnded()
,那么当用户的触摸结束时将运行 touchEnded()
,而 mouseReleased() 不会运行。
注意:touchStarted()、touchEnded()
和 touchMoved() 是相关的。当用户触摸屏幕设备时,touchStarted() 会立即运行。当用户结束触摸时,touchEnded()
会立即运行。当用户移动任何触摸点时,touchMoved() 会重复运行。
可选的 TouchEvent 回调参数。
\n"],"type":[0,"TouchEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square switches color between black and white each time the user stops touching the screen.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle colors when a touch ends.\nfunction touchEnded() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nlet bgColor = 50;\nlet fillColor = 255;\nlet borderWidth = 0.5;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with the number 0 at the top-center. The number tracks the number of places the user is touching the screen. Circles appear at each touch point and change style in response to events.'\n );\n}\n\nfunction draw() {\n background(bgColor);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n fill(0);\n noStroke();\n\n // Display the number of touch points.\n text(touches.length, 50, 20);\n\n // Style the touch points.\n fill(fillColor);\n stroke(0);\n strokeWeight(borderWidth);\n\n // Display the touch points as circles.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n\n// Set the background color to a random grayscale value.\nfunction touchStarted() {\n bgColor = random(80, 255);\n}\n\n// Set the fill color to a random grayscale value.\nfunction touchEnded() {\n fillColor = random(0, 255);\n}\n\n// Set the stroke weight.\nfunction touchMoved() {\n // Increment the border width.\n borderWidth += 0.1;\n\n // Reset the border width once it's too thick.\n if (borderWidth > 20) {\n borderWidth = 0.5;\n }\n}\n
\n当用户触摸屏幕并移动时调用的函数。
\n\n声明函数 touchMoved()
会设置一个代码块,当用户触摸屏幕并移动时调用的函数。
\nfunction touchMoved() {\n // Code to run.\n}\n
\n\n当 p5.js 调用 touchMoved()
时,touches 数组将被更新为最新的触摸点:
\nfunction touchMoved() {\n // Paint over the background.\n background(200);\n\n // Mark each touch point while the user moves.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n
\n参数 event 是可选的。touchStarted()
会被传递为一个描述触摸事件属性的 TouchEvent 对象:
\nfunction touchMoved(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n在屏幕设备上,如果未声明 touchMoved()
,当用户的触摸点移动时,mouseDragged() 将运行。如果声明了 touchMoved()
,那么当用户的触摸点移动时,将运行 touchMoved()
,而 mouseDragged() 不会运行。
注意:touchStarted()、touchEnded() 和 touchMoved()
是相关的。当用户触摸触屏设备时,touchStarted() 会立即运行。当用户结束触摸时,touchEnded() 会立即运行。当用户移动任何触摸点时,touchMoved()
会重复运行。
可选的 TouchEvent 回调参数。
\n"],"type":[0,"TouchEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square becomes lighter when the user touches the screen and moves.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\nfunction touchMoved() {\n // Update the grayscale value.\n value += 5;\n\n // Reset the grayscale value.\n if (value > 255) {\n value = 0;\n }\n}\n
\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nlet bgColor = 50;\nlet fillColor = 255;\nlet borderWidth = 0.5;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with the number 0 at the top-center. The number tracks the number of places the user is touching the screen. Circles appear at each touch point and change style in response to events.'\n );\n}\n\nfunction draw() {\n background(bgColor);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n fill(0);\n noStroke();\n\n // Display the number of touch points.\n text(touches.length, 50, 20);\n\n // Style the touch points.\n fill(fillColor);\n stroke(0);\n strokeWeight(borderWidth);\n\n // Display the touch points as circles.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n\n// Set the background color to a random grayscale value.\nfunction touchStarted() {\n bgColor = random(80, 255);\n}\n\n// Set the fill color to a random grayscale value.\nfunction touchEnded() {\n fillColor = random(0, 255);\n}\n\n// Set the stroke weight.\nfunction touchMoved() {\n // Increment the border width.\n borderWidth += 0.1;\n\n // Reset the border width once it's too thick.\n if (borderWidth > 20) {\n borderWidth = 0.5;\n }\n}\n
\n每当用户触摸屏幕时调用的函数。
\n每当用户开始触摸触屏设备时,声明一个名为 touchStarted()
的函数会设置一个代码块,自动运行:
\nfunction touchStarted() {\n // Code to run.\n}\n
\n\n当 p5.js 调用 touchStarted()
时,touches 数组将被更新为最新的触摸点:
\nfunction touchStarted() {\n // Paint over the background.\n background(200);\n\n // Mark each touch point once with a circle.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n
\n参数 event 是可选的。touchStarted()
会被传递为一个描述触摸事件属性的 TouchEvent 对象:
\nfunction touchStarted(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n\n在触屏设备上,如果未声明 touchStarted()
,当用户触摸开始时,mousePressed() 会运行。如果声明了 touchStarted()
,那么当用户触摸开始时将运行 touchStarted()
,而 mousePressed() 不会运行。
注意:touchStarted()
、touchEnded() 和 touchMoved() 都是相关的。touchStarted()
会在用户触摸触屏设备时立即运行。 touchEnded() 会在用户结束触摸时立即运行。touchMoved() 会在用户移动任何触摸点时重复运行。
可选的 TouchEvent 回调参数。
\n"],"type":[0,"TouchEvent"],"optional":[0,true]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"example":[1,[[0,"\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square switches color between black and white each time the user touches the screen.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle colors with each touch.\nfunction touchStarted() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n
\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nlet bgColor = 50;\nlet fillColor = 255;\nlet borderWidth = 0.5;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with the number 0 at the top-center. The number tracks the number of places the user is touching the screen. Circles appear at each touch point and change style in response to events.'\n );\n}\n\nfunction draw() {\n background(bgColor);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n fill(0);\n noStroke();\n\n // Display the number of touch points.\n text(touches.length, 50, 20);\n\n // Style the touch points.\n fill(fillColor);\n stroke(0);\n strokeWeight(borderWidth);\n\n // Display the touch points as circles.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n\n// Set the background color to a random grayscale value.\nfunction touchStarted() {\n bgColor = random(80, 255);\n}\n\n// Set the fill color to a random grayscale value.\nfunction touchEnded() {\n fillColor = random(0, 255);\n}\n\n// Set the stroke weight.\nfunction touchMoved() {\n // Increment the border width.\n borderWidth += 0.1;\n\n // Reset the border width once it's too thick.\n if (borderWidth > 20) {\n borderWidth = 0.5;\n }\n}\n
\n包含一个触摸屏设备上所有当前触摸点的一个数组 Array
。
touches
数组默认为空。当用户触摸屏幕时,一个新的触摸点会被追踪并添加到这个数组中。触摸点是带有以下属性的对象 Objects
:
\n// Iterate over the touches array.\nfor (let touch of touches) {\n // x-coordinate relative to the top-left\n // corner of the canvas.\n console.log(touch.x);\n\n // y-coordinate relative to the top-left\n // corner of the canvas.\n console.log(touch.y);
\n // x-coordinate relative to the top-left\n // corner of the browser.\n console.log(touch.winX);
\n // y-coordinate relative to the top-left\n // corner of the browser.\n console.log(touch.winY);
\n // ID number\n console.log(touch.id);\n}\n
\n"],"line":[0,10],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. White circles appear where the user touches the square.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw a circle at each touch point.\n for (let touch of touches) {\n circle(touch.x, touch.y, 40);\n }\n}\n
\n\n// On a touchscreen device, touch the canvas using one or more fingers\n// at the same time.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. Labels appear where the user touches the square, displaying the coordinates.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw a label above each touch point.\n for (let touch of touches) {\n text(`${touch.x}, ${touch.y}`, touch.x, touch.y - 40);\n }\n}\n
\n一个 String
字符串类型的系统变量,包含最后一次键入的键的值。
key 变量对于检查是否键入了一个 ASCII 键非常有用。例如,表达式 key === \"a\"
如果键入了 a
键则评估为 true
,如果没有则为 false
。对于特殊键如 LEFT_ARROW
和 ENTER
,key
不会更新。对于特殊键,请使用 keyCode。应使用 keyIsDown() 函数检查多个不同的按键同时按下的状态。
\n// Click on the canvas to begin detecting key presses.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. The last key pressed is displayed at the center.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the last key pressed.\n text(key, 50, 50);\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nlet x = 50;\nlet y = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe(\n 'A gray square with a black circle at its center. The circle moves when the user presses the keys \"w\", \"a\", \"s\", or \"d\". It leaves a trail as it moves.'\n );\n}\n\nfunction draw() {\n // Update x and y if a key is pressed.\n if (keyIsPressed === true) {\n if (key === 'w') {\n y -= 1;\n } else if (key === 's') {\n y += 1;\n } else if (key === 'a') {\n x -= 1;\n } else if (key === 'd') {\n x += 1;\n }\n }\n\n // Style the circle.\n fill(0);\n\n // Draw the circle at (x, y).\n circle(x, y, 5);\n}\n
\n一个 Number
数字类型的系统变量,包含最后输入键的代码。
所有键都有一个 keyCode
。例如,a
键的 keyCode
为 65。\nkeyCode
变量对于检查是否输入了特殊键非常有用。例如,以下条件检查是否输入了回车键:
\nif (keyCode === 13) {\n // Code to run if the enter key was pressed.\n}\n
\n相同的代码可以使用系统变量 ENTER
更清晰地写出,其值为 13:
\nif (keyCode === ENTER) {\n // Code to run if the enter key was pressed.\n}\n
\n系统变量 BACKSPACE
、DELETE
、ENTER
、RETURN
、TAB
、\nESCAPE
、SHIFT
、CONTROL
、OPTION
、ALT
、UP_ARROW
、 DOWN_ARROW
、\nLEFT_ARROW
和 RIGHT_ARROW
都是特殊键的键码的有用简写。键码可以在如\nkeycode.info 等网站上找到。
\n// Click on the canvas to begin detecting key presses.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. The last key pressed and its code are displayed at the center.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the last key pressed and its code.\n text(`${key} : ${keyCode}`, 50, 50);\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nlet x = 50;\nlet y = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe(\n 'A gray square with a black circle at its center. The circle moves when the user presses an arrow key. It leaves a trail as it moves.'\n );\n}\n\nfunction draw() {\n // Update x and y if an arrow key is pressed.\n if (keyIsPressed === true) {\n if (keyCode === UP_ARROW) {\n y -= 1;\n } else if (keyCode === DOWN_ARROW) {\n y += 1;\n } else if (keyCode === LEFT_ARROW) {\n x -= 1;\n } else if (keyCode === RIGHT_ARROW) {\n x += 1;\n }\n }\n\n // Style the circle.\n fill(0);\n\n // Draw the circle at (x, y).\n circle(x, y, 5);\n}\n
\n如果正在检查的键被按下,则返回 true
,否则返回 false
。
keyIsDown()
在检查多个不同键按下时很有帮助。例如,keyIsDown()
可用于检查是否同时按下了 LEFT_ARROW
和 UP_ARROW
:
if (keyIsDown(LEFT_ARROW) && keyIsDown(UP_ARROW)) {\n // Move diagonally.\n}
\nkeyIsDown()
可以使用 keyCode 值检查按键,如 keyIsDown(37)
或 keyIsDown(LEFT_ARROW)
。键码可以在如 keycode.info 等网站上找到。
key to check.
\n"],"type":[0,"Number"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"whether the key is down or not."],"type":[0,"Boolean"]}],"example":[1,[[0,"\n\n// Click on the canvas to begin detecting key presses.\n\nlet x = 50;\nlet y = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe(\n 'A gray square with a black circle at its center. The circle moves when the user presses an arrow key. It leaves a trail as it moves.'\n );\n}\n\nfunction draw() {\n // Update x and y if an arrow key is pressed.\n if (keyIsDown(LEFT_ARROW) === true) {\n x -= 1;\n }\n\n if (keyIsDown(RIGHT_ARROW) === true) {\n x += 1;\n }\n\n if (keyIsDown(UP_ARROW) === true) {\n y -= 1;\n }\n\n if (keyIsDown(DOWN_ARROW) === true) {\n y += 1;\n }\n\n // Style the circle.\n fill(0);\n\n // Draw the circle.\n circle(x, y, 5);\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nlet x = 50;\nlet y = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n describe(\n 'A gray square with a black circle at its center. The circle moves when the user presses an arrow key. It leaves a trail as it moves.'\n );\n}\n\nfunction draw() {\n // Update x and y if an arrow key is pressed.\n if (keyIsDown(37) === true) {\n x -= 1;\n }\n\n if (keyIsDown(39) === true) {\n x += 1;\n }\n\n if (keyIsDown(38) === true) {\n y -= 1;\n }\n\n if (keyIsDown(40) === true) {\n y += 1;\n }\n\n // Style the circle.\n fill(0);\n\n // Draw the circle.\n circle(x, y, 5);\n}\n
\n一个 Boolean
布尔值类型的系统变量,如果当前有任何键被按下则为 true
,否则为 false
。
\n// Click on the canvas to begin detecting key presses.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a white square at its center. The white square turns black when the user presses a key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n if (keyIsPressed === true) {\n fill(0);\n } else {\n fill(255);\n }\n\n // Draw the square.\n square(25, 25, 50);\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with the word \"false\" at its center. The word switches to \"true\" when the user presses a key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the value of keyIsPressed.\n text(keyIsPressed, 50, 50);\n}\n
\n当任何键被按下时调用一次的函数。
\n声明函数 keyPressed()
会设置一个代码块,当用户按下任何键时自动运行一次:
\nfunction keyPressed() {\n // Code to run.\n}\n
\n当 keyPressed()
被 p5.js 调用时,key 和 keyCode 变量会更新为最近输入的值:
\nfunction keyPressed() {\n if (key === 'c') {\n // Code to run.\n }\n\n if (keyCode === ENTER) {\n // Code to run.\n }\n}\n
\n参数 event
是可选的。keyPressed()
总是传递一个 KeyboardEvent 对象,该对象带有描述按键事件的属性:
\nfunction keyPressed(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n浏览器可能会将默认行为附加到各种键事件上。例如,一些浏览器在按下 SPACE
键时可能会跳转到网页底部。要防止此事件的任何默认行为,在函数末尾添加 return false;
。
optional KeyboardEvent
callback argument.
\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square changes color when the user presses a key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle the background color when the user presses a key.\nfunction keyPressed() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a white square at its center. The inner square turns black when the user presses the \"b\" key. It turns white when the user presses the \"a\" key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Reassign value when the user presses the 'a' or 'b' key.\nfunction keyPressed() {\n if (key === 'a') {\n value = 255;\n } else if (key === 'b') {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square turns white when the user presses the left arrow key. It turns black when the user presses the right arrow key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle the background color when the user presses an arrow key.\nfunction keyPressed() {\n if (keyCode === LEFT_ARROW) {\n value = 255;\n } else if (keyCode === RIGHT_ARROW) {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n当任何键被释放时调用一次的函数。
\n声明函数keyReleased()
会设置一个代码块,当用户释放任何键时,自动运行一次:
\nfunction keyReleased() {\n // Code to run.\n}\n
\n当 p5.js 调用keyReleased()
时,key和keyCode变量将会更新为最近一次释放的值:
\nfunction keyReleased() {\n if (key === 'c') {\n // Code to run.\n }\n\n if (keyCode === ENTER) {\n // Code to run.\n }\n}\n
\n参数event
是可选的。keyReleased()
总是传递一个KeyboardEvent对象,该对象带有描述按键事件的属性:
\nfunction keyReleased(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n浏览器可能会对各种键盘事件附加默认行为。为了阻止这个事件的任何默认行为,在函数的末尾添加return false;
。
optional KeyboardEvent
callback argument.
\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square changes color when the user releases a key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle value when the user releases a key.\nfunction keyReleased() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square becomes white when the user releases the \"w\" key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Set value to 255 the user releases the 'w' key.\nfunction keyReleased() {\n if (key === 'w') {\n value = 255;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square turns white when the user presses and releases the left arrow key. It turns black when the user presses and releases the right arrow key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle the background color when the user releases an arrow key.\nfunction keyReleased() {\n if (keyCode === LEFT_ARROW) {\n value = 255;\n } else if (keyCode === RIGHT_ARROW) {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n当按下具有可打印字符的键时调用一次的函数。
\n声明函数 keyTyped()
将设置一个代码块,当用户按下任何具有可打印字符的键时自动运行一次,如 a
或 1。修饰键如 SHIFT
、CONTROL
和箭头键将被忽略:
\nfunction keyTyped() {\n // Code to run.\n}\n
\n当 keyTyped()
由 p5.js 调用时,变量 key 和 keyCode 将更新为最近释放的值:
\nfunction keyTyped() {\n // Check for the \"c\" character using key.\n if (key === 'c') {\n // Code to run.\n }\n\n // Check for \"c\" using keyCode.\n if (keyCode === 67) {\n // Code to run.\n }\n}\n
\n参数 event
是可选的。keyTyped()
总是传递一个带有描述按键事件属性的 KeyboardEvent 对象:
\nfunction keyReleased(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n注意:使用 keyPressed() 函数和 keyCode 系统变量来响应 ALT
等修饰键。
浏览器可能会将默认行为附加到各种键事件上。为了防止此事件的任何默认行为,在函数的结尾添加 return false;
。
optional KeyboardEvent
callback argument.
\n// Click on the canvas to begin detecting key presses.\n// Note: Pressing special keys such as SPACE have no effect.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a white square at its center. The inner square changes color when the user presses a key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle the square's color when the user types a printable key.\nfunction keyTyped() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a white square at its center. The inner square turns black when the user types the \"b\" key. It turns white when the user types the \"a\" key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Reassign value when the user types the 'a' or 'b' key.\nfunction keyTyped() {\n if (key === 'a') {\n value = 255;\n } else if (key === 'b') {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n当鼠标按钮快速双击时调用一次的函数。
\n声明函数 doubleClicked()
会设置一个代码块,当用户快速按下并释放鼠标按钮两次时自动运行:
\nfunction doubleClicked() {\n // Code to run.\n}\n
\n鼠标系统变量,如 mouseX 和 mouseY,在调用 doubleClicked()
时会更新为它们最新的值:
\nfunction doubleClicked() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\n参数 event
是可选的。doubleClicked()
总是传递一个 MouseEvent 对象,该对象带有描述双击事件的属性:
\nfunction doubleClicked(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n在触摸屏设备上,放置在 doubleClicked()
中的代码将在短时间内发生两次触摸后运行。
浏览器可能会将默认行为附加到各种鼠标事件上。例如,一些浏览器在用户按下鼠标按钮同时移动鼠标时会高亮显示文本。为了防止此事件的任何默认行为,在函数的末尾添加 return false;
。
optional MouseEvent
argument.
\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square changes color when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle the square's color when the user double-clicks.\nfunction doubleClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black circle at its center. When the user double-clicks on the circle, it changes color to white.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the circle.\n fill(value);\n\n // Draw the circle.\n circle(50, 50, 80);\n}\n\n// Reassign value to 255 when the user double-clicks on the circle.\nfunction doubleClicked() {\n if (dist(50, 50, mouseX, mouseY) < 40) {\n value = 255;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n退出由 requestPointerLock 开始的指针锁定。
\n调用 requestPointerLock()
会锁定 mouseX、mouseY、pmouseX 和 pmouseY 的值。调用 exitPointerLock()
会恢复更新鼠标系统变量。
注意:大多数浏览器在调用 requestPointerLock()
需要一个输入操作,比如点击。建议在事件函数中调用 requestPointerLock()
,例如 doubleClicked()。
\nlet isLocked = false;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a word at its center. The word changes between \"Unlocked\" and \"Locked\" when the user double-clicks.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Tell the user whether the pointer is locked.\n if (isLocked === true) {\n text('Locked', 50, 50);\n } else {\n text('Unlocked', 50, 50);\n }\n}\n\n// Toggle the pointer lock when the user double-clicks.\nfunction doubleClicked() {\n if (isLocked === true) {\n exitPointerLock();\n isLocked = false;\n } else {\n requestPointerLock();\n isLocked = true;\n }\n}\n
\n一个字符串系统变量,包含最后一次按下的鼠标按钮的值。
\nmouseButton
变量可能是 LEFT
、RIGHT
或 CENTER
,取决于最后按下的是哪个按钮。
注意:不同的浏览器可能会以不同的方式跟踪 mouseButton
。更多信息请参见 MDN。
\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with black text at its center. The text changes from 0 to either \"left\" or \"right\" when the user clicks a mouse button.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the mouse button.\n text(mouseButton, 50, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n \"A gray square. Different shapes appear at its center depending on the mouse button that's clicked.\"\n );\n}\n\nfunction draw() {\n background(200);\n\n if (mouseIsPressed === true) {\n if (mouseButton === LEFT) {\n circle(50, 50, 50);\n }\n if (mouseButton === RIGHT) {\n square(25, 25, 50);\n }\n if (mouseButton === CENTER) {\n triangle(23, 75, 50, 20, 78, 75);\n }\n }\n}\n
\n在鼠标按钮被按下并释放后调用一次的函数。
\n声明函数 mouseClicked()
会设置一个代码块,当用户在按下鼠标按钮后释放时自动运行:
\nfunction mouseClicked() {\n // Code to run.\n}\n
\n\n鼠标系统变量,如 mouseX 和\nmouseY,将在 p5.js 调用 mouseClicked()
时更新为它们最新的值:
\nfunction mouseClicked() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\n参数 event
是可选的。mouseClicked()
总是会传递一个\nMouseEvent\n对象,其属性描述了鼠标点击事件:
\nfunction mouseClicked(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n\n在触摸屏设备上,如果没有声明 touchEnded(),mouseClicked()
会在用户触摸结束时运行。如果声明了\ntouchEnded(),那么当用户触摸结束时 touchEnded() 会运行,并且 mouseClicked()
不会运行。
浏览器可能会对各种鼠标事件附加默认行为。例如,一些浏览器在用户按下鼠标按钮时移动鼠标会高亮显示文本。为了防止此事件的任何默认行为,可以在函数的末尾添加 return false;
。
注意:mousePressed()、\nmouseReleased(),\n和 mouseClicked()
都是相关联的。mousePressed() 会在用户点击鼠标时立即运行。mouseReleased() 会在用户释放鼠标点击时立即运行。mouseClicked()
会在 mouseReleased() 之后立即运行。
optional MouseEvent
argument.
\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square changes color when the user presses and releases a mouse button.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\n// Toggle the square's color when the user clicks.\nfunction mouseClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Style the circle.\n fill('orange');\n stroke('royalblue');\n strokeWeight(10);\n\n describe(\n 'An orange circle with a thick, blue border drawn on a gray background. When the user presses and holds the mouse, the border becomes thin and pink. When the user releases the mouse, the border becomes thicker and changes color to blue.'\n );\n}\n\nfunction draw() {\n background(220);\n\n // Draw the circle.\n circle(50, 50, 20);\n}\n\n// Set the stroke color and weight as soon as the user clicks.\nfunction mousePressed() {\n stroke('deeppink');\n strokeWeight(3);\n}\n\n// Set the stroke and fill colors as soon as the user releases\n// the mouse.\nfunction mouseReleased() {\n stroke('royalblue');\n\n // This is never visible because fill() is called\n // in mouseClicked() which runs immediately after\n // mouseReleased();\n fill('limegreen');\n}\n\n// Set the fill color and stroke weight after\n// mousePressed() and mouseReleased() are called.\nfunction mouseClicked() {\n fill('orange');\n strokeWeight(10);\n}\n
\n当按下按钮且拖动鼠标时调用的函数。
\n声明函数 mouseDragged()
会设置一个代码块,当用户点击并拖动鼠标时自动运行:
\nfunction mouseDragged() {\n // Code to run.\n}\n
\n鼠标系统变量,如 mouseX 和 mouseY,将在调用 mouseDragged()
时用它们最新的值更新:
\nfunction mouseDragged() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\n参数 event
是可选的。mouseDragged()
总是会传递一个 MouseEvent 对象,其中包含描述鼠标拖动事件的属性:
\nfunction mouseDragged(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n在触摸屏设备上,如果没有声明 touchMoved(),则当用户移动触摸点时会运行 mouseDragged()
。如果声明了 touchMoved(),则当用户移动触摸点时会运行 touchMoved(),而 mouseDragged()
不会运行。
浏览器可能会将默认行为附加到各种鼠标事件上。例如,一些浏览器在用户按下鼠标按钮同时移动鼠标时会高亮显示文本。为了防止此事件的任何默认行为,可在函数末尾添加 return false;
。
optional MouseEvent
argument.
\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square becomes lighter as the user drags the mouse.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\nfunction mouseDragged() {\n // Update the grayscale value.\n value += 5;\n\n // Reset the grayscale value.\n if (value > 255) {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n一个 Boolean
布尔值类型的系统变量,当鼠标被按下时为 true
,否则为 false
。
\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with the word \"false\" at its center. The word changes to \"true\" when the user presses a mouse button.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the mouseIsPressed variable.\n text(mouseIsPressed, 25, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a white square at its center. The inner square turns black when the user presses the mouse.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n if (mouseIsPressed === true) {\n fill(0);\n } else {\n fill(255);\n }\n\n // Draw the square.\n square(25, 25, 50);\n}\n
\n当鼠标移动时调用的函数。
\n声明函数 mouseMoved()
会设置一个代码块,在用户移动鼠标但未点击任何鼠标按钮时自动运行:
\nfunction mouseMoved() {\n // Code to run.\n}\n
\n鼠标系统变量,如 mouseX 和 mouseY,将在 p5.js 调用 mouseMoved()
时更新为最新的值:
\nfunction mouseMoved() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\n参数 event
是可选的。mouseMoved()
总是传递一个 MouseEvent 对象,该对象带有描述鼠标移动事件的属性:
\nfunction mouseMoved(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n浏览器可能对各种鼠标事件附加了默认行为。例如,当用户在按下鼠标按钮的同时移动鼠标时,一些浏览器会高亮显示文本。要防止此事件的任何默认行为,请在函数末尾添加 return false;
。
optional MouseEvent
argument.
\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square becomes lighter as the mouse moves.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\nfunction mouseMoved() {\n // Update the grayscale value.\n value += 5;\n\n // Reset the grayscale value.\n if (value > 255) {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n当鼠标按钮被按下时调用一次的函数。
\n声明函数 mousePressed()
将设置一个代码块,在用户按下鼠标按钮时自动运行:
\nfunction mousePressed() {\n // Code to run.\n}\n
\n鼠标系统变量,如 mouseX 和 mouseY,会在 p5.js 调用 mousePressed()
时更新为最新的值:
\nfunction mousePressed() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\n参数 event
是可选的。mousePressed()
总是传递一个 MouseEvent 对象,其中包含描述鼠标按压事件的属性:
\nfunction mousePressed(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n在触摸屏设备上,如果没有声明 touchStarted(),当用户的触摸开始时 mousePressed()
会运行。如果声明了 touchStarted(),那么当用户的触摸开始时 touchStarted() 会运行,而 mousePressed()
不会。
浏览器可能会将默认行为附加到各种鼠标事件上。例如,一些浏览器在用户按下鼠标按钮同时移动鼠标时会高亮显示文本。要防止此事件的任何默认行为,在函数的末尾添加 return false;
。
注意:mousePressed()
、mouseReleased() 和 mouseClicked() 都是相关的。mousePressed()
在用户点击鼠标时立即运行。mouseReleased() 在用户释放鼠标点击时立即运行。mouseClicked() 在 mouseReleased() 之后立即运行。
optional MouseEvent
argument.
\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square becomes lighter when the user presses a mouse button.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\nfunction mousePressed() {\n // Update the grayscale value.\n value += 5;\n\n // Reset the grayscale value.\n if (value > 255) {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Style the circle.\n fill('orange');\n stroke('royalblue');\n strokeWeight(10);\n\n describe(\n 'An orange circle with a thick, blue border drawn on a gray background. When the user presses and holds the mouse, the border becomes thin and pink. When the user releases the mouse, the border becomes thicker and changes color to blue.'\n );\n}\n\nfunction draw() {\n background(220);\n\n // Draw the circle.\n circle(50, 50, 20);\n}\n\n// Set the stroke color and weight as soon as the user clicks.\nfunction mousePressed() {\n stroke('deeppink');\n strokeWeight(3);\n}\n\n// Set the stroke and fill colors as soon as the user releases\n// the mouse.\nfunction mouseReleased() {\n stroke('royalblue');\n\n // This is never visible because fill() is called\n // in mouseClicked() which runs immediately after\n // mouseReleased();\n fill('limegreen');\n}\n\n// Set the fill color and stroke weight after\n// mousePressed() and mouseReleased() are called.\nfunction mouseClicked() {\n fill('orange');\n strokeWeight(10);\n}\n
\n当鼠标按钮释放时调用一次的函数。
\n声明函数 mouseReleased()
将设置一个代码块,当用户在按下鼠标按钮后释放时自动运行:
\nfunction mouseReleased() {\n // Code to run.\n}\n
\n鼠标系统变量,如 mouseX 和 mouseY,将在 p5.js 调用 mouseReleased()
时更新为最新的值:
\nfunction mouseReleased() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\n参数 event
是可选的。 mouseReleased()
总是传递一个 MouseEvent 对象,其属性描述了鼠标释放事件:
\nfunction mouseReleased(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\n在触摸屏设备上,如果没有声明 touchEnded(),当用户的触摸结束时,mouseReleased()
会运行。如果声明了 touchEnded(),那么当用户的触摸结束时,touchEnded() 会运行,而 mouseReleased()
不会。
浏览器可能会将默认行为附加到各种鼠标事件上。例如,一些浏览器在用户按下鼠标按钮移动鼠标时会高亮显示文本。要防止此事件的任何默认行为,在函数的末尾添加 return false;
。
注意:mousePressed()、mouseReleased()
和 mouseClicked() 都是相关的。mousePressed() 在用户点击鼠标时运行。mouseReleased()
在用户释放鼠标点击时运行。mouseClicked() 在 mouseReleased()
之后立即运行。
optional MouseEvent
argument.
\nlet value = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with a black square at its center. The inner square becomes lighter when the user presses and releases a mouse button.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the square.\n fill(value);\n\n // Draw the square.\n square(25, 25, 50);\n}\n\nfunction mouseReleased() {\n // Update the grayscale value.\n value += 5;\n\n // Reset the grayscale value.\n if (value > 255) {\n value = 0;\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Style the circle.\n fill('orange');\n stroke('royalblue');\n strokeWeight(10);\n\n describe(\n 'An orange circle with a thick, blue border drawn on a gray background. When the user presses and holds the mouse, the border becomes thin and pink. When the user releases the mouse, the border becomes thicker and changes color to blue.'\n );\n}\n\nfunction draw() {\n background(220);\n\n // Draw the circle.\n circle(50, 50, 20);\n}\n\n// Set the stroke color and weight as soon as the user clicks.\nfunction mousePressed() {\n stroke('deeppink');\n strokeWeight(3);\n}\n\n// Set the stroke and fill colors as soon as the user releases\n// the mouse.\nfunction mouseReleased() {\n stroke('royalblue');\n\n // This is never visible because fill() is called\n // in mouseClicked() which runs immediately after\n // mouseReleased();\n fill('limegreen');\n}\n\n// Set the fill color and stroke weight after\n// mousePressed() and mouseReleased() are called.\nfunction mouseClicked() {\n fill('orange');\n strokeWeight(10);\n}\n
\n当鼠标滚轮移动时调用一次的函数。
\n声明函数 mouseWheel()
将设置一个代码块,当用户使用鼠标滚轮滚动时自动运行:
\nfunction mouseWheel() {\n // Code to run.\n}\n
\n鼠标系统变量,如 mouseX 和 mouseY,将在调用 mouseWheel()
时更新为最新的值:
\nfunction mouseWheel() {\n if (mouseX < 50) {\n // Code to run if the mouse is on the left.\n }\n\n if (mouseY > 50) {\n // Code to run if the mouse is near the bottom.\n }\n}\n
\n参数 event
是可选的。mouseWheel()
总是传递一个 MouseEvent 对象,该对象带有描述鼠标滚轮事件的属性:
\nfunction mouseWheel(event) {\n // Code to run that uses the event.\n console.log(event);\n}\n
\nevent
对象有许多属性,包括 delta
,一个 Number
,包含用户滚动的距离。例如,当用户向上滚动时,event.delta
可能有值 5。event.delta
如果用户向上滚动则为正,向下滚动则为负。在 macOS 上启用“自然”滚动时,符号相反。
浏览器可能对各种鼠标事件附加默认行为。例如,一些浏览器在用户按下鼠标按钮时移动鼠标会突出显示文本。为了防止此事件的任何默认行为,添加 return false;
到函数的末尾。
注意:在 Safari 上,mouseWheel()
可能只有在函数末尾添加 return false;
时才能按预期工作。
optional WheelEvent
argument.
\nlet circleSize = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. A white circle at its center grows up when the user scrolls the mouse wheel.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Draw the circle\n circle(circleSize, 50, 50);\n}\n\n// Increment circleSize when the user scrolls the mouse wheel.\nfunction mouseWheel() {\n circleSize += 1;\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n\nlet direction = '';\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. An arrow at its center points up when the user scrolls up. The arrow points down when the user scrolls down.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Draw an arrow that points where\n // the mouse last scrolled.\n text(direction, 50, 50);\n}\n\n// Change direction when the user scrolls the mouse wheel.\nfunction mouseWheel(event) {\n if (event.delta > 0) {\n direction = '▲';\n } else {\n direction = '▼';\n }\n // Uncomment to prevent any default behavior.\n // return false;\n}\n
\n一个 Number
数字类型的系统变量,用于跟踪鼠标的水平位置。
在 2D 模式下,mouseX
跟踪鼠标相对于画布左上角的位置。例如,如果鼠标距离画布的左边缘 50 像素,那么 mouseX
将为 50。
在 WebGL 模式下,mouseX
跟踪鼠标相对于画布中心的位置。例如,如果鼠标位于画布中心右侧 50 像素处,那么 mouseX
将为 50。
如果使用触摸代替鼠标,则 mouseX
将保持最近触摸点的 x 坐标。
\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A vertical black line moves left and right following the mouse's x-position.\");\n}\n\nfunction draw() {\n background(200);\n\n // Draw a vertical line that follows the mouse's x-coordinate.\n line(mouseX, 0, mouseX, 100);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse.\");\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the mouse's coordinates.\n text(`x: ${mouseX} y: ${mouseY}`, 50, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\"A vertical black line moves left and right following the mouse's x-position.\");\n}\n\nfunction draw() {\n background(200);\n\n // Adjust coordinates for WebGL mode.\n // The origin (0, 0) is at the center of the canvas.\n let mx = mouseX - 50;\n\n // Draw the line.\n line(mx, -50, mx, 50);\n}\n
\n\nlet font;\n\n// Load a font for WebGL mode.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n \"A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse.\"\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Display the mouse's coordinates.\n text(`x: ${mouseX} y: ${mouseY}`, 0, 0);\n}\n
\n一个 Number
数字类型的系统变量,用于跟踪鼠标的垂直位置。
在 2D 模式下,mouseY
跟踪鼠标相对于画布左上角的位置。例如,如果鼠标距离画布顶部边缘 50 像素,则 mouseY
将为 50。
在 WebGL 模式下,mouseY
跟踪鼠标相对于画布中心的位置。例如,如果鼠标位于画布中心下方 50 像素,则 mouseY
将为 50。
如果使用触摸代替鼠标,则 mouseY
将持有最近触摸点的 y 坐标。
\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A horizontal black line moves up and down following the mouse's y-position.\");\n}\n\nfunction draw() {\n background(200);\n\n // Draw a horizontal line that follows the mouse's y-coordinate.\n line(0, mouseY, 0, mouseY);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse.\");\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the mouse's coordinates.\n text(`x: ${mouseX} y: ${mouseY}`, 50, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\"A horizontal black line moves up and down following the mouse's y-position.\");\n}\n\nfunction draw() {\n background(200);\n\n // Adjust coordinates for WebGL mode.\n // The origin (0, 0) is at the center of the canvas.\n let my = mouseY - 50;\n\n // Draw the line.\n line(-50, my, 50, my);\n}\n
\n\nlet font;\n\n// Load a font for WebGL mode.\nfunction preload() {\n font = loadFont('/assets/inconsolata.otf');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe(\n \"A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse.\"\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n textFont(font);\n fill(0);\n\n // Display the mouse's coordinates.\n text(`x: ${mouseX} y: ${mouseY}`, 0, 0);\n}\n
\n一个 Number
数字类型的系统变量,用于跟踪鼠标的水平移动。
movedX
跟踪鼠标在帧之间左右移动了多少像素。如果鼠标在帧之间向左移动,movedX
将会是负值;如果向右移动,则为正值。movedX
可以计算为 mouseX - pmouseX
。
注意:movedX
即使在 requestPointerLock() 激活时也会继续更新。
\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. The text \">>\" appears when the user moves the mouse to the right. The text \"<<\" appears when the user moves the mouse to the left.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display >> when movedX is positive and\n // << when it's negative.\n if (movedX > 0) {\n text('>>', 50, 50);\n } else if (movedX < 0) {\n text('<<', 50, 50);\n }\n}\n
\n一个 Number
数字类型的系统变量,用于跟踪鼠标的垂直移动。
movedY
跟踪鼠标在帧之间上升或下降的像素数。movedY
如果鼠标在帧之间上移会有一个负值,如果下移则有一个正值。movedY
可以计算为 mouseY - pmouseY
。
注意:movedY
即使在 requestPointerLock() 激活时也会继续更新。
\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square. The text \"▲\" appears when the user moves the mouse upward. The text \"▼\" appears when the user moves the mouse downward.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display ▼ when movedY is positive and\n // ▲ when it's negative.\n if (movedY > 0) {\n text('▼', 50, 50);\n } else if (movedY < 0) {\n text('▲', 50, 50);\n }\n}\n
\n一个 Number
数字类型的系统变量,用于跟踪鼠标的前一个水平位置。
在 2D 模式下,pmouseX
用于跟踪鼠标相对于画布左上角的位置。它的值是上一帧的 mouseX。例如,如果上一帧鼠标距离画布左边缘 50 像素,则 pmouseX
将为 50。
在 WebGL 模式下,pmouseX
用于跟踪鼠标相对于画布中心的位置。例如,如果上一帧鼠标在画布中心右侧 50 像素,则 pmouseX
将为 50。
如果使用触摸代替鼠标,则 pmouseX
将保存最后一个触摸点的 x 坐标。
注意:pmouseX
在每个触摸事件开始时重置为当前的 mouseX 值。
\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(10);\n\n describe('A line follows the mouse as it moves. The line grows longer with faster movements.');\n}\n\nfunction draw() {\n background(200);\n\n line(pmouseX, pmouseY, mouseX, mouseY);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A line follows the mouse as it moves. The line grows longer with faster movements.');\n}\n\nfunction draw() {\n background(200);\n\n // Adjust coordinates for WebGL mode.\n // The origin (0, 0) is at the center of the canvas.\n let pmx = pmouseX - 50;\n let pmy = pmouseY - 50;\n let mx = mouseX - 50;\n let my = mouseY - 50;\n\n // Draw the line.\n line(pmx, pmy, mx, my);\n}\n
\n一个 Number
数字类型的系统变量,用于追踪鼠标的前一个垂直位置。
在 2D 模式下,pmouseY
跟踪鼠标相对于画布左上角的位置。其值是上一帧的 mouseY。例如,如果上一帧鼠标距离画布顶边 50 像素,则 pmouseY
将为 50。
在 WebGL 模式下,pmouseY
跟踪鼠标相对于画布中心的位置。例如,如果上一帧鼠标在画布中心下方 50 像素,则 pmouseY
将为 50。
如果使用触摸代替鼠标,则 pmouseY
将保持最后一个触摸点的 y 坐标。
注意:pmouseY
在每个触摸事件开始时重置为当前的 mouseY 值。
\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(10);\n\n describe('A line follows the mouse as it moves. The line grows longer with faster movements.');\n}\n\nfunction draw() {\n background(200);\n\n line(pmouseX, pmouseY, mouseX, mouseY);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n describe('A line follows the mouse as it moves. The line grows longer with faster movements.');\n}\n\nfunction draw() {\n background(200);\n\n // Adjust coordinates for WebGL mode.\n // The origin (0, 0) is at the center of the canvas.\n let pmx = pmouseX - 50;\n let pmy = pmouseY - 50;\n let mx = mouseX - 50;\n let my = mouseY - 50;\n\n // Draw the line.\n line(pmx, pmy, mx, my);\n}\n
\n一个 Number
数字类型的系统变量,用于跟踪鼠标在浏览器内的前一个水平位置。
pwinMouseX
记录鼠标相对于浏览器窗口左上角的位置。其值是上一帧的 winMouseX。例如,如果上一帧鼠标距离浏览器左边缘 50 像素,那么 pwinMouseX
将为 50。
在触摸屏设备上,pwinMouseX
将保持最近触摸点的 x 坐标。pwinMouseX
在每个触摸事件开始时重置为当前的 winMouseX 值。
注意:使用 pmouseX 跟踪鼠标在画布内的前一个 x 坐标。
\n"],"line":[0,551],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(10);\n\n describe('A gray square. A white circle at its center grows larger when the mouse moves horizontally.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the circle's diameter.\n let d = winMouseX - pwinMouseX;\n\n // Draw the circle.\n circle(50, 50, d);\n}\n
\n\nfunction setup() {\n // Create the canvas and set its position.\n let cnv = createCanvas(100, 100);\n cnv.position(20, 20);\n\n describe('A gray square with a number at its center. The number changes as the user moves the mouse vertically.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display pwinMouseX.\n text(pwinMouseX, 50, 50);\n}\n
\n一个 Number
数字类型的系统变量,用于追踪鼠标在浏览器内的前一个垂直位置。
pwinMouseY
记录鼠标相对于浏览器窗口左上角的位置。其值是上一个帧的 winMouseY。例如,如果鼠标在上一个帧中距离浏览器顶部边缘 50 像素,那么 pwinMouseY
将是 50。
在触摸屏设备上,pwinMouseY
将保持最近触摸点的 y 坐标。pwinMouseY
在每个触摸事件开始时重置为当前 winMouseY 的值。
注意:使用 pmouseY 来追踪鼠标在画布内的前一个 y 坐标。
\n"],"line":[0,622],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(10);\n\n describe('A gray square. A white circle at its center grows larger when the mouse moves vertically.');\n}\n\nfunction draw() {\n background(200);\n\n // Calculate the circle's diameter.\n let d = winMouseY - pwinMouseY;\n\n // Draw the circle.\n circle(50, 50, d);\n}\n
\n\nfunction setup() {\n // Create the canvas and set its position.\n let cnv = createCanvas(100, 100);\n cnv.position(20, 20);\n\n describe('A gray square with a number at its center. The number changes as the user moves the mouse vertically.');\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display pwinMouseY.\n text(pwinMouseY, 50, 50);\n}\n
\n锁定鼠标指针到其当前位置并使其不可见。
\nrequestPointerLock()
允许鼠标无限移动而不会离开屏幕。调用 requestPointerLock()
会锁定 mouseX、mouseY、pmouseX 和 pmouseY 的值。movedX 和 movedY 会继续更新,并可用于获取自上一帧绘制以来鼠标移动的距离。调用 exitPointerLock() 会恢复更新鼠标系统变量。
注意:大多数浏览器在调用 requestPointerLock()
之前需要一个输入操作,例如点击。建议在如 doubleClicked() 等事件函数中调用 requestPointerLock()
。
\nlet score = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A gray square with the text \"Score: X\" at its center. The score increases when the user moves the mouse upward. It decreases when the user moves the mouse downward.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Update the score.\n score -= movedY;\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the score.\n text(`Score: ${score}`, 50, 50);\n}\n\n// Lock the pointer when the user double-clicks.\nfunction doubleClicked() {\n requestPointerLock();\n}\n
\n一个 Number
数字类型的系统变量,用于跟踪鼠标在浏览器内的水平位置。
winMouseX
跟踪鼠标相对于浏览器窗口左上角的位置。例如,如果鼠标距离浏览器左边缘 50 像素,则 winMouseX
将为 50。
在触摸屏设备上,winMouseX
将保存最近触摸点的 x 坐标。
注意:使用 mouseX 来跟踪鼠标在画布内的 x 坐标。
\n"],"line":[0,469],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse.\");\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the mouse's coordinates within the browser window.\n text(`x: ${winMouseX} y: ${winMouseY}`, 50, 50);\n}\n
\n一个 Number
数字类型的系统变量,用于追踪鼠标在浏览器内的垂直位置。
winMouseY
跟踪鼠标相对于浏览器窗口左上角的位置。例如,如果鼠标距离浏览器顶部边缘 50 像素,则 winMouseY
将为 50。
在触摸屏设备上,winMouseY
将保存最近触摸点的 y 坐标。
注意:使用 mouseY 来追踪鼠标在画布内的 y 坐标。
\n"],"line":[0,510],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\"A gray square. The mouse's x- and y-coordinates are displayed as the user moves the mouse.\");\n}\n\nfunction draw() {\n background(200);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Display the mouse's coordinates within the browser window.\n text(`x: ${winMouseX} y: ${winMouseY}`, 50, 50);\n}\n
\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
\n将数字或字符串转换为其布尔值。对于数字,任何非零值(正数或负数),其布尔值都是 true,0 的布尔值是 false。对于字符串,值 “true” 的布尔值是 true,其余都是 false。\n如果传入的值是数字或字符串数组,则会返回和数组等长度的布尔数组。
\n"],"line":[0,112],"params":[1,[[0,{"name":[0,"n"],"description":[0,"value to parse
\n"],"type":[0,"String|Boolean|Number|Array"]}]]],"itemtype":[0,"method"],"class":[0,"p5"],"chainable":[0,false],"return":[0,{"description":[0,"boolean representation of value"],"type":[0,"Boolean"]}],"example":[1,[[0,"\n\nprint(boolean(0)); // false\nprint(boolean(1)); // true\nprint(boolean('true')); // true\nprint(boolean('abcd')); // false\nprint(boolean([0, 12, 'true'])); // [false, true, true]\n
一个 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
\n一个按顺序存储多个数据的列表。
\n数组有助于存储相关数据。它们可以存储任何类型的数据。例如,数组可以以字符串的形式存储某人最喜欢的颜色列表。数组的创建方式如下:
\n\nlet colors = ['deeppink', 'darkorchid', 'magenta'];\n
\n\n数组中的每个数据皆为一个元素。每个元素在其数组中都有一个地址或索引。变量 colors
指的是一个包含三个元素的数组。String> elements, 'deeppink'
,\n'darkorchid'
,和 'magenta'
。数组的索引是从 0 开始的,这就意味着 'deeppink'
的索引是 0, 'darkorchid'
的索引是 1,\n‘magenta'
的索引是 2。我们可以使用数组的索引来访问数组元素,如下所示:
\nlet zeroth = colors[0]; // 'deeppink'\nlet first = colors[1]; // 'darkorchid'\nlet second = colors[2]; // 'magenta'\n
\n\n通过调用 push()
方法,可以在数组末尾添加元素。方法如下:\nmethod as follows:
\ncolors.push('lavender');\n\nlet third = colors[3]; // 'lavender'\n
\n了解更多关于数组的信息,请参阅 MDN
\n"],"line":[0,1137],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// Declare the variable xCoordinates and assign it an array\n// with three numeric elements.\nlet xCoordinates = [25, 50, 75];\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'Three white circles drawn in a horizontal line on a gray background.'\n );\n}\n\nfunction draw() {\n background(200);\n\n // Access the element at index 0, which is 25.\n circle(xCoordinates[0], 50, 20);\n\n // Access the element at index 1, which is 50.\n circle(xCoordinates[1], 50, 20);\n\n // Access the element at index 2, which is 75.\n circle(xCoordinates[2], 50, 20);\n}\n
\n\n// Declare the variable xCoordinates and assign it an array with three numeric elements.\nlet xCoordinates = [20, 40, 60];\n\n// Add another element to the end of the array.\nxCoordinates.push(80);\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Four white circles drawn in a horizontal line on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the element at index 0, which is 20.\n circle(xCoordinates[0], 50, 20);\n\n // Access the element at index 1, which is 40.\n circle(xCoordinates[1], 50, 20);\n\n // Access the element at index 2, which is 60.\n circle(xCoordinates[2], 50, 20);\n\n // Access the element at index 3, which is 80.\n circle(xCoordinates[3], 50, 20);\n}\n
\n\n// Declare the variable xCoordinates and assign it an empty array.\nlet xCoordinates = [];\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Add elements to the array using a loop.\n for (let x = 20; x < 100; x += 20) {\n xCoordinates.push(x);\n }\n\n describe('Four white circles drawn in a horizontal line on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the element at index i and use it to draw a circle.\n for (let i = 0; i < xCoordinates.length; i += 1) {\n circle(xCoordinates[i], 50, 20);\n }\n}\n
\n\n// Declare the variable xCoordinates and assign it an empty array.\nlet xCoordinates = [];\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Add elements to the array using a loop.\n for (let x = 20; x < 100; x += 20) {\n xCoordinates.push(x);\n }\n\n describe('Four white circles drawn in a horizontal line on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access each element of the array and use it to draw a circle.\n for (let x of xCoordinates) {\n circle(x, 50, 20);\n }\n}\n
\n\n// Declare the variable xCoordinates and assign it an empty array.\nlet xCoordinates = [];\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Add elements to the array using a loop.\n for (let x = 20; x < 100; x += 20) {\n xCoordinates.push(x);\n }\n\n describe(\n 'Four white circles in a horizontal line on a gray background. The circles move randomly.'\n );\n}\n\nfunction draw() {\n background(200);\n\n for (let i = 0; i < xCoordinates.length; i += 1) {\n // Update the element at index i.\n xCoordinates[i] += random(-1, 1);\n\n // Use the element at index i to draw a circle.\n circle(xCoordinates[i], 50, 20);\n }\n}\n
\n特殊类型对象的创建模板
类可以让使用对象编程变得更容易。例如,一个 Frog
\n 类可以创建行为像青蛙一样的对象。通过类创建的每个对象都是该类的一个实例。同一个类的所有实例都是相同类型。以下是创建 Frog
\n 类实例的示例:
let fifi = new Frog(50, 50, 20);
\n变量 fifi
代表 Frog
的一个实例。关键字 new
用于在语句 new Frog()
中调用 Frog
。总之,一个新的 Frog
对象被创建并赋值给了变量 fifi
。类是模板,因此我们可以用它创建多个实例:
// First Frog instance. let frog1 = new Frog(25, 50, 10);\n// Second Frog instance. let frog2 = new Frog(75, 50, 10);
一个简单的 Frog
类可以声明如下:
class Frog {\n constructor(x, y, size) {\n // This code runs once when an instance is created.\n this.x = x;\n this.y = y;\n this.size = size;\n }\n\n show() {\n // This code runs once when myFrog.show() is called.\n textAlign(CENTER, CENTER);\n textSize(this.size);\n text('\\U0001F438', this.x, this.y);\n }
\n hop() {\n // This code runs once when myFrog.hop() is called.\n this.x += random(-10, 10);\n this.y += random(-10, 10);\n }\n}
类的声明以关键字 class
开头,后跟类名。例如 Frog
,加上 {}
。类名应该使用 PascalCase
,并且不能包含空格。例如:命名为含有空格的 Kermit The Frog
,就会引发 SyntaxError
错误。花括号 {}
之间的代码定义类。
属于类的函数被称为方法。在 Frog
类中,constructor()
, show()
,和 hop()
都是方法。方法定义对象的行为。方法可以接受参数并返回值,就像函数一样。注意:方法不使用 function
关键字。
constructor()
是一个特殊的方法,在创建类的实例时调用一次。语句 new Frog()
调用 Frog
类的 constructor()
方法。
类定义是实例的模板。关键字 this
指代实例的数据和方法。例如,每个 Frog
实例都有独特的坐标存储在 this.x
和 this.y
中。show()
方法使用这些坐标来绘制青蛙。当调用 hop()
方法时,坐标会更新。一旦创建了一个 Frog
实例,可以使用点运算符 .
来访问它的数据和方法,如下所示:
// Draw a lily pad. fill('green'); stroke('green'); circle(fifi.x, fifi.y, 2 \\* fifi.size);\n// Show the Frog. fifi.show();
// Hop. fifi.hop();
\n"],"line":[0,1325],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// Declare a frog variable.\nlet fifi;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Assign the frog variable a new Frog object.\n fifi = new Frog(50, 50, 20);\n\n describe('A frog face drawn on a gray background.');\n}\n\nfunction draw() {\n background('cornflowerblue');\n\n // Show the frog.\n fifi.show();\n}\n\nclass Frog {\n constructor(x, y, size) {\n this.x = x;\n this.y = y;\n this.size = size;\n }\n\n show() {\n textAlign(CENTER, CENTER);\n textSize(this.size);\n text('🐸', this.x, this.y);\n }\n}\n
\n\n// Declare two frog variables.\nlet frog1;\nlet frog2;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Assign the frog variables a new Frog object.\n frog1 = new Frog(25, 50, 10);\n frog2 = new Frog(75, 50, 20);\n\n describe('Two frog faces drawn next to each other on a gray background.');\n}\n\nfunction draw() {\n background('cornflowerblue');\n\n // Show the frogs.\n frog1.show();\n frog2.show();\n}\n\nclass Frog {\n constructor(x, y, size) {\n this.x = x;\n this.y = y;\n this.size = size;\n }\n\n show() {\n textAlign(CENTER, CENTER);\n textSize(this.size);\n text('🐸', this.x, this.y);\n }\n}\n
\n\n// Declare two frog variables.\nlet frog1;\nlet frog2;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Assign the frog variables a new Frog object.\n frog1 = new Frog(25, 50, 10);\n frog2 = new Frog(75, 50, 20);\n\n // Slow the frame rate.\n frameRate(1);\n\n describe('Two frog faces on a gray background. The frogs hop around randomly.');\n}\n\nfunction draw() {\n background('cornflowerblue');\n\n // Show the frogs.\n frog1.show();\n frog2.show();\n\n // Move the frogs.\n frog1.hop();\n frog2.hop();\n\n // Wrap around if they've hopped off the edge.\n frog1.checkEdges();\n frog2.checkEdges();\n}\n\nclass Frog {\n constructor(x, y, size) {\n this.x = x;\n this.y = y;\n this.size = size;\n }\n\n show() {\n textAlign(CENTER, CENTER);\n textSize(this.size);\n text('🐸', this.x, this.y);\n }\n\n hop() {\n this.x += random(-10, 10);\n this.y += random(-10, 10);\n }\n\n checkEdges() {\n if (this.x > width) {\n this.x = this.x - width;\n } else if (this.x < 0) {\n this.x = width - this.x;\n }\n\n if (this.y > height) {\n this.y = this.y - height;\n } else if (this.y < 0) {\n this.y = height - this.y;\n }\n }\n}\n
\n\n// Declare two frog variables.\nlet frog1;\nlet frog2;\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Assign the frog variables a new Frog object.\n frog1 = new Frog(25, 50, 10);\n frog2 = new Frog(75, 50, 20);\n\n describe('Two frog faces drawn next to each other on a gray background.');\n}\n\nfunction draw() {\n background('cornflowerblue');\n\n // Show the frogs.\n frog1.show();\n frog2.show();\n}\n\nclass Frog {\n constructor(x, y, size) {\n this.x = x;\n this.y = y;\n this.size = size;\n }\n\n show() {\n textAlign(CENTER, CENTER);\n textSize(this.size);\n text('🐸', this.x, this.y);\n }\n}\n
\n\n// Create an array that will hold frogs.\nlet frogs = [];\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Add Frog objects to the array.\n for (let i = 0; i < 5; i += 1) {\n // Calculate random coordinates and size.\n let x = random(0, 100);\n let y = random(0, 100);\n let s = random(2, 20);\n\n // Create a new Frog object.\n let frog = new Frog(x, y, s);\n\n // Add the Frog to the array.\n frogs.push(frog);\n }\n\n // Slow the frame rate.\n frameRate(1);\n\n describe(\n 'Five frog faces on a gray background. The frogs hop around randomly.'\n );\n}\n\nfunction draw() {\n background('cornflowerblue');\n\n for (let frog of frogs) {\n // Show the frog.\n frog.show();\n\n // Move the frog.\n frog.hop();\n\n // Wrap around if they've hopped off the edge.\n frog.checkEdges();\n }\n}\n\nclass Frog {\n constructor(x, y, size) {\n this.x = x;\n this.y = y;\n this.size = size;\n }\n\n show() {\n textAlign(CENTER, CENTER);\n textSize(this.size);\n text('🐸', this.x, this.y);\n }\n\n hop() {\n this.x += random(-10, 10);\n this.y += random(-10, 10);\n }\n\n checkEdges() {\n if (this.x > width) {\n this.x = this.x - width;\n } else if (this.x < 0) {\n this.x = width - this.x;\n }\n\n if (this.y > height) {\n this.y = this.y - height;\n } else if (this.y < 0) {\n this.y = height - this.y;\n }\n }\n}\n
\n一种在已知迭代次数的情况下重复代码块的方法。
\nfor
循环对于重复执行特定次数的语句很有帮助。例如,for
循环使得表达\"画五条线\"的想法变得简单,如下所示:
\nfor (let x = 10; x < 100; x += 20) {\n line(x, 25, x, 75);\n}\n
\n\n循环的头部以关键字 for
开头。循环通常在重复或迭代时递增或递减。括号中的语句 let x = 10; x < 100; x += 20
决定循环的重复方式:
let x = 10
表示循环从 10
开始计数,并使用变量 x
记录迭代次数。 x < 100
表示循环计数到 100(但不包括 100)。x += 20
表示每次迭代结束时递增 20
。花括号 {}
之间的代码是循环的主体。循环主体中的语句在每次循环迭代期间重复执行。
意外创建无限循环是很常见的。当发生这种情况时,绘图可能会变得无响应,网页浏览器可能会显示警告。例如,以下循环永远不会停止迭代,因为它没有计数递增:
\n\nfor (let x = 10; x < 100; x = 20) {\n line(x, 25, x, 75);\n}\n
\n\n语句 x = 20
使变量 x
的值变为 20
,始终小于 100
。
for
循环也可以递减计数:
\nfor (let d = 100; d > 0; d -= 10) {\n circle(50, 50, d);\n}\n
\n\nfor
循环也可以包含其他循环。下面的嵌套循环绘制了一个点网格。
\n// Loop from left to right.\nfor (let x = 10; x < 100; x += 10) {\n\n // Loop from top to bottom.\n for (let y = 10; y < 100; y += 10) {\n point(x, y);\n }
\n}\n
\nfor
循环对于遍历数组的元素也非常有用。例如,常见的是遍历一个包含绘制位置或内容信息的数组:
\n// Create an array of x-coordinates.\nlet xCoordinates = [20, 40, 60];\n\nfor (let i = 0; i < xCoordinates.length; i += 1) {\n // Update the element.\n xCoordinates[i] += random(-1, 1);
\n // Draw a circle.\n circle(xCoordinates[i], 50, 20);\n}\n
\n如果数组的值没有被修改, 可以用 for...of
语句可以简化代码。这类似于 Python \n中的 for
循环,和 C++、Java 中的 for-each
循环。\n以下循环具有相同的效果:
\n// Draw circles with a for loop.\nlet xCoordinates = [20, 40, 60];\n\nfor (let i = 0; i < xCoordinates.length; i += 1) {\n circle(xCoordinates[i], 50, 20);\n}\n
\n\n// Draw circles with a for...of statement.\nlet xCoordinates = [20, 40, 60];\n\nfor (let x of xCoordinates) {\n circle(x, 50, 20);\n}\n
\n在上面的代码片段中,变量 i
和 x
有不同的作用。
在第一个代码片段中,i
从 0
递增到 2
,也就是 xCoordinates.length
减 1。 i
用于访问 xCoordinates
中索引为 i
的元素。
在第二个代码片段中,x
并不跟踪循环的进度或索引。在每次迭代中,x
包含 xCoordinates
的下一个元素。 x
从 xCoordinates
的开头(20
)开始,并在下一次迭代中将其值更新为 40
,然后 60
。
\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Five black vertical lines on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw vertical lines using a loop.\n for (let x = 10; x < 100; x += 20) {\n line(x, 25, x, 75);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Five white concentric circles drawn on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Draw concentric circles using a loop.\n for (let d = 100; d > 0; d -= 20) {\n circle(50, 50, d);\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A grid of black dots on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Set the spacing for points on the grid.\n let space = 10;\n\n // Increase the stroke weight.\n strokeWeight(3);\n\n // Loop from the left to the right.\n for (let x = space; x < 100; x += space) {\n // Loop from the top to the bottom.\n for (let y = space; y < 100; y += space) {\n point(x, y);\n }\n }\n}\n
\n\n// Declare the variable xCoordinates and assign it an array of numbers.\nlet xCoordinates = [20, 40, 60, 80];\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Four white circles drawn in a horizontal line on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the element at index i and use it to draw a circle.\n for (let i = 0; i < xCoordinates.length; i += 1) {\n circle(xCoordinates[i], 50, 20);\n }\n}\n
\n\n// Declare the variable xCoordinates and assign it an array of numbers.\nlet xCoordinates = [20, 40, 60, 80];\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Four white circles drawn in a horizontal line on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access each element of the array and use it to draw a circle.\n for (let x of xCoordinates) {\n circle(x, 50, 20);\n }\n}\n
\n一个被命名的语句组
Functions\n 函数有助于组织和复用代码。例如,函数使得表达“画一朵花”的想法变得容易:
\n function drawFlower() {\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(20);\n\n // Draw a flower emoji.\n text('\\U0001F338', 50, 50);\n}
函数头以关键字 function
开始。函数名 drawFlower
后面是括号 ()
和花括号 {}
。\n 花括号之间的代码是函数的主体。调用函数时,函数主体中的代码就会运行,如下所示:
drawFlower();
\n函数可以通过在其头部添加参数来接收输入。\n 参数是值的占位符,调用函数时需要提供这些值。例如,drawFlower()
函数可以接收一个代表花朵大小的参数:
function drawFlower(size) {\n // Style the text.\n textAlign(CENTER, CENTER);\n\n // Use the size parameter.\n textSize(size);
\n // Draw a flower emoji.\n text('\\U0001F338', 50, 50);\n}
参数是函数声明的一部分,实参由调用函数的代码提供。调用函数时,实参会替代形参:
// The argument 20 is assigned to the parameter size. drawFlower(20);
\n一个函数可以有多个参数,参数之间用逗号隔开。参数可以是任何类型,例如,drawFlower()
函数可以接收 Number
类型的参数,用于花朵的 x 和 y 坐标以及花朵的大小:
function drawFlower(x, y, size) {\n // Style the text.\n textAlign(CENTER, CENTER);\n\n // Use the size parameter.\n textSize(size);
\n // Draw a flower emoji.\n // Use the x and y parameters.\n text('\\U0001F338', x, y);\n}
函数还可以通过添加 return
语句产生输出:
function double(x) {\n let answer = 2 \\* x;\n return answer;\n}
\nreturn
后面的表达式可以产生一个输出,这个输出可以在其他地方使用。例如,double()
函数的输出可以赋值给一个变量:
let six = double(3); text(`3 x 2 = ${six}`, 50, 50);
\n"],"line":[0,317],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A pink flower on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Call the drawFlower() function.\n drawFlower();\n}\n\n// Declare a function that draws a flower at the\n// center of the canvas.\nfunction drawFlower() {\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(20);\n\n // Draw a flower emoji.\n text('🌸', 50, 50);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A pink flower on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Call the drawFlower() function and pass values for\n // its position and size.\n drawFlower(50, 50, 20);\n}\n\n// Declare a function that draws a flower at the\n// center of the canvas.\nfunction drawFlower(x, y, size) {\n // Style the text.\n textAlign(CENTER, CENTER);\n\n // Use the size parameter.\n textSize(size);\n\n // Draw a flower emoji.\n // Use the x and y parameters.\n text('🌸', x, y);\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('The message \"Hello, 🌍!\" written on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Create a greeting.\n let greeting = createGreeting('🌍');\n\n // Style the text.\n textAlign(CENTER, CENTER);\n textSize(16);\n\n // Display the greeting.\n text(greeting, 50, 50);\n}\n\n// Return a string with a personalized greeting.\nfunction createGreeting(name) {\n let message = `Hello, ${name}!`;\n return message;\n}\n
\n一种选择是否运行一段代码的方法。
\nif
语句对于根据条件运行一段代码非常有帮助。例如 if
语句使得表达“如果鼠标被按下,则画一个圆”的想法变得简单:
\nif (mouseIsPressed === true) {\n circle(mouseX, mouseY, 20);\n}\n
\n\n语句头部以关键字 if
开头。括号中的表达式 mouseIsPressed === true
是一个 Boolean
表达式, 其值为 true
或 false
。花括号 {}
之间的代码是 if 语句的主体。 只有当 Boolean
表达式的值是 true
时,主体中的代码才会运行。
mouseIsPressed 系统变量始终为 true
或 false
,所以上面的代码片段也可以写成:
\nif (mouseIsPressed) {\n circle(mouseX, mouseY, 20);\n}\n
\n\nif
-else
语句中的代码,只有当 Boolean
表达式的值为 false
的时候才会运行。 例如:下面是一个 if
-else
语句,表示“如果鼠标被按下,则画一个圆。否则,显示一条消息”:
\nif (mouseIsPressed === true) {\n // When true.\n circle(mouseX, mouseY, 20);\n} else {\n // When false.\n text('Click me!', 50, 50);\n}\n
\n\n这段代码片段有两条可能的路径,或者说分支。程序必须遵循其中一条分支。
\nelse
-if
语句允许添加多个分支。\nelse
-if
语句在不同的条件下运行不同的代码块。 例如,else
-if
语句使得表达“如果鼠标在左边,将画布涂白。 如果鼠标在中间,将画布涂灰。否则,将画布涂黑。”变得简单:
\nif (mouseX < 33) {\n background(255);\n} else if (mouseX < 67) {\n background(200);\n} else {\n background(0);\n}\n
\n\nif
语句可以根据需要添加多个 else
-if
语句。但是,只能有一个 else
语句,并且且必须放在末尾。
if
语句还可以一次性判断多个条件。例如,Boolean
运算符 &&
(且)判断两个表达式是否同时为 true
。
\nif (keyIsPressed === true && key === 'p') {\n text('You pressed the \"p\" key!', 50, 50);\n}\n
\n\n如果用户按下键盘中的 'p'
键,则会显示一条信息。
Boolean
运算符 ||
(或) 判断两个表达式中是否至少有一个为 true
。
\nif (keyIsPressed === true || mouseIsPressed === true) {\n text('You did something!', 50, 50);\n}\n
\n\n如果用户按下一个键,或者按下一个鼠标按钮,或者两者都按下,则会显示一条消息。
\nif
语句的主体可以包含另一个 if
语句。这被称为嵌套 if
语句。 例如,嵌套 if
语句使得表达“如果按下一个键,判断这个键是否是'r'键。如果是,那么将填充颜色设置为红色。”变得简单:
\nif (keyIsPressed === true) {\n if (key === 'r') {\n fill('red');\n }\n}\n
\n\n学习更多关于这些数据类型及其支持的操作,请参阅 Boolean 和 Number。
\n"],"line":[0,110],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\n// Click the mouse to show the circle.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A white circle on a gray background. The circle follows the mouse user clicks on the canvas.'\n );\n}\n\nfunction draw() {\n background(200);\n\n if (mouseIsPressed === true) {\n circle(mouseX, mouseY, 20);\n }\n}\n
\n\n// Click the mouse to show different shapes.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A white ellipse on a gray background. The ellipse becomes a circle when the user presses the mouse.'\n );\n}\n\nfunction draw() {\n background(200);\n\n if (mouseIsPressed === true) {\n circle(50, 50, 20);\n } else {\n ellipse(50, 50, 20, 50);\n }\n}\n
\n\n// Move the mouse to change the background color.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A square changes color from white to black as the user moves the mouse from left to right.'\n );\n}\n\nfunction draw() {\n if (mouseX < 33) {\n background(255);\n } else if (mouseX < 67) {\n background(200);\n } else {\n background(0);\n }\n}\n
\n\n// Click on the canvas to begin detecting key presses.\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe(\n 'A white circle drawn on a gray background. The circle changes color to red when the user presses the \"r\" key.'\n );\n}\n\nfunction draw() {\n background(200);\n\n if (keyIsPressed === true) {\n if (key === 'r') {\n fill('red');\n }\n }\n\n circle(50, 50, 40);\n}\n
\n声明一个新的变量。
\n变量是用于存储值的容器。例如,一个变量可能包含类型为数字 Number
的 x 坐标,或者类型为字符串 String
的名称。变量可以通过重新赋值来改变其值,如下所示:\n
\n// Declare the variable x and assign it the value 10.\nlet x = 10;\n\n// Reassign x to 50.\nx = 50;\n
\n变量具有块级作用域。当一个变量被声明在花括号 {}
之间时,它只存在于由花括号定义的块级内。例如,以下代码会抛出 ReferenceError
, 因为 x
是在 setup()
函数的块级内声明的:
\nfunction setup() {\n createCanvas(100, 100);\n\n let x = 50;\n}
\nfunction draw() {\n background(200);
\n // x was declared in setup(), so it can't be referenced here.\n circle(x, 50, 20);\n}\n
\n在所有花括号 {}
之外声明的变量是全局变量。全局变量可以在绘图的任何地方使用和更改:
\nlet x = 50;\n\nfunction setup() {\n createCanvas(100, 100);\n}
\nfunction draw() {\n background(200);
\n // Change the value of x.\n x += 10;
\n circle(x, 50, 20);\n}\n
\n"],"line":[0,7],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(220);\n\n // Style the text.\n textAlign(CENTER);\n textSize(16);\n\n // Create the message variable.\n let message = 'Hello, 🌍!';\n\n // Display the message.\n text(message, 50, 50);\n\n describe('The text \"Hello, 🌍!\" written on a gray background.');\n}\n
\n\nlet x = 0;\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle moves from left to right against a gray background.');\n}\n\nfunction draw() {\n background(220);\n\n // Change the value of x.\n x += 1;\n\n circle(x, 50, 20);\n}\n
\n一个可以是正数、负数或零的数字。
\nNumber
数据类型用于描述位置、大小和颜色等值。数字可以是整数,如 20,也可以是十进制数,如 12.34。 例如,圆的位置和大小可以用三个数字来描述:
\ncircle(50, 50, 20);\n
\n\n\ncircle(50, 50, 12.34);\n
\n\n数字支持基本的算术运算,并遵循标准的运算顺序:括号、指数、乘法、除法、加法和减法(PEMDAS)。 例如,我们通常使用算术运算符与 p5.js 的系统变量,这些变量都是数字:
\n\n// Draw a circle at the center.\ncircle(width / 2, height / 2, 20);\n
\n\n\n// Draw a circle that moves from left to right.\ncircle(frameCount * 0.01, 50, 20);\n
\n\n以下是算术运算符的简要概述:
\n\n1 + 2 // Add\n1 - 2 // Subtract\n1 * 2 // Multiply\n1 / 2 // Divide\n1 % 2 // Remainder\n1 ** 2 // Exponentiate\n
\n\n常见的是使用算术运算更新数字变量。例如,可以像这样更新对象的位置:
\n\nx = x + 1;\n
\n\n上面的语句使用 +
运算符将 x
的值变为 x
+ 1。 加法赋值运算符 +=
表达了相同的意思:
\nx += 1;\n
\n\n以下是赋值运算符的简要概述:
\n\nx += 2 // Addition assignment\nx -= 2 // Subtraction assignment\nx *= 2 // Multiplication assignment\nx /= 2 // Division assignment\nx %= 2 // Remainder assignment\n
\n\n数字可以通过 relational operators 进行比较:\n>
,<< code=\"\">,
>=
,<=< code=\"\">,
<>===
,和 !==
。 例如,绘图的 frameCount 可以用作计时器:=<>
\nif (frameCount > 1000) {\n text('Game over!', 50, 50);\n}\n
\n\n类似 frameCount > 1000
这样的表达式,会得出一个 Boolean
值, 要么是 true
,要么是 false
。关系运算符的运算结果都是 Boolean
值。
\n2 > 1 // true\n2 < 1 // false\n2 >= 2 // true\n2 <= 2=\"\" true=\"\" !=\"=\" false=\"\" <=\"\" code=\"\">\n\n获取更多关于比较和条件的信息,请参阅 Boolean。
\n注意:还有少一个 =
的 ==
和 !=
运算符,不要使用它们。
\n当某些情况出错时,数字表达式也可以产生特殊值:
\n\nsqrt(-1) // NaN\n1 / 0 // Infinity\n
\n\nNaN
值表示非数字 Not-A-Number。\n计算或转换失败时,返回 NaN
。 Infinity
是一个大于任何数字的值,它会出现在某些计算中。
\n=>
"],"line":[0,852],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n background(200);\n\n // Draw a circle at the center.\n circle(50, 50, 70);\n\n // Draw a smaller circle at the center.\n circle(width / 2, height / 2, 30);\n\n describe('Two concentric, white circles drawn on a gray background.');\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle travels from left to right on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n circle(frameCount * 0.01, 50, 20);\n}\n
\n一个存储键值对数据容器。
对象有助于组织任何类型的相关数据,包括其他对象。\n 存储在对象中的值可以通过名称访问,称为其键。每个键值对称为“属性”。对象类似于 Python 中的字典,Java、Ruby 中的映射。
\n例如,一个对象可以包含 dog 的位置、大小和外观:
// Declare the dog variable and assign it an object. let dog = { x: 50, y: 50, size: 20, emoji: '\\U0001F436' };\n// Style the text. textAlign(CENTER, CENTER); textSize(dog.size);
// Draw the dog. text(dog.emoji, dog.x, dog.y);
变量 dog
被赋予一个具有四个属性的对象。对象声明在花括号 {}
之中。使用点运算符可以访问对象的值,如 dog.size
。在上面的例子中,键 size
对应的值是 20
。对象的初始值也可以为空:
// Declare a cat variable and assign it an empty object. let cat = {};\n// Add properties to the object. cat.x = 50; cat.y = 50; cat.size = 20; cat.emoji = '\\U0001F431';
// Style the text. textAlign(CENTER, CENTER); textSize(cat.size);
// Draw the cat. text(cat.emoji, cat.x, cat.y);
对象的数据可以在绘图进行时被更新。例如,可以更新变量 cat
的值,使其远离 dog
:
// Run to the right. cat.x += 5;
\n如果需要,可以使用方括号 []
和字符串,而不用点符号来访问对象的值:
// Run to the right. cat[\\\"x\\\"] += 5;
\n当键名有空格时,这种语法会很有帮助,例如,cat['height (m)']
。
\n// Declare the variable data and assign it an object with three properties.\nlet data = { x: 50, y: 50, d: 20 };\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the object's values using the . operator.\n circle(data.x, data.y, data.d);\n}\n
\n\n// Declare the variable data and assign it an object with three properties.\nlet data = { x: 50, y: 50, d: 20 };\n\n// Add another property for color.\ndata.color = 'deeppink';\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A pink circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the object's values using the . operator.\n fill(data.color);\n circle(data.x, data.y, data.d);\n}\n
\n\n\n// Declare the variable data and assign it an object with three properties.\nlet data = { x: 50, y: 50, d: 20 };\n\n// Add another property for color.\ndata.color = 'deeppink';\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('A white circle on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Access the object's values using the . operator.\n fill(data.color);\n circle(data.x, data.y, data.d);\n\n // Update the object's x and y properties.\n data.x += random(-1, 1);\n data.y += random(-1, 1);\n}\n
\n重复一段代码的方法。
\nwhile
循环有助于在条件为 true
时重复执行语句。类似于重复的 if
语句。例如,while
循环可以很容易地表达“画几条线”的想法,就像这样:
\n// Declare a variable to keep track of iteration.\nlet x = 10;\n\n// Repeat as long as x < 100\nwhile (x < 100) {\n line(x, 25, x, 75);
\n // Increment by 20.\n x += 20;\n}\n
\n循环的头部以关键字 while
开始。循环通常在重复或迭代时递增或递减。括号中的语句 x < 100
是循环每次迭代时需要判断的条件,如果条件为 true
,运行花括号 {}
之间的代码。 大括号之间的代码称为循环的主体。如果条件为 false
,则跳过主体并退出循环。
意外创建无限循环是很常见的。例如,以下循环永远不会停止迭代,因为它不计数递增:
\n\n// Declare a variable to keep track of iteration.\nlet x = 10;\n\n// Repeat as long as x < 100\nwhile (x < 100) {\n line(x, 25, x, 75);\n}
\n// This should be in the loop's body!\nx += 20;\n
\n语句 x += 20
出现在循环主体之后。这意味着变量 x
的值固定为 10
,它始终小于 100
。
当迭代次数不明确时,while
就很有用。例如,可以以随机增量绘制同心圆:
\nlet d = 100;\nlet minSize = 5;\n\nwhile (d > minSize) {\n circle(50, 50, d);\n d -= random(10);\n}\n
\n"],"line":[0,1908],"itemtype":[0,"property"],"class":[0,"p5"],"example":[1,[[0,"\n\nfunction setup() {\n createCanvas(100, 100);\n\n describe('Five black vertical lines on a gray background.');\n}\n\nfunction draw() {\n background(200);\n\n // Declare a variable to keep track of iteration.\n let x = 10;\n\n // Repeat as long as x < 100\n while (x < 100) {\n line(x, 25, x, 75);\n\n // Increment by 20.\n x += 20\n }\n}\n
\n\nfunction setup() {\n createCanvas(100, 100);\n\n // Slow the frame rate.\n frameRate(5);\n\n describe(\n \"A gray square with several concentric circles at the center. The circles' sizes decrease at random increments.\"\n );\n}\n\nfunction draw() {\n background(200);\n\n let d = 100;\n let minSize = 5;\n\n while (d > minSize) {\n circle(50, 50, d);\n d -= random(5, 15);\n }\n}\n
\n