使用html2canvas进行网页图片的截图(涉及跨域)

/ 前端 / 没有评论 / 236浏览

将该网页使用nginx解析,访问地址为https://www.ceshi.com/copy, 但是网页中的图片地址是 https://www.other.com/upload/xxx.png ,所以出现了图片跨域问题,是无法进行截图的,于是使用nginx对图片进行反向代理解决;

1.nginx配置反向代理

nginx配置:

        location /copy {
            alias /root/vod;
            index index.html;
            try_files $uri $uri/ @router;
        }

        location /upload {
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_pass https://www.other.com/upload;

        }

2.编写网页代码

网页源码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./html2canvas.min.js"></script>

    <style>
        img {
            width: 300px;
            height: 300px;
        }
    </style>
</head>
<body>

<img src="https://ceshi/upload/xxx.png" id="source">

<img src="" id="target">

<script>
    var copy = () => {
        html2canvas(source).then(function (canvas) {
            var img = canvas.toDataURL("image/png");
            document.querySelector("#target").src = img
        })
    }

    var source = document.querySelector("#source");
    if (source.complete) {
        copy()
    }

    source.onload = function () {
        copy()
    }
</script>
</body>
</html>