canvassvgdrawimagecgcontextdrawimage

Canvas drawImage draws only some part of SVG


I have chart SVG of width around 500 and height around 300. I have scaled it using scale attribute in SVG. Now when I tried drawing it on canvas it draws on some part from top left corner of the SVG. If I open SVG file separately in browser it shows the whole image also the image tag which I have created for canvas also shows whole image.

I have also tried using different source and destination offsets, width and height but it didn't work.

I am clueless now what could be the problem.

Following is ths sample code where I have changed the SVG.

NOTE:- this also crops image but shows full SVG when I provide source and destination offsets, width and height. Unfortunatly it doesn't help me with my SVG.

var data = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" version="1.1"><rect width="1000" height="350" fill="rgb(0, 255, 0)" stroke-width="1" stroke="rgb(0, 0, 0)" /></svg>';

var canvas = $("<canvas width='1024' height='360' style=\"border: 1px solid red;\">");
$(canvas).appendTo('body').css('position', 'absolute').css('top', 0);
var image = new Image;
$(image).appendTo("body")
    .width(defaultZoomWidth).height(360)
    .css("position", "fixed").css("top", "400px");
image.onload = function() {
    setTimeout(function(){
        var context = canvas.get(0).getContext("2d");
        context.drawImage(image, 0, 0);
    }, 1000);
};
image.src = data;

Solution

  • Your issue is that you must set absolute width and height attributes on the <svg> node, not percentages, which will be the default if nothing is set (100%).

    As side notes, the most supported dataURI header syntax is
    data:image/svg+xml; charset=utf8, + your_svg_markup.

    Also, it's always better to encodeURIComponent your serialized svg markup when setting it as a dataURI.

    So here it is :

    var svgString = '<svg width="1000" height="1000" xmlns="http://www.w3.org/2000/svg" version="1.1"><rect width="1000" height="350" fill="rgb(0, 255, 0)" stroke-width="1" stroke="rgb(0, 0, 0)" /></svg>';
    
    var data = 'data:image/svg+xml; charset=utf8, '+ encodeURIComponent(svgString);
    
    var canvas = $("<canvas width='1024' height='360' style=\"border: 1px solid red;\">");
    $(canvas).appendTo('body').css('position', 'absolute').css('top', 0);
    var image = new Image;
    image.onload = function() {
        var context = canvas.get(0).getContext("2d");
        context.drawImage(image, 0, 0);
    };
    image.src = data;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>