1

我有一个 highcharts svg,我已通过 canvg 将其转换为 png 并显示在网页上。然后我想将此 png 发送到服务器以创建指向图像的链接。我正在关注另一个主题的答案代码:

重命名从 HTML5 画布创建的图像

我的javascript代码如下:

var timeout = window.setTimeout(function() {
    canvg(document.getElementById('canvas'), chart.getSVG());
}, 10000);

var canvas = document.getElementById("canvas");

var img = canvas.toDataURL("images/png");
document.write('<img src="'+img+'"/>');

saveDataURL(img)

function saveDataURL(canvas) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState === 4 && request.status === 200) {
            window.location.href = request.responseText;
        }
    };
    request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    request.open("POST", "saveDataURL.php", true);
    request.send("dataURL=" + canvas.toDataURL());
}

我的名为 saveDataURL.php 的 php 是:

$dataURL = $_POST["dataURL"];
$encodedData = explode(',', $dataURL)[1];
$decodedData = base64_decode($encodedData);
file_put_contents("temp/faizan.png", $decodedData);
echo "http://whichchart.com/temp/faizan.png";

在 Firefox 12 中,“request.setRequestHeader”行会抛出以下错误:

组件返回失败代码:0x804b000f (NS_ERROR_IN_PROGRESS) [nsIXMLHttpRequest.setRequestHeader] http://whichchart.com/oil.js 第 102 行

在 chrome 中,同一行的错误是:

未捕获的错误:INVALID_STATE_ERR:DOM 异常 11 saveDataURLoil.js:106(匿名函数)

该示例可以在此处查看:whichchart.com。你能帮我吗?谢谢。

4

1 回答 1

1

好的,经过多次搜索,我找到了不同的解决方案。链接在这里:

http://permadi.com/blog/2010/10/html5-saving-canvas-image-data-using-php-and-ajax/

假设你有一个名为 testCanvas 的画布,这个 javascript 和 php 将起作用:

var canvasData = testCanvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'testSave.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData );  

<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
    // Get the data
    $imageData=$GLOBALS['HTTP_RAW_POST_DATA'];

    // Remove the headers (data:,) part. 
    // A real application should use them according to needs such as to check image type
    $filteredData=substr($imageData, strpos($imageData, ",")+1);

    // Need to decode before saving since the data we received is already base64 encoded
    $unencodedData=base64_decode($filteredData);

    //echo "unencodedData".$unencodedData;

    // Save file.  This example uses a hard coded filename for testing,
    // but a real application can specify filename in POST variable
    $fp = fopen( 'test.png', 'wb' );
    fwrite( $fp, $unencodedData);
    fclose( $fp );
}
?>
于 2012-05-05T00:20:00.007 回答