I ran into an issue when using https://www.npmjs.com/package/fast-average-color or any other color library for that matter.
I’m trying to calculate average color from an already loaded image.
All images load on my website just fine, because I have CORS configured properly in the backend.
Surprisingly, using this library yields the following errors:
_slug_.c3743e61.js:56 Error: FastAverageColor: security error (CORS)
for resource https://api.mypage.com/assets/get/310fffca-a463-40ed-ad2e-4d41cee2a1eb.
_slug_.c3743e61.js:57 DOMException: Failed to execute 'getImageData' on
'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
I’m a bit flabbergasted, as this issue happens nowhere else throughout my app but this specific instance where I use the library.
Here’s the image element I’m feeding it:
<img
:src='src'
@load='setBackground'
>
Here’s my implementation of the function:
async getAverageColor(img: HTMLImageElement): Promise<IColor>
{
const color = await fac.getColor(img);
return (
{
r: color.value[0],
g: color.value[1],
b: color.value[2],
a: color.value[3]
}
);
}
Additionally, I’m using nginx as a reverse proxy and haven’t had any issues with CORS before.
I’m out of options, any help is appreciated.
2
Answers
From MDN Web Docs:
And fast-average-color, the library in question, uses
drawImage
under the hood.Adding a
crossorigin
attribute to yourimg
an element would solve your issue (under the assumption that the resource in question be configured for CORS). The library’s README has a section about this.Displaying an image across origins doesn’t require permission using CORS (and won’t invoke the CORS mechanisms (such as the
Origin
request header) by default).Reading the image data into JavaScript and processing it does require permission using CORS.
The purpose of fast-average-color is to read the image data into JavaScript and calculate the average or dominant color. That is processing and therefore requires permission using CORS.
You can use the
crossorigin
attribute on the<img>
element to tell the browser that you want to load it with CORS permissions (this will add theOrigin
request header when the image is loaded). (Obviously this requires that the server set theAccess-Control-Allow-Origin
header in the response).