【问题标题】:html2canvas not rendering CDN imageshtml2canvas 不渲染 CDN 图像
【发布时间】:2018-11-02 16:53:34
【问题描述】:

我正在尝试使用 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();
        }
    });
}

保存.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 控制台是否有错误。

标签: jquery html2canvas


【解决方案1】:

您可以通过传递 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
   }
});

【讨论】:

  • {非常有帮助}。
【解决方案2】:

好的,我知道问题出在哪里了。如果图像不是来自同一来源,则 html2canvas 无法捕获图像。图片来自 CDN。 html到canvas有一些限制

限制

脚本使用的所有图像都需要位于 same origin 下,这样它才能在没有 proxy 帮助的情况下读取它们。同样,如果页面上还有其他画布元素,这些元素已经被跨域内容污染,它们会变脏,不再被 html2canvas 读取。

脚本不会呈现插件内容,例如 Flash 或 Java 小程序。它也不呈现 iframe 内容。

Documentation

【讨论】:

  • 你有没有解决这个问题?我遇到了同样的问题 - 将所有内容放到非 CDN 域上似乎有点矫枉过正!
  • @Bhavin Solanki 你找到解决方案了吗?
猜你喜欢
  • 1970-01-01
  • 2015-09-23
  • 2015-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-17
  • 2022-12-21
  • 1970-01-01
相关资源
最近更新 更多