html and Svg to Canvas javascript

前端 未结 5 664
别那么骄傲
别那么骄傲 2021-02-02 01:36
&l
5条回答
  •  难免孤独
    2021-02-02 01:47

    As the html2canvas don't take svg elements, you need to convert all svg elements to canvas before you call the html2canvas method. You could use the canvg library to convert all the svg to canvas. You can pass the jquery object(which needs to convert from svg to canvas, can also be a parent element) to the following method:

    function svgToCanvas (targetElem) {
    var nodesToRecover = [];
    var nodesToRemove = [];
    
    var svgElem = targetElem.find('svg');
    
    svgElem.each(function(index, node) {
        var parentNode = node.parentNode;
        var svg = parentNode.innerHTML;
    
        var canvas = document.createElement('canvas');
    
        canvg(canvas, svg);
    
        nodesToRecover.push({
            parent: parentNode,
            child: node
        });
        parentNode.removeChild(node);
    
        nodesToRemove.push({
            parent: parentNode,
            child: canvas
        });
    
        parentNode.appendChild(canvas);
    });
    
    html2canvas(targetElem, {
        onrendered: function(canvas) {
            var ctx = canvas.getContext('2d');
            ctx.webkitImageSmoothingEnabled = false;
            ctx.mozImageSmoothingEnabled = false;
            ctx.imageSmoothingEnabled = false;
        }
        });
    }
    

提交回复
热议问题