How to post immediately after svg to canvas conversion is done?

冷暖自知 提交于 2020-05-01 14:30:12

问题


I am attempting post with html2canvas after converting all the svgs in a html element to canvas, but the post executes immediately before the svg to canvas conversion finishes, since it takes a few seconds. I have tried using deferred and promises, but I am still having the same issue.

    // https://github.com/niklasvh/html2canvas/issues/95#issuecomment-45114424
    // First render all SVGs to canvases
    targetElem = $('#dashboard');

    var elements = targetElem.find('svg').map(function() {
        var svg = $(this);
        var canvas = $('<canvas></canvas>');
        svg.replaceWith(canvas);

        // Get the raw SVG string and curate it
        var content = svg.wrap('<p></p>').parent().html();
        content = content.replace(/xlink:title='hide\/show'/g, '');
        content = encodeURIComponent(content);
        svg.unwrap();

        // Create an image from the svg
        var image = new Image();
        image.src = 'data:image/svg+xml,' + content;
        image.onload = function() {
            canvas[0].width = image.width;
            canvas[0].height = image.height;

            // Render the image to the canvas
            var context = canvas[0].getContext('2d');
            context.drawImage(image, 0, 0);
        };

        return {
            svg: svg,
            canvas: canvas
        };
    }); // end of targetElem.find('svg').map(function() {...});

EDITED: Here is the deferred and promise I have been attempting to implement to create two operations that run in sequential order.

$(document).ready(function() {

    $( '#save_dashboard' ).click(function() {

    // Create a deferred object
    var dfd = $.Deferred();

        // https://github.com/niklasvh/html2canvas/issues/95#issuecomment-45114424
        // First render all SVGs to canvases
        targetElem = $('#dashboard');

        var elements = targetElem.find('svg').map(function() {
            var svg = $(this);
            var canvas = $('<canvas></canvas>');
            svg.replaceWith(canvas);

            // Get the raw SVG string and curate it
            var content = svg.wrap('<p></p>').parent().html();
            content = content.replace(/xlink:title='hide\/show'/g, '');
            content = encodeURIComponent(content);
            svg.unwrap();

            // Create an image from the svg
            var image = new Image();
            image.src = 'data:image/svg+xml,' + content;
            image.onload = function() {
                canvas[0].width = image.width;
                canvas[0].height = image.height;

                // Render the image to the canvas
                var context = canvas[0].getContext('2d');
                context.drawImage(image, 0, 0);
            };
            dfd.resolve();

            return dfd.promise();
            };
        }); // end of targetElem.find('svg').map(function() {...});

        dfd.resolve();

        $.when(dfd).done(function(){
            console.log('dfd done');

            // http://www.kubilayerdogan.net/html2canvas-take-screenshot-of-web-page-and-save-it-to-server-javascript-and-php/
            $('#dashboard').html2canvas({
                onrendered: function (canvas) {
                    //Set hidden field's value to image data (base-64 string)
                    var dashboardPng = canvas.toDataURL('image/png');
                    console.log('dashboardPng: ' + dashboardPng);

                    $.ajax({
                        url:'save_dashboard_image.php',
                        data:{dashboardPngData: dashboardPng},
                        type:'POST',
                        dataType:'json',
                        success: function(){
                            console.log('success');
                        }
                        ,
                        error: function(xhr, status, error){
                            console.log('The requested page was: ' + document.URL +
                                '. The error number returned was: ' + xhr.status +
                                '. The error message was: ' + error);
                        }
                    });
                }
            });
        }); // end of $.when(dfd).done(...)
    }); // end of save_dashboard click function
}); // end of document ready

回答1:


Updated

Note, Untested. Adjusted click event to return multiple canvas , promise objects , to .then()

If interpret question correctly, try

$(document).ready(function() {

    $( '#save_dashboard' ).click(function() {

    // Create a deferred object
    // dfd = new $.Deferred();

        // https://github.com/niklasvh/html2canvas/issues/95#issuecomment-45114424
        // First render all SVGs to canvases
        targetElem = $('#dashboard');
        var promises = $.when.apply(targetElem, $.map(targetElem.find('svg')
          , function(el, index) {
            return new $.Deferred(function(dfd) {
              var svg = $(el);
              var canvas = $('<canvas></canvas>');
              svg.replaceWith(canvas);

              // Get the raw SVG string and curate it
              var content = svg.wrap('<p></p>').parent().html();
              content = content.replace(/xlink:title='hide\/show'/g, '');
              content = encodeURIComponent(content);
              svg.unwrap();

              // Create an image from the svg
              var image = new Image();

              image.onload = function() {
                  canvas[0].width = image.width;
                  canvas[0].height = image.height;

                  // Render the image to the canvas
                  var context = canvas[0].getContext('2d');

                  dfd.resolve(context.drawImage(image, 0, 0));
              };
              image.src = 'data:image/svg+xml,' + content;
            }).promise();          
          })
         ); // end of targetElem.find('svg').map(function() {...});



        promises.then(function(_canvas) {
            console.log('dfd done', _canvas, arguments);

            // http://www.kubilayerdogan.net/html2canvas-take-screenshot-of-web-page-and-save-it-to-server-javascript-and-php/
            $('#dashboard').html2canvas({
                onrendered: function (canvas) {
                    //Set hidden field's value to image data (base-64 string)
                    var dashboardPng = canvas.toDataURL('image/png');
                    console.log('dashboardPng: ' + dashboardPng);

                    $.ajax({
                        url:'save_dashboard_image.php',
                        data:{dashboardPngData: dashboardPng},
                        type:'POST',
                        dataType:'json',
                        success: function(){
                            console.log('success');
                        }
                        ,
                        error: function(xhr, status, error){
                            console.log('The requested page was: ' + document.URL +
                                '. The error number returned was: ' + xhr.status +
                                '. The error message was: ' + error);
                        }
                    });
                }
            });
        }); // end of $.when(dfd).done(...)
    }); // end of save_dashboard click function
}); // end of document 



回答2:


Solution I had to use an array for each successive svg to canvas conversion and when they were all complete. I could pass the array to then() to post the html2canvas.

  1. Create a new array on click, use that to store all deferreds from SVGs
  2. Loop through all SVG elements
    • In each instance, create a new internal deferred object
    • Resolve or reject the deferred
    • Push it into the array outside the loop
  3. Use $.when.apply($, arrayOfDeferredObjects) to check for status of all deferred objects in the array

    $( '#save_dashboard' ).click(function() {
    
        // Declare an array to store all deferred objects from each svg element
        var svgDfds = [],
            targetElem = $('#dashboard');
    
        targetElem.find('svg').each(function() {
            var dfd = new $.Deferred(),
                svg = $(this),
                canvas = $('<canvas></canvas>');
    
            svg.replaceWith(canvas);
    
            // Get the raw SVG string and curate it
            var content = svg.wrap('<p></p>').parent().html();
            content = content.replace(/xlink:title='hide\/show'/g, '');
            content = encodeURIComponent(content);
            svg.unwrap();
    
            // Create an image from the svg
            var image = new Image();
            image.src = 'data:image/svg+xml,' + content;
            image.onload = function() {
                canvas[0].width = image.width;
                canvas[0].height = image.height;
    
                // Render the image to the canvas
                var context = canvas[0].getContext('2d');
    
                // Resolve or reject the deferred
                dfd.resolve(context.drawImage(image, 0, 0));
            };
    
            // Push deferred object into array
            svgDfds.push(dfd);
    
        }); // end of targetElem.find('svg').map(function() {...});
    
        // Check for all deferreds
        $.when.apply($, svgDfds).then(function(_canvas) {
            console.log('dfd done', _canvas);
    
            // http://www.kubilayerdogan.net/html2canvas-take-screenshot-of-web-page-and-save-it-to-server-javascript-and-php/
            $('#dashboard').html2canvas({
                onrendered: function (canvas) {
                    //Set hidden field's value to image data (base-64 string)
                    var dashboardPng = canvas.toDataURL('image/png');
                    console.log('dashboardPng: ' + dashboardPng);
    
                    $.ajax({
                        url:'save_dashboard_image.php',
                        data:{dashboardPngData: dashboardPng},
                        type:'POST',
                        dataType:'json',
                        success: function(){
                            console.log('success');
                        }
                        ,
                        error: function(xhr, status, error){
                            console.log('The requested page was: ' + document.URL +
                                '. The error number returned was: ' + xhr.status +
                                '. The error message was: ' + error);
                        }
                    });
                }
            });
        });
    
    }); // end of save_dashboard click function
    


来源:https://stackoverflow.com/questions/29635005/how-to-post-immediately-after-svg-to-canvas-conversion-is-done

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!