Appending a div containing canvas is not working

南楼画角 提交于 2019-12-11 16:58:53

问题


I am making use of canvg to convert svg present in div into canvas(upto this it's working fine) and then copying the innerHTML of div to another div, but it's not working. Canvas is coming but nothing will be present in that canvas. Thanks in advance

<div id="k">
<svg width="100" height="100">
   <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
   Sorry, your browser does not support inline SVG.
</svg> 
</div>
<div id="kk">
<p>Watch me</p>
</div>

var svgTag = document.querySelectorAll('#k svg');    
    svgTag = svgTag[0];
    var c = document.createElement('canvas');
    c.width = svgTag.clientWidth;
    c.height = svgTag.clientHeight;
    svgTag.parentNode.insertBefore(c, svgTag);
    svgTag.parentNode.removeChild(svgTag);
    var div = document.createElement('div');
    div.appendChild(svgTag);
    canvg(c, div.innerHTML);

    setTimeout(function(){
        var data = $("#k").html();
      $("#kk").append($(''+data+''));
    },5000);

JSFiddle


回答1:


The content of a canvas element is held as binary data, much like the content of an image element. Canvas elements do not have an innerHTML text property that can be used to recreate the canvas.

The following example shows a method of cloning a canvas element using standard canvas 2D methods:

function canvasClone(c1) {
    var c2 = document.createElement('canvas');
    c2.width=c1.width;
    c2.height=c1.height;
    c2.getContext("2d").drawImage(c1, 0,0);
    return c2;
}

You can demonstrate it by including the function in the fiddle and changing the timeout processing to:

setTimeout(function(){
  kk.appendChild(canvasClone(c));
},5000);

Feel free to rewrite the timeout code in JQuery if you prefer.



来源:https://stackoverflow.com/questions/46559050/appending-a-div-containing-canvas-is-not-working

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