直接从HTML5画布保存图像

时间:2014-02-14 06:37:02

标签: html5 canvas highcharts html5-canvas

我浏览了高级网站http://jsfiddle.net/highcharts/PDnmQ/上提供的演示jsfiddle。 当我点击按钮保存为png时,它会下载一个标题为下载而不是png文件的文件。

HTML:

<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script> 
<script src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script> 

脚本:

(function (H) {
    H.Chart.prototype.createCanvas = function (divId) {
        var svg = this.getSVG(),
            width = parseInt(svg.match(/width="([0-9]+)"/)[1]),
            height = parseInt(svg.match(/height="([0-9]+)"/)[1]),
            canvas = document.createElement('canvas');

        canvas.setAttribute('width', width);
        canvas.setAttribute('height', height);

        if (canvas.getContext && canvas.getContext('2d')) {

            canvg(canvas, svg);

            var image = canvas.toDataURL("image/png")
                .replace("image/png", "image/octet-stream"); 

            // Save locally
            window.location.href = image;
        } else {
            alert ("Your browser doesn't support this feature, please use a modern browser");
        }

    }
}(Highcharts));

$('#container').highcharts({

    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    title: {
        text: 'Click the button and Save as PNG =>',
        align: 'right',
        x: -40
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
    }],

    exporting: {
        buttons: {
            contextButton: {
                menuItems: [{
                    text: 'Print',
                    onclick: function() {
                        this.print();
                    }
                }, {
                    text: 'Save as PNG',
                    onclick: function() {
                        this.createCanvas();
                    },
                    separator: false
                }]
            }
        }
    }

});

1 个答案:

答案 0 :(得分:4)

您可以将画布中的data-uri分配给一个锚元素,然后您可以使用设置文件名的下载属性来定位该元素。

例如,假设此锚存在于您的HTML中:

<a id="saveAs" href="#">Click to download</a>

然后,当您从画布抓取图像时,可以通过以下方式更新锚标记:

var link = document.getElementById('saveAs');

link.href = canvas.toDataURL();   /// set data-uri as href, defaults to PNG
link.download = 'myFilename.png'; /// set filename

现在您可以单击锚链接,它将允许您使用set filename下载文件。

您还可以动态创建离屏锚标记,并通过模拟点击事件来调用点击。