下载Canvas Image Png Chrome / Safari

时间:2013-10-29 03:50:59

标签: javascript canvas

适用于Firefox,无法在Safari或Chrome中使用。

 function loadimage()
    {
    var canvas = document.getElementById("canvas");

    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
       xmlhttp=new XMLHttpRequest();
       xmlhttp2=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
       xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
    }
       xmlhttp.onreadystatechange=function()
    {

    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    rasterizeHTML.drawHTML(xmlhttp.responseText, canvas);
    var t=setTimeout(function(){copy()},3000)
    }
  }
  xmlhttp.open("GET","/sm/<?=$sm[0];?>",true);
  xmlhttp.send();
}

function copy()
{
var canvas = document.getElementById("canvas");
var img    = canvas.toDataURL("image/png");

document.getElementById('dl').href = img;
document.getElementById('dl').innerHTML = "Download";
}

现在我没有写这个,所以我不太了解JavaScript。但该脚本适用于Firefox。在Chrome中,获取:未捕获的安全错误:尝试突破用户代理的安全策略。对于toDataURL("image/png")

1 个答案:

答案 0 :(得分:0)

假设<?=$sm[0];?>在服务器上正确预处理,以下应该做同样的事情,但是跨浏览器工作:

function loadImage() {
    $.get("sm/<?=$sm[0];?>", function (data) {
        rasterizeHTML.drawHTML(data, $('#canvas')[0]);
        setTimeout(copy, 3000);
    });
}

function copy() {
    var $canvas = $("#canvas");
    var img = $canvas[0].toDataURL("image/png");
    $('#dl').attr('href', img).text("Download");
}