addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
// Get the image URL from the query string
const url = new URL(request.url);
const imageUrl = url.searchParams.get('url');
// Fetch the original image
const response = await fetch(imageUrl);
const blob = await response.blob();
// Create a canvas and draw the original image on it
const img = new Image();
img.src = URL.createObjectURL(blob);
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
// Generate a random color tint
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
const tint = `rgb(${r}, ${g}, ${b})`;
// Draw a transparent rect to cover the entire canvas, then set the
// composite operation to "source-atop" so that only the tinted areas
// are visible
ctx.fillStyle = tint;
ctx.globalCompositeOperation = 'source-atop';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Convert the canvas to a blob and return it as the response
const tintedBlob = await new Promise((resolve) => {
canvas.toBlob(resolve, 'image/png');
});
const tintedResponse = new Response(tintedBlob);
tintedResponse.headers.set('Content-Type', 'image/png');
tintedResponse.headers.set('Content-Disposition', 'inline');
return tintedResponse
}