HTML2Canvas无法渲染CDN图片

3
我将尝试使用html2canvas获取屏幕截图。对于文本来说,它运行良好,但是如果要渲染CDN图像,则无法正常工作。如果我将图像托管在服务器上,则可以正常工作,但是如果尝试从CDN链接加载图像,则这些图像不会呈现。

我的代码如下:

index.php

<div id="target">
     <img id="editor_Img_1" src="http://d2j259rizy5u5h.cloudfront.net/outputvideos/thumbs/email_44_2015_03_02_54f462457526c-00001.png" alt="event-video" style="height: 200px; width: 320px;">
</div>

function capture() {
    $('#target').html2canvas({
        onrendered: function (canvas) {
            var img = canvas.toDataURL();
            console.log(img);
            $('<img>',{src:img}).appendTo($('img'));
            //Set hidden field's value to image data (base-64 string)
            $('#img_val').val(canvas.toDataURL("image/png"));
            //Submit the form manually
            document.getElementById("myForm").submit();
        }
    });
}

Save.php

<?php
    //Get the base-64 string from data
    $filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);

    //Decode the string
    $unencodedData=base64_decode($filteredData);

    echo $filteredData;

    //Save the image
    file_put_contents('img.png', $unencodedData);
?>
<h2>Save the image and show to user</h2>
<table>
<tr>
    <td>
        <a href="img.png" target="blank">
            Click Here to See The Image Saved to Server</a>
    </td>
    <td align="right">
        <a href="index.php">
            Click Here to Go Back</a>
    </td>
</tr>
<tr>
    <td colspan="2">
        <br />
        <br />
        <span>
            Here is Client-sided image:
        </span>
        <br />
        <?php
            //Show the image
            echo '<img src="'.$_POST['img_val'].'" />';
        ?>
     </td>
</tr>
</table>

很可能有一个跨域请求被禁止了。请检查您的JavaScript控制台是否有错误。 - Nick Coad
2个回答

4

您可以通过在html2canvas函数中传递一个选项来实现。

html2canvas(document.body,
{
   useCORS: true, //By passing this option in function Cross origin images will be rendered properly in the downloaded version of the PDF
   onrendered: function (canvas) {
     //your functions here
   }
});

1
非常有帮助。 - user3048231

2
好的,我已经找出了问题所在。html2canvas无法捕获不来自同一源的图像。这些图片来自CDN。html to canvas存在一些限制。
限制:
所有脚本使用的图片都需要位于相同的来源之下,才能够在没有代理的情况下读取它们。同样地,如果页面上有其他带有跨域内容的画布元素,它们将变得污染并且不能被html2canvas读取。
该脚本不会呈现插件内容,如Flash或Java小程序。它也不会呈现iframe内容。 文档

你解决了这个问题吗?我也遇到了同样的问题 - 把所有东西都放在非CDN域名上似乎有点过度杀伐! - Andrew Newby
@Bhavin Solanki,你解决了这个问题吗? - Nikhil Radadiya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接