CanvasOffscreenBuffer

CanvasOffscreenBuffer

This is a utility class used to create an off-screen
canvas for image manipulation.

var CanvasOffscreenBuffer = require('paraviewweb/src/Common/Misc/CanvasOffscreenBuffer'),
instance = new CanvasOffscreenBuffer(100, 100);

constructor(width, height)

Create a canvas and add it to the DOM as a child of the
<body/> element.

size([width, [height]]) : [ width, height ]

Return the actual canvas size if used without any argument.

If the width and height arguments are provided, this will update the canvas
width and height attributes.

// Get size
var size = instance.size();

// Update size
instance.size(200,500);

get2DContext()

Returns the 2D context of the given canvas.

var ctx = instance.get2DContext();

ctx.fillRect(0,0,10,200);

// ...

get3DContext()

Experimental, returns the 3D WebGL context of the given canvas.

toDataURL(type=’image/png’, encoderOptions=1)

Returns a data URI containing a representation of the image in the
format specified by the type parameter (defaults to PNG). The returned image has a resolution of 96 dpi.

  • type : A string indicating the image format, the default is image/png.
  • encoderOptions : A number between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp.

destroy()

Free the internal resources and remove the DOM element from the tree.

Source

index.js
let offscreenCanvasCount = 0;

// Create <canvas/> within the DOM
/* global document */
export default class CanvasOffscreenBuffer {
constructor(width, height) {
offscreenCanvasCount += 1;
this.id = `CanvasOffscreenBuffer_${offscreenCanvasCount}`;
this.el = document.createElement('canvas');
this.width = width;
this.height = height;

this.el.style.display = 'none';
this.el.setAttribute('width', this.width);
this.el.setAttribute('height', this.height);

document.body.appendChild(this.el);
}

size(width, height) {
if (width) {
this.el.setAttribute('width', (this.width = width));
}
if (height) {
this.el.setAttribute('height', (this.height = height));
}
return [Number(this.width), Number(this.height)];
}

get2DContext() {
return this.el.getContext('2d');
}

get3DContext(
options = { preserveDrawingBuffer: true, premultipliedAlpha: false }
) {
return (
this.el.getContext('webgl', options) ||
this.el.getContext('experimental-webgl', options)
);
}

// Remove canvas from DOM
destroy() {
this.el.parentNode.removeChild(this.el);
this.el = null;
this.width = null;
this.height = null;
}

toDataURL(type, encoderOptions) {
return this.el.toDataURL(type, encoderOptions);
}
}