laravel 如何使用外部图像生成html div的“屏幕截图”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41254805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:58:02  来源:igfitidea点击:

How to generate "screenshot" of html div with external images?

javascriptphphtmllaravelhtml2canvas

提问by cytsunny

I have a HTML div with external images. (The following is an example, but in the actual case I am using Amazon S3, so downloading and storing the image on the same server is not an option) Currently I am using html2canvasto convert the div to image. However, the external image is always replaced by a blank space.

我有一个带有外部图像的 HTML div。(以下是一个示例,但在实际情况下,我使用的是 Amazon S3,因此无法将图像下载并存储在同一台服务器上)目前我正在使用html2canvas将 div 转换为图像。但是,外部图像总是被空白替换。

The code I use to capture the image:

我用来捕获图像的代码:

$(function() { 
    $("#btnSave").click(function() { 
        html2canvas($("#widget"), {
            onrendered: function(canvas) {
                theCanvas = canvas;
                document.body.appendChild(canvas);

                // Convert and download as image 
                Canvas2Image.saveAsPNG(canvas); 
                $("#img-out").append(canvas);
            }
        });
    });
}); 

Edited:jsfiddle: https://jsfiddle.net/0y2zxxL8/3/

编辑:jsfiddle:https ://jsfiddle.net/0y2zxxL8/3/

I may use other library. I may also do that in backend. (I am using PHP + laravel 5 for backend) Is there a way I can generate a "screenshot" of the HTML div with external images?

我可能会使用其他图书馆。我也可以在后端这样做。(我使用 PHP + laravel 5 作为后端)有没有办法用外部图像生成 HTML div 的“屏幕截图”?

UpdateThe current answer are working after editing. Yet, for my actual use, there will be multiple image with their position set by the user by drag and drop. I can still get the position, but it would be better for me if it is possible to not set the position specifically.

更新当前答案在编辑后有效。然而,对于我的实际使用,将会有多个图像,它们的位置由用户通过拖放设置。我仍然可以得到位置,但如果可以不专门设置位置对我来说会更好。

采纳答案by AddWeb Solution Pvt Ltd

Your JSFiddlegiven ReferenceError: Canvas2Image is not definedwhile hit on 'Save PNG' button. So check your code(not fiddle) for same error.

的jsfiddle给出ReferenceError: Canvas2Image is not defined同时命中“保存PNG”按钮。所以检查你的代码(不是小提琴)是否有同样的错误。

UPDATE
See this JSFiddleexample as reference. May this one will help you.

更新
请参阅此JSFiddle示例作为参考。愿这个对你有帮助。

UPDATE 2
I place some code into your one, check it out. Hope this will be your solution..!

更新 2
我将一些代码放入您的代码中,请查看。希望这将是您的解决方案..!

Working result with FF v44 and its working. Taken snap with JSFiddlecode enter image description here

FF v44 的工作结果及其工作。使用JSFiddle代码 拍摄在此处输入图片说明

$(function() { 
    $("#btnSave").click(function() { 
        html2canvas($("#widget"), {
            onrendered: function(canvas) {
                var context=canvas.getContext("2d"); // returns the 2d context object
                var img=new Image() //creates a variable for a new image

                img.src= "http://lorempixel.com/400/200/"; // specifies the location of the image
                context.drawImage(img,0,50); // draws the image at the specified x and y location
                // Convert and download as image 
                theCanvas = canvas;
                document.body.appendChild(canvas);

                // Convert and download as image 
                Canvas2Image.saveAsPNG(canvas); 
                $("#img-out").append(canvas);
            }
        });
    });
});

UPDATE 3(12/29/2016) JSFiddle

更新 3(12/29/2016) JSFiddle

After research, found that the problem is because we are only assigning the image source which is only pass message to the browser to retrieve the data.

经过研究,发现问题是因为我们只分配了图像源,它只是向浏览器传递消息来检索数据。

Further image element is may be not really accessible with the browser when click to draw canvas from it. We are just tell code to load it and it's done.

单击以从中绘制画布时,浏览器可能无法真正访问更多图像元素。我们只是告诉代码加载它,它就完成了。

Change code to solve OP's facing chrome issue like below:

更改代码以解决 OP 面临的 chrome 问题,如下所示:

img.onload = function() {
  context.drawImage(img, 0, 50);// draws the image at the specified x and y location
}

UPDATE 4JSFiddle
Make image position dynamic based on OP requirement.

更新 4 JSFiddle
根据 OP 要求使图像位置动态。

回答by sulest

You may try to scan the image source for external urls and change them to your website and load them with php.

您可以尝试扫描外部 url 的图像源并将它们更改为您的网站并使用 php 加载它们。

Something like

就像是

$(function() { 

  var imageproxy = "http://example.com/imageproxy.php"; //Change this
  var mydomain = new RegExp(location.host);

  $("#btnSave").click(function() { 

    $("#widget").find('img').each(function(){

       var img_src = $(this).attr('src');
       if(!mydomain.test(img_src)){
           $(this).attr('src', imageproxy + "?url=" + encodeURIComponent(img_src));
       }
    });

    html2canvas($("#widget"), {
        onrendered: function(canvas) {

            var link = $('<a target="_blank">Download</a>');
            link.attr('download', 'test.png');
            link.attr('href', canvas.toDataURL());

            $("#btnSave").after(link);
        }
    });
  });
}); 

imageproxy.php

图片代理.php

<?php

if(!empty($_GET['url'])){

    $url = urldecode($_GET['url']);
    $img_type = "image/jpeg";

    $chunks = explode('.', $url);

    if(is_array($chunks) && count($chunks) > 1){
        $ext = end($chunks);

        switch ($ext){

            case 'jpg':
            case 'jpeg':
                $img_type = "image/jpeg";
            break;

            case 'png':
                $img_type = "image/png";
            break;

            case 'gif':
                $img_type = "image/gif";
            break;
        }
    }


    $img = file_get_contents($url);

    header ("Content-Type: $img_type");
    echo $img;
}

note: php script is very simple, image detection is not working 100%, this is just ti give you an idea. If you use some php image libs to load and get image type you can do this just with few lines of code. you may also try with "php readfile".

注意:php 脚本非常简单,图像检测不能 100% 工作,这只是给你一个想法。如果您使用一些 php 图像库来加载和获取图像类型,则只需几行代码即可完成此操作。您也可以尝试使用“php readfile”。

回答by r3mus

onrendered is no longer working..

onrendered 不再工作..

i solved this problem by adding "allowTaint" option

我通过添加“allowTaint”选项解决了这个问题

{ allowTaint: true }

2018 solution:

2018年解决方案:

html2canvas(document.getElementById('result'), { allowTaint: true }).then(function (canvas) {
    document.body.appendChild(canvas);
});