2014-02-23 27 views
1

我想要在畫布上加載和顯示多個圖像。圖像源都保存在一個數組:Kinetic JS - 在畫布上載入多張圖片

var sources = {"../src/img/IMG_1284.JPG", "../src/img/IMG_1285.JPG", "../src/img/IMG_1286.JPG", "../src/img/IMG_1287.JPG", "../src/img/IMG_1288.JPG"} 

我發現這個教程:http://www.html5canvastutorials.com/tutorials/html5-canvas-image-loader

但我不知道我怎麼可以這個代碼適應我的消息來源陣列。 此外,我想設置每個圖像可拖動,但我認爲這是不可能與context.drawImage(..)。

希望我的問題是可以理解的。感謝您的幫助...

回答

4

我看到你用KineticJS標記了你的問題。

KineticJS通過記錄圖像並讓用戶拖曳它們,使您的工作變得簡單。

就這麼簡單:

  • 使用的圖像加載程序,以確保您的所有圖像試圖拉攏他們
  • 加載時完全加載之後,使用每個圖像創建Kinetic.Image。
  • 穿上Kinetic.Image可拖動屬性,它會自動可拖動

這裏的代碼和演示:http://jsfiddle.net/m1erickson/3es4Z/

<!DOCTYPE html> 
<html> 
    <head> 
    <meta charset="utf-8"> 
    <title>Prototype</title> 
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> 
    <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.2.min.js"></script> 
<style> 
body{padding:20px;} 
#container{ 
    border:solid 1px #ccc; 
    margin-top: 10px; 
    width:350px; 
    height:350px; 
} 
</style>   
<script> 
$(function(){ 

    // create the Kinetic stage and layer 
    var stage = new Kinetic.Stage({ 
     container: 'container', 
     width: 350, 
     height: 350 
    }); 
    var layer = new Kinetic.Layer(); 
    stage.add(layer); 

    // put the paths to your images in imageURLs 
    var imageURLs=[]; 
    imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-1.jpg"); 
    imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-2.jpg"); 
    imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-3.jpg"); 
    var imagesOK=0; 
    var imgs=[]; 

    // fully load every image, then call the start function 
    loadAllImages(start); 

    function loadAllImages(callback){ 
     for (var i=0; i<imageURLs.length; i++) { 
      var img = new Image(); 
      imgs.push(img); 
      img.onload = function(){ 
       imagesOK++; 
       if (imagesOK>=imageURLs.length) { 
        callback(); 
       } 
      }; 
      img.onerror=function(){alert("image load failed");} 
      img.crossOrigin="anonymous"; 
      img.src = imageURLs[i]; 
     }  
    } 

    function start(){ 
     // the imgs[] array holds fully loaded images 
     // the imgs[] are in the same order as imageURLs[] 

     // make each image into a draggable Kinetic.Image 
     for(var i=0;i<imgs.length;i++){ 
      var img=new Kinetic.Image({ 
       x:i*75+15, 
       y:i*75+15, 
       width:60, 
       height:60, 
       image:imgs[i], 
       draggable:true 
      }); 
      layer.add(img); 
     } 
     layer.draw(); 
    } 

}); // end $(function(){}); 
</script>  
</head> 
<body> 
    <button id="myButton">Button</button> 
    <div id="container"></div> 
</body> 
</html>