基于koa,puppeteer实现网页不同尺寸截图

对网页不同尺寸进行截图,检查在不同尺寸下网页ui是否有错误。
在这里插入图片描述
在这里插入图片描述
该demo基于koa.jspuppeteer.js
接口实现:

index.js

const Koa = require('koa');
const app = new Koa;
// 允许跨域
const cors = require('koa2-cors');
app.use(cors());
// 静态资源
const path = require('path')
const koaStatic = require('koa-static')
app.use(koaStatic(path.join(__dirname, './src/assets/')))
// 路由中间件
const userRoute = require('./src/router');
app.use(userRoute.routes()).use(userRoute.allowedMethods());// allowedMethods 405响应和501响应

app.listen(3000, () => {
    console.log('Service running: http://127.0.0.1:3000');
})
module.exports = app;

/router/index.js:

const Router = require('koa-router');
const router = new Router();
const KoaBody = require('koa-body');

// 获取图片
router.get('/getJpeg', auth, async (ctx) => {
    const getPdf = require('../views/getJpeg');
    ctx.body = JSON.stringify(await getJpeg(ctx));
})

module.exports = router;

/views/getJpeg.js:

const puppeteer = require('puppeteer');

function delay(time) {
    return new Promise(res => setTimeout(res, time))
}
// 滚动到底
function autoScroll(page) {
    return page.evaluate(() => {
        return new Promise((resolve, reject) => {
            var totalHeight = 0;
            var distance = 500;
            var timer = setInterval(() => {
                var scrollHeight = document.body.scrollHeight;
                window.scrollBy(0, distance);
                totalHeight += distance;
                if (totalHeight >= scrollHeight) {
                    clearInterval(timer);
                    resolve(totalHeight);
                }
            }, 17);
        })
    });
}

const sc = [
    { width: 800, height: 600 },
    { width: 1024, height: 768 },
    { width: 1280, height: 960 },
    { width: 1440, height: 900 },
    { width: 1680, height: 1050 },
    { width: 1920, height: 1200 },
    { width: 2560, height: 1440 },
    { width: 3840, height: 2160 },
]
async function getJpegStart(url, scarr, quality = 50) {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(url, {
        waitUntil: 'networkidle0'
    });
    await delay(3000) //等待3秒让页面渲染dom
    let pathArr = [];
	// 截取图片
    async function sh() {
        if (!scarr.length) return
        await page.setViewport(sc[scarr[0]]);
        let height = await autoScroll(page);
        let u = url.replace(':', '_').replace(/\./g, '_').replace(/\//g, '');
        await page.screenshot({
            path: 'src/assets/' + sc[scarr[0]].width + '_' + sc[scarr[0]].height + '(' + u + ')' + '.jpeg',
            clip: {
                x: 0,
                y: 0,
                width: sc[scarr[0]].width,
                height: height,
            },
            quality
        });
        pathArr.push({
            src: sc[scarr[0]].width + '_' + sc[scarr[0]].height + '(' + u + ')' + '.jpeg',
            size: sc[scarr[0]].width + '*' + sc[scarr[0]].height,
            name: sc[scarr[0]].width + '_' + sc[scarr[0]].height + '(' + u + ')'
        });
        scarr.shift();
        await sh();
    }
    await sh()

    await browser.close()
    return pathArr
}

async function getJpeg(ctx, id) {
    let res;
    let url = ctx.query.url;
    let quality = Number(ctx.query.quality);
    let sc = []; // 尺寸索引 传入的值格式为: sc=1,3,5
    ctx.query.sc.split(',').forEach(function (v) { sc.push(Number(v)) })
    let pathArr = await getJpegStart(url, sc, quality);
    
    if (pathArr.length) {
        pathArr.forEach(function (v) {
            v.src = 'http://' + ctx.host + '/' + v.src;
        })
        res = {
            status: 1,
            data: pathArr
        }
    } else {
        res = {
            status: 0,
            data: null,
            msg: '目标链接访问失败'
        }
    }
    return res
}

module.exports = getJpeg;

最后推荐一个前端开发好用的导航网站:www.888i8.cn

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值