Canvas toDataURI() on chrome security issue

I am having an issue with Canvas on chrome. I know that this is mentioned a lot but i was not able to find a solution that suites me.

Basically, i am designing a website that does the following steps:
- Loads an SVG image template from the hosting server into an object.
- Manipulates that SVG (Coloring, hiding and showing layers etc...)
- Then send the manipulated version to the server to be inserted into a pdf document and emailed.

My issue is with the last step. The approach that i was using involves:
- Fetching the content document of the SVG and serializing its XML.

 var s = new XMLSerializer();
 svg = document.getElementById('theSVG').contentDocument;
 var xmlTest = s.serializeToString(svg);
  • Defining a new image with an onLoad function and applying the src to it:

    drawnImage.src = 'data:image/svg+xml,' + escape(xmlTest);

  • Creating a canvas element and drawing that image into it:

    var canvas = document.createElement('canvas'); var cont = canvas.getContext('2d'); cont.drawImage(drawnImage, 0, 0, canvas.width, canvas.height);

  • The last step is extracting the dataURI from the canvas element as such:

  • var ImageDataURl = canvas.toDataURL();

    After that, the data (base64) is sent to the server, coonverted to bitmap and saved as a jpeg image on the server disk then inserted as a part of a big pdf document.

    All was going well until i tested it out on chrome, and i ran through the security error that states:

    Uncaught SecurityError: An attempt was made to break through the security policy of the user agent

    As i read about this error, i knew that this is a chrome security issue for cross domain images and blah blah. What i would like to know is the following:
    - Is creating a new canvas and loading the image into it on the user's browser treated as a file from another domain?
    - And is there a workaround for this even if it is server side (I am using C#) i do not mind. I tried uploading the SVG XML and tried convert it to base64 string but with no luck.

    Any help would be appreciated.


    On Chrome loading an SVG image into a canvas taints the canvas which means that you can't read any data from it although you can still write to it. It seems to have been fixed recently in Chrome provided you avoid certain SVG elements such as <foreignObject> so perhaps it will be in a Chrome release version soon.

    In the meantime, perhaps you could use Firefox instead which wouldn't taint the canvas.


    I solved this issue by using fabric js. Great library. The code is as follows:

    var a = document.getElementById("theSVG"); //This is the <object>
    a.setAttribute('data', 'worldmap.svg'); //Setting the data attribute to the svg file
    
    
    a.onload = function () {
    
        var svgDoc = a.contentDocument;
        var s = new XMLSerializer();
        var xml = s.serializeToString(svgDoc);
    
    
        var canvas = new fabric.Canvas('canvas');
    
        var svg = xml;
    
        fabric.loadSVGFromString(svg, function (objects, options) {
            var loadedObject = fabric.util.groupSVGElements(objects, options);
            canvas.add(loadedObject);
            canvas.calcOffset();
            canvas.renderAll();
            if (!fabric.Canvas.supports('toDataURL')) {
                alert('This browser doesn't provide means to serialize canvas to an image');
            }
            else {
                window.open(canvas.toDataURL('png'));
            }
    
        });
    }
    

    This solved the .toDataURL() issue. But i am left with the problems with my SVG File. Hope this helps.


    Hi I am doing like below. I didn't get any error. Hope this help you.

    <script type="text/javascript">
    
    $("#exportButton").click(function() { 
    
        html2canvas( [ document.getElementById("divId_for_Pdf") ], {
           onrendered: function(canvas) {
               var dataUrl = canvas.toDataURL();
             // $('#img1').attr('src',dataUrl);
               var action ='saveChartData';
                var data="dataUrl="+dataUrl;
               $.ajax({url:action, data:data, dataType:'text',type:'POST',cache:false,
                   success: function(data) {
                     //alert("success..........!")
                       window.location.href = "${grailsApplication.config.grails.serverURL}/adminConfig/downloadAnalyticsChart?tenantName=${tenantInstance?.tenantName}&from=Dashboard"
                   },
                   error: function(request, status, error) {
                       alert('error');
                   },
                   complete: function(data){
    
                   }
               });
    
           }
       });
    });        
    
    </script>
    
    链接地址: http://www.djcxy.com/p/50324.html

    上一篇: 使用<canvas>将非常大的SVG转换为PNG

    下一篇: Canvas toDataURI()在chrome安全问题上