我想找到页面中所有图像的平均颜色。我正在使用 Puppeteer 启动 chromium,然后在浏览器中运行 javascript。
问题是我正在使用 Promies.all 异步计算浏览器内的所有颜色。
我想将计算出的图像颜色返回到 page.evaluate。我怎样才能做到这一点?是否可以?
以下代码不起作用,因为 imgcolors 显然没有定义,它在 Promise.all 回调中返回。
const returned = await page.evaluate(async () => {
const fac = new FastAverageColor();
const imgs = Array.from(document.querySelectorAll('img'));
const imgpromises = imgs.map(img => fac.getColorAsync(img.src));
Promise.all(imgpromises).then(imgcolors => { return imgcolors;});
return {
document:{
height: document.body.scrollHeight,
width:document.body.scrollWidth
},
imgcolors:imgcolors
};
});
Run Code Online (Sandbox Code Playgroud)
我尝试过以下操作:
Promise.all(imgpromises).then(imgcolors => {
return {
elements:elements,
document:{
height: document.body.scrollHeight,
width:document.body.scrollWidth
},
imgcolors:imgcolors
};
});
Run Code Online (Sandbox Code Playgroud)
现在我不会将数据返回到 page.evaluate puppeteer 函数。所以返回的 const 是未定义的。
怎么做?先感谢您!