在canvg创建的画布下方显示图像

时间:2016-09-28 11:16:06

标签: html5 canvas d3.js svg canvg

我使用canvg插件创建了一个画布。

然后我想使用ctx.drawimage()[由canvg创建]在画布下放置另一个背景图像。

我试过了。

请建议。

var svgString = new XMLSerializer().serializeToString(document.querySelector('svg'));

        var canvas = document.getElementById("canvas");
         var DOMURL = self.URL || self.webkitURL || self;
        ctx = canvas.getContext("2d");
    canvg(canvas, svgString, { ignoreMouse: true, ignoreAnimation: true});
     var img1 = new Image();


        img1.onload = function() {

             ctx.drawImage(img1, 136, 136);


            var png = canvas.toDataURL("image/png");
            document.querySelector('#chart').innerHTML = '<img src="'+png+'"/>';
            DOMURL.revokeObjectURL(png);

        };

  img1.src= "chart.png";

1 个答案:

答案 0 :(得分:0)

这很有效。使用ctx.drawSvg(svgString,0,0,500,500);而不是drawImage

  var svgString = new       XMLSerializer().serializeToString(document.querySelector('svg'));

        var canvas = document.getElementById("canvas");
         var DOMURL = self.URL || self.webkitURL || self;

        var ctx = canvas.getContext("2d");

        var DOMURL = self.URL || self.webkitURL || self;
        var img = new Image();
        //var svg = new Blob([svgString], {type: "image/svg+xml;charset=utf-8"});
        var svg = new Blob([svgString], {type: "image/svg+xml"});
        var url = DOMURL.createObjectURL(svg);


        var png = '';

        var img1 = new Image();



         img1.onload = function(){
           ctx.drawImage(img1, 136, 136);
           ctx.drawSvg(svgString,0,0,500,500);
           var png = canvas.toDataURL("image/png");
            document.querySelector('#chart').innerHTML = '<img src="'+png+'"/>';
            DOMURL.revokeObjectURL(png);
         };
        img1.src = 'chart.png';