舞台

站点: 聚观点-创意编程
课程: 必修1. 互联网创意编程基础
图书: 舞台
打印: 访客用户
日期: 2024年04月24日 Wednesday 18:26

2. 场景

应用/游戏场景切换

3.1. 预先加载资源


preload()

示例:

▶️运行示例代码




let img;
let c;
function preload() {
  // preload() runs once
  img = loadImage('assets/laDefense.jpg');
}
function setup() {
  // setup() waits until preload() is done
  img.loadPixels();
  // get color of middle pixel
  c = img.get(img.width / 2, img.height / 2);
}

function draw() {
  background(c);
  image(img, 25, 25, 50, 50);
}
舞台区显示的画布内容如下:


Description

Called directly before setup(), the preload() function is used to handle asynchronous loading of external files in a blocking way. If a preload function is defined, setup() will wait until any load calls within have finished. Nothing besides load calls (loadImageloadJSONloadFontloadStrings, etc.) should be inside the preload function. If asynchronous loading is preferred, the load methods can instead be called in setup() or anywhere else with the use of a callback parameter.

By default the text "loading..." will be displayed. To make your own loading page, include an HTML element with id "p5_loading" in your page. More information here.

Syntax

preload()

3.2. 启动设置

📽️视频1.1.1:代码结构

📽️视频1.1.2:静态模式

🎞️p5.js参考



setup()

示例:

▶️运行示例代码




let a = 0;
function setup() {
  background(0);
  noStroke();
  fill(102);
}
function draw() {
  rect(a++ % width, 10, 2, 80);
}
舞台区显示的画布内容如下:


Description

The setup() function is called once when the program starts. It's used to define initial environment properties such as screen size and background color and to load media such as images and fonts as the program starts. There can only be one setup() function for each program and it shouldn't be called again after its initial execution.

Note: Variables declared within setup() are not accessible within other functions, including draw().

Syntax

setup()


3.3. 不断画帧

📽️视频1.1.3:动态模式

🎞️p5.js参考


draw()

示例:

▶️运行示例代码




let yPos = 0;
function setup() {
  // setup() runs once
  frameRate(30);
}
function draw() {
  // draw() loops forever, until stopped
  background(204);
  yPos = yPos - 1;
  if (yPos < 0) {
    yPos = height;
  }
  line(0, yPos, width, yPos);
}
舞台区显示的画布内容如下:


Description

Called directly after setup(), the draw() function continuously executes the lines of code contained inside its block until the program is stopped or noLoop() is called. Note if noLoop() is called in setup()draw() will still be executed once before stopping. draw() is called automatically and should never be called explicitly.

It should always be controlled with noLoop()redraw() and loop(). After noLoop() stops the code in draw() from executing, redraw() causes the code inside draw() to execute once, and loop() will cause the code inside draw() to resume executing continuously.

The number of times draw() executes in each second may be controlled with the frameRate() function.

There can only be one draw() function for each sketch, and draw() must exist if you want the code to run continuously, or to process events such as mousePressed(). Sometimes, you might have an empty call to draw() in your program, as shown in the above example.

It is important to note that the drawing coordinate system will be reset at the beginning of each draw() call. If any transformations are performed within draw() (ex: scale, rotate, translate), their effects will be undone at the beginning of draw(), so transformations will not accumulate over time. On the other hand, styling applied (ex: fill, stroke, etc) will remain in effect.

Syntax

draw()


3.4. 存储设置


push()

示例:

▶️运行示例代码




function setup() {
ellipse(0, 50, 33, 33); // Left circle
push(); // Start a new drawing state
strokeWeight(10);
fill(204, 153, 0);
translate(50, 0);
ellipse(0, 50, 33, 33); // Middle circle
pop(); // Restore original state
ellipse(100, 50, 33, 33); // Right circle
}

舞台区显示的画布内容如下:

示例:

▶️运行示例代码




function setup() {
ellipse(0, 50, 33, 33); // Left circle
push(); // Start a new drawing state
strokeWeight(10);
fill(204, 153, 0);
ellipse(33, 50, 33, 33); // Left-middle circle
push(); // Start another new drawing state
stroke(0, 102, 153);
ellipse(66, 50, 33, 33); // Right-middle circle
pop(); // Restore previous state
pop(); // Restore original state
ellipse(100, 50, 33, 33); // Right circle
}

舞台区显示的画布内容如下:



Description

The push() function saves the current drawing style settings and transformations, while pop() restores these settings. Note that these functions are always used together. They allow you to change the style and transformation settings and later return to what you had. When a new state is started with push(), it builds on the current style and transform information. The push() and pop() functions can be embedded to provide more control. (See the second example for a demonstration.)

push() stores information related to the current transformation state and style settings controlled by the following functions: fill()noFill()noStroke()stroke()tint()noTint()strokeWeight()strokeCap()strokeJoin()imageMode()rectMode()ellipseMode()colorMode()textAlign()textFont()textSize()textLeading()applyMatrix()resetMatrix()rotate()scale()shearX()shearY()translate()noiseSeed().

In WEBGL mode additional style settings are stored. These are controlled by the following functions: setCamera()ambientLight()directionalLight()pointLight()texture()specularMaterial()shininess()normalMaterial() and shader().

Syntax

push()

3.5. 恢复设置


pop()

示例:

▶️运行示例代码




function setup() {
ellipse(0, 50, 33, 33); // Left circle
push(); // Start a new drawing state
strokeWeight(10);
fill(204, 153, 0);
translate(50, 0);
ellipse(0, 50, 33, 33); // Middle circle
pop(); // Restore original state
ellipse(100, 50, 33, 33); // Right circle
}

舞台区显示的画布内容如下:


示例:

▶️运行示例代码


function setup() {
ellipse(0, 50, 33, 33); // Left circle
push(); // Start a new drawing state
strokeWeight(10);
fill(204, 153, 0);
ellipse(33, 50, 33, 33); // Left-middle circle
push(); // Start another new drawing state
stroke(0, 102, 153);
ellipse(66, 50, 33, 33); // Right-middle circle
pop(); // Restore previous state
pop(); // Restore original state
ellipse(100, 50, 33, 33); // Right circle
}


舞台区显示的画布内容如下:

Description

The push() function saves the current drawing style settings and transformations, while pop() restores these settings. Note that these functions are always used together. They allow you to change the style and transformation settings and later return to what you had. When a new state is started with push(), it builds on the current style and transform information. The push() and pop() functions can be embedded to provide more control. (See the second example for a demonstration.)

push() stores information related to the current transformation state and style settings controlled by the following functions: fill()noFill()noStroke()stroke()tint()noTint()strokeWeight()strokeCap()strokeJoin()imageMode()rectMode()ellipseMode()colorMode()textAlign()textFont()textSize()textLeading()applyMatrix()resetMatrix()rotate()scale()shearX()shearY()translate()noiseSeed().

In WEBGL mode additional style settings are stored. These are controlled by the following functions: setCamera()ambientLight()directionalLight()pointLight()texture()specularMaterial()shininess()normalMaterial() and shader().

Syntax

pop()

3.6. 停止持续重复执行不断画帧()内的代码


noloop()

示例:

▶️运行示例代码



function setup() {
  createCanvas(100, 100);
  background(200);
  noLoop();
}
function draw() {
  line(10, 10, 90, 90);
}

舞台区显示的画布内容如下:

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}
舞台区显示的画布内容如下:

Description

Stops p5.js from continuously executing the code within draw(). If loop() is called, the code in draw() begins to run continuously again. If using noLoop() in setup(), it should be the last line inside the block.

When noLoop() is used, it's not possible to manipulate or access the screen inside event handling functions such as mousePressed() or keyPressed(). Instead, use those functions to call redraw() or loop(), which will run draw(), which can update the screen properly. This means that when noLoop() has been called, no drawing can happen, and functions like saveFrames() or loadPixels() may not be used.

Note that if the sketch is resized, redraw() will be called to update the sketch, even after noLoop() has been specified. Otherwise, the sketch would enter an odd state until loop() was called.

Use isLooping() to check the current state of loop().

Syntax

noLoop()


3.7. 循环执行


loop()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:


Description

By default, p5.js loops through draw() continuously, executing the code within it. However, the draw() loop may be stopped by calling noLoop(). In that case, the draw() loop can be resumed with loop().

Avoid calling loop() from inside setup().

Use isLooping() to check the current state of loop().

一般情况下,p5.js的循环是通过调用draw()函数,draw()函数中的代码是持续循环执行的。然而,通过调用noLoop()函数可以停止draw()函数的循环执行。当循环中止的情况下,可以使用loop()来恢复draw()函数的循环执行。

避免从setup()函数内部调用loop()函数。

使用isLooping()函数检查loop()函数的当前状态。

Syntax

loop()


4.1. 创建画布


createCanvas()

示例:

▶️运行示例代码



function setup() {
  createCanvas(100, 50);
  background(153);
  line(0, 0, width, height);
}
舞台区显示的画布内容如下:


Description

Creates a canvas element in the document and sets its dimensions in pixels. This method should be called only once at the start of setup(). Calling createCanvas more than once in a sketch will result in very unpredictable behavior. If you want more than one drawing canvas you could use createGraphics() (hidden by default but it can be shown).

Important note: in 2D mode (i.e. when p5.Renderer is not set) the origin (0,0) is positioned at the top left of the screen. In 3D mode (i.e. when p5.Renderer is set to WEBGL), the origin is positioned at the center of the canvas. See this issue for more information.

The system variables width and height are set by the parameters passed to this function. If createCanvas() is not used, the window will be given a default size of 100×100 pixels.

For more ways to position the canvas, see the positioning the canvas wiki page.

Syntax

createCanvas(w, h, [renderer])

Parameters

  • w
     
    Number: 

    width of the canvas

  • h
     
    Number: 

    height of the canvas

  • renderer
     
    Constant: 

    either P2D or WEBGL

     (Optional)

Returns

p5.Renderer: pointer to p5.Renderer holding canvas


4.2. 缩放画布


resizeCanvas()

示例:

▶️运行示例代码



function setup() {
  createCanvas(windowWidth, windowHeight);
}
function draw() {
  background(0, 100, 200);
}
function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}

舞台区显示的画布内容如下:


Description

Resizes the canvas to given width and height. The canvas will be cleared and draw will be called immediately, allowing the sketch to re-render itself in the resized canvas.

Syntax

resizeCanvas(w, h, [noRedraw])

Parameters

  • w
     
    Number: 

    width of the canvas

  • h
     
    Number: 

    height of the canvas

  • noRedraw
     
    Boolean: 

    don't redraw the canvas immediately

     (Optional)


4.3. 移除画布


noCanvas()

示例:

▶️运行示例代码



function setup(){
  noCanvas();
};


Description

Removes the default canvas for a p5 sketch that doesn't require a canvas

Syntax

noCanvas()


4.4. 画布存为图像


saveCanvas()

示例:

▶️运行示例代码



function setup(){
  createCanvas(100,100);
  background('#ff0000');
  saveCanvas('myCanvas', 'jpg');
};
舞台区显示的画布内容如下:


Description

Save the current canvas as an image. The browser will either save the file immediately, or prompt the user with a dialogue window.

Syntax

saveCanvas(selectedCanvas, [filename], [extension])
saveCanvas([filename], [extension])

Parameters

  • selectedCanvas
     
    p5.Element|HTMLCanvasElement: 

    a variable representing a specific html5 canvas (optional)

  • filename
     
    String: (Optional)
  • extension
     
    String: 

    'jpg' or 'png'

     (Optional)



4.5. 画布渲染环境


 drawingContext

示例:

▶️运行示例代码



function setup(){
  drawingContext.shadowOffsetX = 5;
  drawingContext.shadowOffsetY = -5;
  drawingContext.shadowBlur = 10;
  drawingContext.shadowColor = '#000000';
  background('#c8c8c8');
  ellipse(((width) / 2),((height) / 2),50,50);
};

舞台区显示的画布内容如下:


Description

The p5.js API provides a lot of functionality for creating graphics, but there is some native HTML5 Canvas functionality that is not exposed by p5. You can still call it directly using the variable drawingContext, as in the example shown. This is the equivalent of calling canvas.getContext('2d'); or canvas.getContext('webgl');. See this reference for the native canvas API for possible drawing functions you can call.

p5.js的API提供了很多创建图形的函数,但是没有包含一些原生的HTML5画布函数,这些函数仍然可以通过直接使用变量来调用drawingContext,具体调用函数的时候请参考原生HTML5的画布API。

Syntax

drawingContext



4.6. 使用图形缓冲区

舞台-画布


▶️运行示例代码

4.7. 创建图形缓冲区


createGraphics()

示例:

▶️运行示例代码



var pg;
function setup(){
  createCanvas(100,100);
  pg = (createGraphics(100,100));
};

function draw(){
  background('#c8c8c8');
  pg.background('#666666');
  pg.noStroke();
  pg.ellipse((pg.width / 2), (pg.height / 2), 50, 50);
  image(pg, 50, 50);
  image(pg, 0, 0, 50, 50);
};

舞台区显示的画布内容如下:


Description

Creates and returns a new p5.Renderer object. Use this class if you need to draw into an off-screen graphics buffer. The two parameters define the width and height in pixels.

Syntax

createGraphics(w, h, [renderer])

Parameters

  • w
     
    Number: 

    width of the offscreen graphics buffer

  • h
     
    Number: 

    height of the offscreen graphics buffer

  • renderer
     
    Constant: 

    either P2D or WEBGL undefined defaults to p2d

     (Optional)

Returns

p5.Graphics: offscreen graphics buffer




4.8. 开始图形缓冲区

▶️运行示例代码


▶️运行示例代码2


p5.layers

npm version

p5.layers is a p5.js library that simplifies some common use cases for p5.js Graphics objects.

It does this by addings this functionality to p5.js:

  • A new pair of functions, beginLayer() and endLayer(), handles variable-free creation and use of a Graphics.
  • The p5.js draw and other canvas functions (e.g. rect() , fill()) operate either on the canvas, or on the current layer (p5.Graphics instance), depending on whether they are called between a call to beginLayer() / endLayer().

trail example animation trail example animation

You can find a collection of examples here.

For example:

// with p5.layer
function draw() {
  // ...
  beginLayer();
  background(100);
  fill('blue');
  circle(width / 2, height / 2, 100);
  endLayer();
}

is equivalent to:

// without p5.layer
function setup() {
  // ...
  let pg = createGraphics(100, 100);
}

function draw() {
  // ...
  pg.background(100);
  pg.fill('blue');
  pg.circle(pg.width / 2, pg.height / 2, 100);
  image(pg, 0, 0);
}

The version with beginLayer() doesn't require the use of pg. as a prefix in order to affect the created Graphics. This makes it easier to change your mind about what goes inside of a layer (or what happens in which of several layers), and to write functions that can apply to either the canvas and or a layer.

The Graphics instances that beginLayer() creates persist across calls to draw(). For example, the following code, from examples/lissajous/sketch.js, leaves a trail of circles, because the layer is only partially erased (the second argument to background() is a value that indicates partial opacity). It is drawn onto a canvas that is completely erased each frame, as required by the other code in the draw() function in that file.

  beginLayer();
  background(100, 10);
  let x = map(sin(millis() / 500), -1, 1, 0, width);
  let y = map(sin(millis() / 700), -1, 1, 0, height);
  circle(x, y, 20);
  endLayer();

The equivalent functionality, without using beginLayer() and endLayer(), would require code that is distributed among setup(), draw(), and the global context:

let pg;

function setup() {
  // ...
  pg = createGraphics(width, height);
}

function draw() {
  // ...
  pg.background(100, 10);
  let x = map(sin(millis() / 500), -1, 1, 0, pg.width);
  let y = map(sin(millis() / 700), -1, 1, 0, pg.height);
  pg.circle(x, y, 20);
  image(pg, 0, 0);
}

Installation Options

Option 1: Using a CDN

Use the online version by adding the following line to your HTML document:

<script src="https://unpkg.com/p5.layers@1"></script>

Option 2: Downloading the library file

Alternatively, download p5.layers.min.js from this repository. Include it in your HTML document by adding this line, after the line that includes p5.js or p5.min.js:

<script src="p5.layers.min.js"></script>

Option 3: Using p5-server

The p5-server command-line tool, and the P5 Server Visual Studio Code Extension, will each infer this library from the presence of call to beginLayer() in a JavaScript-only sketch (one without an HTML file).

Reference

beginLayer()

Sets the p5.js global functions background(), draw() etc. to render into the specified layer. If no layer is specified, one is created.

Syntax:

beginLayer() beginLayer([width, height, [renderer]])

The first time this function is called, it creates an instance of p5.Graphics. Subsequent calls return this instance. (If the arguments are omitted, the Graphics is created at the canvas width and height.) On subsequent calls, the width, height, and renderer arguments are ignored, and the previously-created instance is used.

beginLayer() returns the Graphics.

beginLayer(key, [width, height, renderer])

This form can be used to create multiple layers. beginLayer() will create a new layer for each distinct key. The special key value "new" always creates a new layer.

beginLayer(graphics)

This form can be used to set global draw functions to render onto a Graphics that was created by createGraphics().

endLayer()

Restores the global draw functions rect() etc. so that they operate on the canvas again, instead of the Graphics created by or passed as an argument to beginLayer(). This function also draws the Graphics onto the canvas – although this behavior can be suppressed.

Syntax:

endLayer()

Restores the global draw functions, and draws the Graphics onto the canvas unless the argument to enterGraphics() was a Graphics.

endLayer(x, y, [width, height])

Restores the global draw functions, and draws the Graphics onto the canvas.

endLayer(false)

Restores the global draw functions. Does not draw the Graphics onto the canvas.

Motivation

  1. My students in Creative Coding frequently wanted to use the equivalent of the Layers concept that is common in GUI painting and drawing programs. I found that this was a significant hurdle, both because of the terminology and the mechanics.
  2. Because the p5.Graphics functions are methods on the instance, changing code to operate on the canvas such that it instead operates p5.Graphics requires a significant amount of editing.

Caveats

  • The code only works in global mode. It does not check whether it is running in global mode.
  • The code does not validate its arguments, and does not use the p5.js Friendly Error System.
  • The code has only been tested in modern browsers.

Keeping in Touch

Report bugs, features requests, and suggestions here, or message me on Twitter.

Follow @osteele on Twitter for updates.

Other Work

p5.js Libraries lists my other p5.js libraries.

https://code.osteele.com lists my other p5.js projects. These include tools, libraries, and examples and educational materials.

License

MIT


Documentation generated by JSDoc 3.6.7 on Wed Dec 15 2021 15:48:35 GMT+0800 (China Standard Time)

4.9. 图像缓冲区像素的RGBA数组

🎞️参看p5.js像素数组

▶️示例代码

在图形缓冲区绘制图像,将图像的数据复制到Three.js的纹理上。


4.10. 结束图形缓冲区

p5.layers

参看开始图形缓冲区

endLayer()

Restores the global draw functions rect() etc. so that they operate on the canvas again, instead of the Graphics created by or passed as an argument to beginLayer(). This function also draws the Graphics onto the canvas – although this behavior can be suppressed.

Syntax:

endLayer()

Restores the global draw functions, and draws the Graphics onto the canvas unless the argument to enterGraphics() was a Graphics.

endLayer(x, y, [width, height])

Restores the global draw functions, and draws the Graphics onto the canvas.

endLayer(false)

Restores the global draw functions. Does not draw the Graphics onto the canvas.


4.11. 获取图形缓冲区图像

📖


▶️运行代码

4.12. 混合像素模式


blendMode()

示例:

▶️运行示例代码



function setup(){
  blendMode(LIGHTEST);
  strokeWeight(30);
  stroke('#3366ff');
  line(25,25,75,75);
  stroke('#ff0000');
  line(75,25,25,75);
};

舞台区显示的画布内容如下:


示例:

▶️运行示例代码



function setup(){
  blendMode(MULTIPLY);
  strokeWeight(30);
  stroke('#3366ff');
  line(25,25,75,75);
  stroke('#ff0000');
  line(75,25,25,75);
};

舞台区显示的画布内容如下:

Description

Blends the pixels in the display window according to the defined mode. There is a choice of the following modes to blend the source pixels (A) with the ones of pixels already in the display window (B):

  • BLEND - linear interpolation of colours: C = A*factor + B. This is the default blending mode.
  • ADD - sum of A and B
  • DARKEST - only the darkest colour succeeds: C = min(A*factor, B).
  • LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B).
  • DIFFERENCE - subtract colors from underlying image.
  • EXCLUSION - similar to DIFFERENCE, but less extreme.
  • MULTIPLY - multiply the colors, result will always be darker.
  • SCREEN - opposite multiply, uses inverse values of the colors.
  • REPLACE - the pixels entirely replace the others and don't utilize alpha (transparency) values.
  • REMOVE - removes pixels from B with the alpha strength of A.
  • OVERLAY - mix of MULTIPLY and SCREEN . Multiplies dark values, and screens light values. (2D)
  • HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower. (2D)
  • SOFT_LIGHT - mix of DARKEST and LIGHTEST. Works like OVERLAY, but not as harsh. (2D)
  • DODGE - lightens light tones and increases contrast, ignores darks. (2D)
  • BURN - darker areas are applied, increasing contrast, ignores lights. (2D)
  • SUBTRACT - remainder of A and B (3D)

(2D) indicates that this blend mode only works in the 2D renderer.
(3D) indicates that this blend mode only works in the WEBGL renderer.

Syntax

blendMode(mode)

Parameters

  • mode
     
    Constant: 

    blend mode to set for canvas. either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN, ADD, REMOVE or SUBTRACT



4.13. 设置绘图属性


setAttributes()

示例:

▶️运行示例代码



function setup() {
  createCanvas(100, 100, WEBGL);
}

function draw() {
  background(255);
  push();
  rotateZ(frameCount * 0.02);
  rotateX(frameCount * 0.02);
  rotateY(frameCount * 0.02);
  fill(0, 0, 0);
  box(50);
  pop();
}

舞台区显示的画布内容如下:


示例:

▶️运行示例代码



function setup() {
  setAttributes('antialias', true);
  createCanvas(100, 100, WEBGL);
}

function draw() {
  background(255);
  push();
  rotateZ(frameCount * 0.02);
  rotateX(frameCount * 0.02);
  rotateY(frameCount * 0.02);
  fill(0, 0, 0);
  box(50);
  pop();
}

舞台区显示的画布内容如下:



示例:

▶️运行示例代码



// press the mouse button to disable perPixelLighting
function setup() {
  createCanvas(100, 100, WEBGL);
  noStroke();
  fill(255);
}

let lights = [
  { c: '#f00', t: 1.12, p: 1.91, r: 0.2 },
  { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 },
  { c: '#00f', t: 1.37, p: 1.57, r: 0.2 },
  { c: '#ff0', t: 1.12, p: 1.91, r: 0.7 },
  { c: '#0ff', t: 1.21, p: 1.31, r: 0.7 },
  { c: '#f0f', t: 1.37, p: 1.57, r: 0.7 }
];

function draw() {
  let t = millis() / 1000 + 1000;
  background(0);
  directionalLight(color('#222'), 1, 1, 1);

  for (let i = 0; i < lights.length; i++) {
    let light = lights[i];
    pointLight(
      color(light.c),
      p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r)
    );
  }

  specularMaterial(255);
  sphere(width * 0.1);

  rotateX(t * 0.77);
  rotateY(t * 0.83);
  rotateZ(t * 0.91);
  torus(width * 0.3, width * 0.07, 24, 10);
}

function mousePressed() {
  setAttributes('perPixelLighting', false);
  noStroke();
  fill(255);
}
function mouseReleased() {
  setAttributes('perPixelLighting', true);
  noStroke();
  fill(255);
}

舞台区显示的画布内容如下:



Description

Set attributes for the WebGL Drawing context. This is a way of adjusting how the WebGL renderer works to fine-tune the display and performance.

Note that this will reinitialize the drawing context if called after the WebGL canvas is made.

If an object is passed as the parameter, all attributes not declared in the object will be set to defaults.

The available attributes are:
alpha - indicates if the canvas contains an alpha buffer default is false

depth - indicates whether the drawing buffer has a depth buffer of at least 16 bits - default is true

stencil - indicates whether the drawing buffer has a stencil buffer of at least 8 bits

antialias - indicates whether or not to perform anti-aliasing default is false (true in Safari)

premultipliedAlpha - indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha default is false

preserveDrawingBuffer - if true the buffers will not be cleared and and will preserve their values until cleared or overwritten by author (note that p5 clears automatically on draw loop) default is true

perPixelLighting - if true, per-pixel lighting will be used in the lighting shader otherwise per-vertex lighting is used. default is true.

Syntax

setAttributes(key, value)
setAttributes(obj)

Parameters

  • key
     
    String: 

    Name of attribute

  • value
     
    Boolean: 

    New value of named attribute

  • obj
     
    Object: 

    object with key-value pairs




4.14. 滤镜

除了使用颜色和透明度外,还有几种滤镜可用于实现特殊的颜色效果,例如,滤镜(GRAY)(将颜色转换为灰度)、滤镜(INVERT)(反转颜色)、滤色器(POSTERIZE)(减少颜色数量)或滤镜(BLUR)(模糊图像)。通过赋予这些过滤器不同的值,它们产生了惊人的创造性效果。

注意,有些滤镜(比如BLUR)需要指定一个参数才能生效。


💻 🔗filter()

5.1. 背景色


background()

示例:

▶️运行示例代码



function setup(){
  createCanvas(100,100);
  colorMode(RGB);
};

function draw(){
  background('#ff0000');
  noStroke();
  fill([0, 100, 0, 80]);
  ellipse(50,50,50,50);
};

舞台区显示的画布内容如下:

Description

The background() function sets the color used for the background of the p5.js canvas. The default background is transparent. This function is typically used within draw() to clear the display window at the beginning of each frame, but it can be used inside setup() to set the background on the first frame of animation or if the background need only be set once.

The color is either specified in terms of the RGB, HSB, or HSL color depending on the current colorMode. (The default color space is RGB, with each value in the range from 0 to 255). The alpha range by default is also 0 to 255.

If a single string argument is provided, RGB, RGBA and Hex CSS color strings and all named color strings are supported. In this case, an alpha number value as a second argument is not supported, the RGBA form should be used.

p5.Color object can also be provided to set the background color.

p5.Image can also be provided to set the background image.

Syntax

background(color)
background(colorstring, [a])
background(gray, [a])
background(v1, v2, v3, [a])
background(values)
background(image, [a])

Parameters

  • color
     
    p5.Color

    any value created by the color() function

  • colorstring
     
    String: 

    color string, possible formats include: integer rgb() or rgba(), percentage rgb() or rgba(), 3-digit hex, 6-digit hex

  • a
     
    Number: 

    opacity of the background relative to current color range (default is 0-255)

     (Optional)
  • gray
     
    Number: 

    specifies a value between white and black

  • v1
     
    Number: 

    red or hue value (depending on the current color mode)

  • v2
     
    Number: 

    green or saturation value (depending on the current color mode)

  • v3
     
    Number: 

    blue or brightness value (depending on the current color mode)

  • values
     
    Number[]: 

    an array containing the red, green, blue and alpha components of the color

  • image
     
    p5.Image

    image created with loadImage() or createImage(), to set as background (must be same size as the sketch window)





5.2. 形状填充颜色


fill()

示例:

▶️运行示例代码



function setup(){
  createCanvas(100,100);
  colorMode(HSB);
};

function draw(){
  background('#c0c0c0');
  fill(color(180,100,100,100));
  rect(20,20,60);
};

舞台区显示的画布内容如下:


Description

Sets the color used to fill shapes. For example, if you run fill(204, 102, 0), all shapes drawn after the fill command will be filled with the color orange. This color is either specified in terms of the RGB or HSB color depending on the current colorMode(). (The default color space is RGB, with each value in the range from 0 to 255). The alpha range by default is also 0 to 255.

If a single string argument is provided, RGB, RGBA and Hex CSS color strings and all named color strings are supported. In this case, an alpha number value as a second argument is not supported, the RGBA form should be used.

p5.Color object can also be provided to set the fill color.

Syntax

fill(v1, v2, v3, [alpha])
fill(value)
fill(gray, [alpha])
fill(values)
fill(color)

Parameters

  • v1
     
    Number: 

    red or hue value relative to the current color range

  • v2
     
    Number: 

    green or saturation value relative to the current color range

  • v3
     
    Number: 

    blue or brightness value relative to the current color range

  • alpha
     
    Number: (Optional)
  • value
     
    String: 

    a color string

  • gray
     
    Number: 

    a gray value

  • values
     
    Number[]: 

    an array containing the red,green,blue & and alpha components of the color

  • color
     
    p5.Color

    the fill color





5.3. 形状的外形线色


stroke()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





5.4. 设置每秒帧数


frameRate()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





5.5. 禁用形状的外形线


noStroke()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





5.6. 禁用形状填充


noFill()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





5.7. 遮罩

从画布中移除之后绘制的图形所占区域。

▶️运行示例代码




erase()

5.9. 渐变

线性渐变


▶️运行示例代码



fillGradient()

径向渐变



5.10. 清除画布


clear()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





5.11. 颜色模式


colorMode()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:




5.12. 设置鼠标符号


cursor()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





5.13. 隐藏鼠标


noCursor()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





5.15. 坐标系网格

▶️运行示例




在坐标系网格的显示之前,可设置两种颜色:
  1. 外形线色,影响定位点的“+”线条颜色
  2. 填充颜色,影响定位点数值的文本颜色
启用鼠标定位:
  • 在画布上点击,会留下一个定位点,并显示其位置数据
启用键盘命令:
  • 按空格,清除所有定位点
  • 按s键,保存画布截图
  • 按h键,改变定位显示方式
  • 按e键,将定位点的数据输出到开发者控制终端(Console)。

6.1. 输出


preload()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





6.2. 帧总数


frameCount

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





6.3. 毫秒数


millis()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





6.4. 帧间隔秒数


deltaTime

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





6.5. 当前窗口是否获得焦点


focused

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





6.6. 每秒帧数


frameRate()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





6.7. 画布宽度


width

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





6.8. 画布高度


height

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





6.9. 窗口宽度


windowWidth

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





6.10. 窗口高度


windowHeight

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





6.11. 屏幕宽度


displayWidth

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





6.12. 屏幕高度


displayHeight

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





6.13. 设置像素密度


pixelDensity()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





7.1. 加载画布的像素资料


loadPixels()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





7.2. 更新画布的像素


updatePixels()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





7.3. 画布像素


pixels

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





7.4. 画布设置像素


set()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





7.5. 画布获取像素xy


get()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





7.6. 画布获取图像


get()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





7.7. 画布获取部分图像


get()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





7.8. 画布像素字节


pixels

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





7.9. 画布设置像素通道


pixels

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





7.10. 画布设置像素


pixels

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





7.11. 画布复制像素


copy()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





7.12. 混合像素


blend()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下:





7.13. 画布过滤器


filter()

示例:

▶️运行示例代码



let x = 0;
function setup() {
  createCanvas(100, 100);
}
function draw() {
  background(204);
  x = x + 0.1;
  if (x > width) {
    x = 0;
  }
  line(x, 0, x, height);
}
function mousePressed() {
  noLoop();
}
function mouseReleased() {
  loop();
}

舞台区显示的画布内容如下: