附加包含画布的div无法正常工作 [英] Appending a div containing canvas is not working

查看:84
本文介绍了附加包含画布的div无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 canvg 将div中存在的svg转换为canvas(到目前为止,它正在工作很好),然后将div的innerHTML复制到另一个div,但无法正常工作.画布即将到来,但该画布中将不存在任何内容. 预先感谢

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

推荐答案

canvas元素的内容被保存为二进制数据,就像image元素的内容一样.画布元素没有可用于重新创建画布的innerHTML文本属性.

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.

以下示例显示了一种使用标准canvas 2D方法克隆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);

如果愿意,可以随时重写JQuery中的超时代码.

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

这篇关于附加包含画布的div无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆