Correct proxy script for html2canvas

这一生的挚爱 提交于 2019-12-11 12:05:19

问题


I'm trying to get html2render ( http://html2canvas.hertzen.com/ ) to work on my website. It works for the basic stuff - but none of the images show (as they are on a cdn.domain.com subdomain).

I've been reading up, and it seems that it doesn't like other domains out of the box. I found a couple of PHP proxy scripts:

  • https://github.com/brcontainer/html2canvas-php-proxy
  • https://github.com/adjdred/html2canvas-proxy-php

I tried to get those going, but we don't have curl enabled on this server. So, I'm resorting to writing something in Perl.

Here is what I've got so far:

use MIME::Base64;
use File::Slurp;

handle();

sub handle {

    print ('Access-Control-Max-Age:' . 5 * 60 * 1000);
    print ("Access-Control-Allow-Origin: *");
    print ('Access-Control-Request-Method: *');
    print ('Access-Control-Allow-Methods: OPTIONS, GET');
    print ('Access-Control-Allow-Headers *');
    print ("Content-Type: application/javascript");

    #print $IN->header;

    my $url = $IN->param('url');

    $url =~ s|https://cdn.xxx.net|/srv/www/xxx.net/www|g;

    if (-e $url) {

        my $file = read_file($url);

        use JSON;

        my $mime_type;
        if ($url =~ /\.jpe?g$/i) {
            $mime_type = "image/jpg"
        } elsif ($url =~ /\.png$/i) {
            $mime_type = "image/png"
        }
        print JSON::encode_json([{
            "pathinfo" => $url,
            "error" => undef,
            "data" => encode_base64($file),
            "mime_type" => $mime_type
        }]);
    } else {
        print "ACK!";
    }

}

However, it still doesn't work :( There is little (none??) documentation on the proxy (apart from telling you that you need it in some cases!)

Can anyone share what the outputted data should look like? I tried to work it out based on the above example codes , but my PHP is a bit rusty (and I don't have a server with PHP and Curl enabled, that I can test it out on)

Thanks!


回答1:


Ok, well not so much an answer about the proxy - but I did come across a post:

HTML2Canvas with CORS in S3 and CloudFront

In here, is shows an example of using:

 useCORS: true,

... so I tried that:

html2canvas(document.body, {
  useCORS: true,
  onrendered: function(canvas) {

  }
});                    

...and it works!!!!

In my instance, I was just using domain.com and cdn.domain.com as the CDN. If you are using other 3rd party CDN's, you may need to look at enabling the CORs headers.



来源:https://stackoverflow.com/questions/33220017/correct-proxy-script-for-html2canvas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!