Typo / Bug in code example.
Author: umairkhan-devCreated Sep 3, 2021Updated Jul 6, 2022
Page Affected: https://developers.google.com/web/updates/2018/08/offscreen-canvas#use_offscreencanvas_in_a_worker
What needs to be done?
The section Use OffscreenCanvas in a worker contains example code. The return statement on last line of getGradientColor function is buggy. Its missing array index [3] and closing curly braces }. Also the result shown // rgba(152, 0, 104, 255 ) is slight different when I execute this function in my browser.
Current code:
// file: worker.js
function getGradientColor(percent) {
const canvas = new OffscreenCanvas(100, 1);
const ctx = canvas.getContext('2d');
const gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'blue');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, ctx.canvas.width, 1);
const imgd = ctx.getImageData(0, 0, ctx.canvas.width, 1);
const colors = imgd.data.slice(percent * 4, percent * 4 + 4);
return `rgba(${colors[0]}, ${colors[1]}, ${colors[2]}, ${colors[])`;
}
getGradientColor(40); // rgba(152, 0, 104, 255 )Suggested:
// file: worker.js
function getGradientColor(percent) {
const canvas = new OffscreenCanvas(100, 1);
const ctx = canvas.getContext('2d');
const gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'blue');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, ctx.canvas.width, 1);
const imgd = ctx.getImageData(0, 0, ctx.canvas.width, 1);
const colors = imgd.data.slice(percent * 4, percent * 4 + 4);
return `rgba(${colors[0]}, ${colors[1]}, ${colors[2]}, ${colors[3]})`;
}
getGradientColor(40); // rgba(151, 0, 103, 255)Screenshot:

Source: google/WebFundamentals