简体   繁体   中英

Save html as image using HTML2CANVAS

I have added HTML2CANVAS to save a canvas wrapped in a div as an image in .png format. It works great in Chrome, but nothign happens in IE 9, 10, or 11. I have set breakpoints in IE to debug, but no errors are ever thrown.

My reason for wrapping the canvas in a div was to be able to export the legend with the chart/graph that is generated in the canvas tag.

I am using AngularJS, but in this instance, only a click event is used.

Again, this is working fine in Chrome. No errors are thrown in IE. When debugging it goes over javascript below and appears to be hitting each line appropriately. I do have the html2canvas.js file added in the page FYI.

I have researched this and came across some posts saying IE does not handle promises and I needed to add a polyfill to compensate for this. I've done that and nothing changes.

Thanks

Here is my code.

HTML

<div class="row">
    <div id="widget" class="col-md-12">
    <canvas id="lineChartCanvas" class="chart chart-line" chart-data="data" chart-labels="labels" style="height: 300px; width: 95%;"
            chart-legend="true" chart-series="series" chart-click="onClick"></canvas>
    </div>
</div>

Button click event

<input type="button" class="btn btn-primary" id="btnSave" ng-click="exportChart()" ng-show="isIEbrowser" value="EXPORT CHART"/>

Javascript/Angular

function exportChart() {

    var canvasdiv = document.getElementById("widget");

    html2canvas(canvasdiv,{

        onrendered: function (canvas) {
            var a = document.createElement("a");
            a.href = canvas.toDataURL("image/png");
            a.download = userContext.mrn + "_chart_" + datetime + ".png";
            a.click();
        }
    });
}

For IE, use the BlobBuilder to convert the canvas to a blob object and save it as an image stream.

Below is a sample code that I have used in one of my project:

if (navigator.msSaveBlob) {
                    var URL = window.URL;
                    var BlobBuilder = window.MSBlobBuilder;
                    navigator.saveBlob = navigator.msSaveBlob;
                    var imgBlob = canvas.msToBlob();
                    if (BlobBuilder && navigator.saveBlob) {
                        var showSave = function (data, name, mimetype) {
                            var builder = new BlobBuilder();
                            builder.append(data);
                            var blob = builder.getBlob(mimetype || "application/octet-stream");
                            navigator.saveBlob(blob, name);
                        };

                        showSave(imgBlob, fileName, "image/png");
                    }
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM