Implement a more performant drawing method.

Instead of drawing opaque triangle contours on an empty canvas and
iterating overt its pixels to invert the opacity, use the
globalCompositeOperation property of the canvas to fill the canvas with
white, and draw "transparent" triangle contours.
This commit is contained in:
Daru13 2019-04-23 02:20:15 +02:00
parent c29f95d6a2
commit e51a59b738

View file

@ -36,10 +36,10 @@
const POINT_MIN_Y_SPEED = 0.15;
const POINT_MAX_Y_SPEED = 0.3;
const POINT_MIN_X_RADIUS = 0.5;
const POINT_MIN_X_RADIUS = 1;
const POINT_MAX_X_RADIUS = 2;
const POINT_MIN_Y_RADIUS = 0.5;
const POINT_MIN_Y_RADIUS = 1;
const POINT_MAX_Y_RADIUS = 2;
// Canvas update halting
@ -104,11 +104,19 @@
}
// Draw certain lines between all points to form contours of triangles
function drawTriangleContours () {
// Width of the contours
// Draw white triangles with transparent contours
function drawTriangles () {
// Style of the drawing
context.fillStyle = "#FFFFFF";
context.lineWidth = 3;
// Fill the canvas with a white background...
context.globalCompositeOperation = "source-over";
context.fillRect(0, 0, WIDTH, HEIGHT);
// ...and erase the contours of the triangles
context.globalCompositeOperation = "destination-out";
for (let row = 0; row < NB_POINTS_PER_COL; row++) {
for (let col = 0; col < NB_POINTS_PER_ROW; col++) {
// Nothing to do with the last point of each row
@ -147,27 +155,6 @@
}
// Transform the triangle contours into plain white triangles
// by iterating over the pixels of the canvas image data
function fillTrianglesAndEmptyContours () {
const currentImageData = context.getImageData(0, 0, WIDTH, HEIGHT);
const currentData = currentImageData.data;
const newImageData = context.createImageData(WIDTH, HEIGHT);
const newData = newImageData.data;
const dataLength = currentData.length;
for (i = 0; i < dataLength; i += 4) {
newData[i + 0] = 255;
newData[i + 1] = 255;
newData[i + 2] = 255;
newData[i + 3] = 255 - currentData[i + 3];
}
context.putImageData(newImageData, 0, 0);
}
/*--------------------------------------------------------*/
@ -244,11 +231,8 @@
return;
}
// Clear the canvas and repeat the drawing process
context.clearRect(0, 0, WIDTH, HEIGHT);
drawTriangleContours();
fillTrianglesAndEmptyContours();
// Repeat the drawing process
drawTriangles();
window.requestAnimationFrame(updateCanvas);
}