optimize: downscale the image *before* drawing it to the canvas.
This commit is contained in:
parent
c7ee75429d
commit
7516df9278
1 changed files with 18 additions and 21 deletions
|
|
@ -67,29 +67,26 @@ export function getVibrantColorFromImage(imgElement) {
|
||||||
const ctx = canvas.getContext('2d');
|
const ctx = canvas.getContext('2d');
|
||||||
if (!ctx) return null;
|
if (!ctx) return null;
|
||||||
|
|
||||||
canvas.width = imgElement.naturalWidth || imgElement.width;
|
|
||||||
canvas.height = imgElement.naturalHeight || imgElement.height;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ctx.drawImage(imgElement, 0, 0);
|
|
||||||
|
|
||||||
// Downscale for performance if image is large
|
|
||||||
const maxDimension = 64;
|
const maxDimension = 64;
|
||||||
if (canvas.width > maxDimension || canvas.height > maxDimension) {
|
let w = imgElement.naturalWidth || imgElement.width;
|
||||||
const scale = Math.min(maxDimension / canvas.width, maxDimension / canvas.height);
|
let h = imgElement.naturalHeight || imgElement.height;
|
||||||
const w = Math.floor(canvas.width * scale);
|
|
||||||
const h = Math.floor(canvas.height * scale);
|
if (w > maxDimension || h > maxDimension) {
|
||||||
const smallCanvas = document.createElement('canvas');
|
const scale = Math.min(maxDimension / w, maxDimension / h);
|
||||||
smallCanvas.width = w;
|
w = Math.floor(w * scale);
|
||||||
smallCanvas.height = h;
|
h = Math.floor(h * scale);
|
||||||
smallCanvas.getContext('2d').drawImage(imgElement, 0, 0, w, h);
|
|
||||||
ctx.drawImage(smallCanvas, 0, 0, canvas.width, canvas.height);
|
|
||||||
// Actually, better to just use the small canvas data
|
|
||||||
var imageData = smallCanvas.getContext('2d').getImageData(0, 0, w, h);
|
|
||||||
} else {
|
|
||||||
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
canvas.width = w;
|
||||||
|
canvas.height = h;
|
||||||
|
|
||||||
|
// Draw image directly at small size
|
||||||
|
// Note: For best quality downscaling, one might step down, but for color extraction,
|
||||||
|
// direct browser downscaling is sufficient and much faster/lighter.
|
||||||
|
ctx.drawImage(imgElement, 0, 0, w, h);
|
||||||
|
|
||||||
|
const imageData = ctx.getImageData(0, 0, w, h);
|
||||||
const pixels = imageData.data;
|
const pixels = imageData.data;
|
||||||
const candidates = [];
|
const candidates = [];
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue