Skip to content

Instantly share code, notes, and snippets.

@fi-tomek-augustyn
Last active October 12, 2015 04:48
Show Gist options
  • Save fi-tomek-augustyn/3973048 to your computer and use it in GitHub Desktop.
Save fi-tomek-augustyn/3973048 to your computer and use it in GitHub Desktop.
Offscreen canvas buffer example
var buffers = [];
drawLightBlob(ctx, 255, 0, 0, 300, 300, 100);
/**
* Draw a blob of light (with offscreen canvas buffering)
*/
function drawLightBlob(ctx, r, g, b, x, y, radius) {
var buffer,
bufferCanvas,
gradient,
id,
colorStop;
// Create an unique ID for the color
id = colorString.split(',').join('');
if (this.buffers[id] != null) {
// Buffer found for this color, so retrieve it
bufferCanvas = this.buffers[id];
} else {
// Buffer not found, so we have to create one
bufferCanvas = document.createElement('canvas');
bufferCanvas.width = radius * 2;
bufferCanvas.height = radius * 2;
buffer = bufferCanvas.getContext('2d');
buffer.beginPath();
// Create radial gradient
gradient = buffer.createRadialGradient(
radius,
radius,
0,
radius,
radius,
radius
);
gradient.addColorStop(0, "rgba(255, 255, 255, 1)");
colorStop = "rgba(" + r + ", " + g + ", " + b + ", 0)";
gradient.addColorStop(0.7, colorStop);
// And draw a circle filled with it
buffer.fillStyle = gradient;
buffer.arc(radius, radius, radius, Math.PI * 2, false);
buffer.closePath();
buffer.fill();
// Store the buffer
this.buffers[id] = bufferCanvas;
}
// Finally, draw the buffer onto main canvas' context
ctx.globalCompositeOperation = 'lighter';
ctx.drawImage(bufferCanvas, x - radius, y - radius);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment