Se quer calcular a cor média duma imagem uma solução é redimensionar sua imagem para o tamanho de 1 pixel e ler esse pixel.
Para criação de buffers e desenho em memória prefira utilizar OffscreenCanvas
ao invés de criar canvas on fly como fez em:
var canvas = document.createElement('canvas')
Isso porque operações gráficas podem vir a impactar negativamente a performance do sistema e quando cria um canvas com document.createElement()
esse elemento é criado no thread principal da aplicação o que pode ocasionar slowdowns em algumas aplicações mais robustas do ponto de vista gráfico. Use essa abordagem apena com polyfill caso o navegador não suporte contextos de renderização fora de tela, veja em Can I Use.
Quando possível prefira utilizar estruturas especializadas em contextos de renderização fora de tela ao invés da improvisação.
Especificamente sobre o erro que vem recebendo:
Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The source width is 0.
O erro que está recebendo indica que a imagem cujo que está tentando processar no momento em que tenta aplicar CanvasRenderingContext2D.getImageData()
está dimensionada com zero pixels de comprimento.
Com os dados pa pergunta não é possível distinguir se a causa do problema:
- Uso de fonte de imagens mal formadas.
- Uso de fonte de imagens não carregadas ou parcialmente carregas durante o processamento.
- Erros de origens desconhecida.
A não ser o problema com uso de fonte de imagens não carregadas ou parcialmente carregas durante o processamento, o uso de fonte de imagens mal formadas ou os erros de origens desconhecida não podem se tratados por essa resposta.
No caso de uso de fonte de imagens ainda não completamente carregadas faça com que sua função averageColor()
seja aplicada apenas quando a fonte de imagens esteja disponível.
Uma forma bastante direta seria adiar a execução de todo seu script até que todas as imagens estejam carregadas usando o evento Window: load
.
window.addEventListener('load', (e) => {
function averageColor(imgElem) {
const canvas = new OffscreenCanvas(1, 1); //var canvas = document.createElement('canvas')
const ctx = canvas.getContext("2d");
ctx.drawImage(imgElem, 0, 0, 1, 1);
const imgData = ctx.getImageData(0, 0, 1, 1);
return {
r: imgData.data[0],
g: imgData.data[1],
b: imgData.data[2]
};
}
const imagem = document.getElementById("imagem");
console.log(averageColor(imagem));
});
<img id="imagem" src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD//gA+Q1JFQV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Sa3lCjk5TPH9a9MTTkjuCbO5ibDfKN4P8AOtl7Ca5j8m5iImT7rKcg/Q/0q/bRjpLVfiaUl0mtPLc+edW8IXdukc/lM0MgyJIwWAqnp2hXxmKMkbQ56l9uP6ivo+z0v7Ckhu4Vkt8/MuOPrg1x3iTTNNTUBcWTSuz5zEo2gE+pHb2FZwjCdT3SpR928Xc43S7O4nu0iS2eZP44y3AHQ+wrs7bwho9mTLcBpFflIw33f8+9Jpmjx2MbXF87J5i8QRNhmH+0eoH60XWqvDdywSwSCVf4SMBRXVyucuWByzqVIv8AdmwsmmWpYlAjSvvYLwSaz7bSrS0+0HTrgxtPIZDv9zwPoKxZJ5JZTJtEa/xSP/Son1yCP5I5Gc+o5rX6s4631Ko1ak3Zo//Z"
/>
Outra possibilidade seria tornar sua função averageColor()
em uma função assíncrona e aguarda o carregamento total da fonte de imagem a ser processada até que uma Promise seja realizada ou rejeitada:
function waitForImage(imgElem) {
return new Promise((res, rej) => {
if (imgElem.complete) {
return res();
}
imgElem.onload = () => res();
imgElem.onerror = () => rej(imgElem);
});
}
async function averageColor(imgElem) {
await waitForImage(imgElem);
const canvas = new OffscreenCanvas(1, 1); //var canvas = document.createElement('canvas')
const ctx = canvas.getContext("2d");
ctx.drawImage(imgElem, 0, 0, 1, 1);
const imgData = ctx.getImageData(0, 0, 1, 1);
return {
r: imgData.data[0],
g: imgData.data[1],
b: imgData.data[2]
};
}
const imagem = document.getElementById("imagem");
averageColor(imagem).then(c => {
console.log(c);
})
<img id="imagem" src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD//gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBkZWZhdWx0IHF1YWxpdHkK/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZEhMPFB0aHx4dGhwcICQuJyAiLCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy/9sAQwEJCQkMCwwYDQ0YMiEcITIyMjIyMj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