feat: Change RandomPixelCanvas

RandomPixelCanvas is now RandomPixelPlaceholder and can also output an img element.
This commit is contained in:
sthag 2026-04-05 12:15:38 +02:00
parent 31457088da
commit 9fc463393e

View file

@ -559,28 +559,59 @@ const delay = ms => new Promise(res => setTimeout(res, ms));
class RandomPixelCanvas { class RandomPixelCanvas {
constructor(containerElement, options = {}) { constructor(containerElement, options = {}) {
this.container = containerElement; this.container = containerElement;
class RandomPixelPlaceholder {
constructor(parent, options = {}) {
this.container = parent;
this.width = options.width || 400; this.width = options.width || 400;
this.height = options.height || 300; this.height = options.height || 300;
this.colors = options.colors || ['#000000', '#ffffff']; this.colors = options.colors || ['#000000', '#ffffff'];
this.filter = options.filter || ''; this.filter = options.filter || '';
this.canvas = this.createCanvas(); this.type = options.type || 'canvas'; // 'canvas' or 'img'
this.element = this.createElement();
this.fillWithRandomPixels(); this.addContextToElement();
} }
createCanvas() { createElement() {
const canvas = document.createElement('canvas'); if (this.type === 'img') {
canvas.width = this.width; const img = document.createElement('img');
canvas.height = this.height; img.style.filter = this.filter;
canvas.style.filter = this.filter;
this.container.appendChild(canvas); this.container.appendChild(img);
return canvas; return img;
} else {
const canvas = document.createElement('canvas');
canvas.width = this.width;
canvas.height = this.height;
canvas.style.filter = this.filter;
this.container.appendChild(canvas);
return canvas;
}
} }
fillWithRandomPixels() { addContextToElement() {
const ctx = this.canvas.getContext('2d'); if (this.type === 'img') {
// Create intermediate canvas
const canvas = document.createElement('canvas');
canvas.width = this.width;
canvas.height = this.height;
this.fillWithRandomPixels(canvas);
// Convert canvas to image data URL and set as img src
this.element.src = canvas.toDataURL();
this.element.width = this.width;
this.element.height = this.height;
} else {
this.fillWithRandomPixels(this.element);
}
}
fillWithRandomPixels(canvas) {
const ctx = canvas.getContext('2d');
const imageData = ctx.createImageData(this.width, this.height); const imageData = ctx.createImageData(this.width, this.height);
const data = imageData.data; const data = imageData.data;