首页 > 解决方案 > 画布没有附加到列表中

问题描述

我有两个 dataUrls 需要显示在画布中,最后我希望将它们附加到名为 "piclist" 的无序列表中。但我只能看到附加了一张图片。有人能告诉我为什么没有附加另一张图片吗?我还检查了一条警告消息,循环是否被迭代了两次并且确实如此。但只附加了图片

  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);

     };


  }

标签: javascripthtml5-canvas

解决方案


同一个元素不能在 DOM 中追加两次,解决方案是在插入第二个位置之前克隆元素,参见演示

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>


推荐阅读