如何在画布上逐个加载多个图像?使用循环

时间:2016-01-26 05:43:18

标签: javascript jquery html5-canvas fabricjs

var ImgCanvas = new fabric.Canvas("mycanvas");
var json = {};
var IdStore = [];
var retval = [];
var retvalsrc = [];

function sava(){
//push to array for loop
$('.Jicon').each(function(){
  retval.push($(this).attr('id'));
  retvalsrc.push($(this).attr('src'));
})


var className = $(".Jicon");
var classnameCount = className.length;
//loop classname
for(var d = 0; d < classnameCount; d++){
updateCanvas(retval[d], retvalsrc[d]);
}

}


//change main image
function updateCanvas(_id, _src)
{    
ImgCanvas.clear();
// var oImg = new fabric.Image(_src, {
fabric.Image.fromURL(_src, function(oImg) {
    oImg.setWidth(500);
    oImg.setHeight(400);
    oImg.left = ((ImgCanvas.width/2)-(oImg.width/2));
    oImg.top = 50;
    oImg.selectable = false;
    ImgCanvas.add(oImg);
    ImgCanvas.renderAll();
  });
}

我有一个多用途的图像,我想用循环逐个加载到画布,我该如何实现?因此,当我按下sava时,图像将逐一显示在画布上。我试图使用它,但它将所有这些图像加载在一起。

任何人都可以在这里给我一个帮助〜感谢apreciate。

Demo

1 个答案:

答案 0 :(得分:0)

让imageFromURL的结尾调用下一个加载,并重构代码以使用settimeout,否则一切都会非常快。

之前的图像全部显示,因为负载是异步的。所以使用for循环你是

  • 按照4张图片的顺序快速开始加载

  • 立即清除4次仍为空的画布

  • 然后每张图片都会完成加载并以随机顺序显示在画布上。

var ImgCanvas = new fabric.Canvas("mycanvas");
var json = {};
var IdStore = [];
var retval = [];
var retvalsrc = [];

function sava(){

  $('.Jicon').each(function(){
    retval.push($(this).attr('id'));
    retvalsrc.push($(this).attr('src'));
  })


  updateCanvas();

}


//change main image
function updateCanvas() {
  ImgCanvas.clear();
var _src = retvalsrc.pop();
fabric.Image.fromURL(_src, function(oImg) {
    oImg.setWidth(500);
    oImg.setHeight(400);
    oImg.left = ((ImgCanvas.width/2)-(oImg.width/2));
    oImg.top = 50;
    oImg.selectable = false;
    ImgCanvas.add(oImg);
    ImgCanvas.renderAll();
    if (retvalsrc.length > 0) {
      setTimeout(updateCanvas, 1000);
    }
  });
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>

<div>
   <img name="001.png" class="Jicon" id="displayImage1" src="http://i795.photobucket.com/albums/yy232/PixKaruumi/Pokemon%20Pixels/077.png" onclick="updateCanvas(this.src);">
   <img name="002.png" class="Jicon" id="displayImag2" src="http://i795.photobucket.com/albums/yy232/PixKaruumi/Pokemon%20Pixels/076.png" onclick="updateCanvas(this.src);">
   <img name="003.png" class="Jicon" id="displayImage3" src="http://rs795.pbsrc.com/albums/yy232/PixKaruumi/Pokemon%20Pixels/071.png~c100" onclick="updateCanvas(this.src);">
   <img name="004.png" class="Jicon" id="displayImag4" src="http://rs795.pbsrc.com/albums/yy232/PixKaruumi/Pokemon%20Pixels/072.png~c100" onclick="updateCanvas(this.src);">
</div>
<button onclick="sava();">sava</button>
  <div id="warpper">
	<canvas id="mycanvas" width="380" height="500" style="border:1px solid #000;"></canvas>
</div><!-- end of div -->
</body>