Skip to content

Canvas3D

Freddie R edited this page Jun 3, 2019 · 5 revisions

Canvas3D

Canvas3D

This is the last current implementation of Object3D, and by far the most general.

This you directly pass an existing p5.graphic object in. This means if you are currently creating a p5.graphic object to render a 2D canvas as a texture in WebGL (a common workaround to take advantage of functions like text()), you can keep the code that creates the canvas and then pass it into a Canvas3D object to render it in 3D instead.

This also means you can create shapes and patterns in 3D and then turn them into 3D.

Example: https://www.openprocessing.org/sketch/673354

(Note: The example shown doesn't use the exact code shown here as it was created during development, but gives an example of the kind of thing that can be created)

Usage

An instance should be created in "setup()" after the canvas has been created like this:

canvasObject = createCanvas3D(
  canvas,      // The p5.Graphics object
  depth,        // How thick the 3D rendered image is (i.e. how many cube pixels of size "size" it is on z-axis)  
  size,         // The size of a unit "box()" making up part of the image  
  resolution,   // A scaling factor (0.1 scales the canvas by 0.1 to reduce detail, 1 is the full scale, 0.4 is a good default) 
  bevelled,     // [OPTIONAL, default = true] Gives the bevelled, embossed 3D look (as seen in screenshot)  
)

To render it you then call it in "draw()" like this:

canvasObject.show()

Code

p5.prototype.Canvas3D = function(p, canvas, depth, size, resolution, bevelled) {
    this.canvas = canvas;
    this.threshold = 60; // Magic number good for canvases

    this.create = function() {
        return this.canvas;
    }

    p5.prototype.Object3D.call(this, p, depth, size, resolution, bevelled, this.threshold);

    // Redefine the resolution as a scaling of the width and height
    this.resX = this.canvas.width*resolution;
    this.resY = this.canvas.height*resolution;

    // Create the array using its own "create()" and Object3D's "toArray()"
    this.array = this.toArray(this.create());
    this.rects = p5.prototype.getRects(this.array, this.bevelled);
}

p5.prototype.createCanvas3D = function(picture, depth = 6, size = 10, resolution = 50, bevelled = false) {
    return new p5.prototype.Canvas3D(p = this, picture, depth, size, resolution, bevelled);
}
Clone this wiki locally