画布未添加到列表

时间:2019-07-08 12:48:02

标签: javascript html5-canvas

我有两个dataUrl,需要在画布中显示它们,最后我希望将它们附加到名为“ piclist”的无序列表中。但是我只能看到1张照片被追加了。有人可以告诉我为什么未附加其他图片吗?我还用警告消息检查了循环是否被重复两次并且确实进行了。但是仅附加了图片

  let datapo = {{datapo|safe}};
  for (var key in datapo) {
    //alert(key+" "+datapo[key]);

     var node = document.createElement("li");
     var d0 = document.createElement("div");
     var c = document.createElement("canvas");
     var c4 = c.getContext("2d");


     c.width  = 200; // in pixels
     c.height = 100; // in pixels


     var myImg = new Image;


     myImg.src = datapo[key];
     myImg.width = c.width;
     myImg.height = c.height;


     myImg.onload = () => { c4.drawImage(myImg, 0, 0, c.width, c.height);

     document.body.appendChild(c); // adds the canvas to the body element
     node.appendChild(c);
     document.getElementById("piclist").append(node);

     };


  }

1 个答案:

答案 0 :(得分:1)

同一元素不能在DOM中添加两次,解决方法是先插入clone元素,再插入第二位,请参见演示

function myFunctionNotWorking() {
  var node = document.createElement("LI");
  var textnode = document.createTextNode("Item");
  node.append(textnode);
  node.append(textnode);
  node.appendChild(textnode);
  document.getElementById("myList").append(node);
  document.getElementById("myList").append(node); 
  document.getElementById("myList").appendChild(node);  
}

function myFunctionWorking() {
  var node = document.createElement("LI");
  var textnode = document.createTextNode("Item");
  node.append(textnode);
  node.append(textnode.cloneNode(true));
  node.appendChild(textnode.cloneNode(true));
  document.getElementById("myList").append(node);
  document.getElementById("myList").append(node.cloneNode(true)); 
  document.getElementById("myList").appendChild(node.cloneNode(true));  
}
<ul id="myList">
  <li>Item</li>
</ul>

<p>Click the button to append an items to the end of the list.</p>

<button onclick="myFunctionNotWorking()">Add Items (not working)</button>
<button onclick="myFunctionWorking()">Add Items (working)</button>