2013-04-02 73 views
0

我也很想知道這是否是最佳做法。HTML 5 canvas如何從spritemap中提取和存儲圖像?

我打開一個精靈地圖:

canvas = $('#GameCanvas')[0]; 
context = canvas.getContext('2d'); 

// load sprite map 
spriteMap = new Image(); 
spriteMap.src = "resources/spritemap.png"; 

現在我裝我的精靈,我要畫在屏幕上。我可以通過使用context.drawImage(..)但這樣做的:的

  • 我不知道這是不是最好的辦法,而不是隻提取我想每個圖像,並分別將它們存儲如。 var playerCharacter = [cut the image out of the sprite map]

  • 我想着色圖像。如果我拔出一個「白色」精靈,我可能會想要將它着色爲紅色,綠色等。我不知道如何去做,但它可能需要創建一個新的着色Image,所以我不得不無論如何,將它從spritemap中拉出來。我不想不斷地重新着色。

任何想法這樣做的最好方法?

回答

1

使用性能精靈

Phrogz對CSS VS帆布這裏一些有用的FPS測試:Efficiency of <canvas> and <div>s他們是活的測試,這樣你就可以在你想測試環境中運行它們。

再顯色精靈

如果你想快速把你的白色精靈,並從它創建的紅,綠,藍精靈,你可以使用globalCompositeOperation =」源式」做的很少工作。只需使用圖像編輯器即可創建要重新着色的圖像部分的切口。然後使用下面的代碼自動創建不同的彩色精靈。我在Photoshop中使用魔法需要的工具 - 2分鐘上衣!

原始魚+面膜=綠魚

enter image description hereenter image description hereenter image description here

當然,你可以創造任何你想要的顏色......即使模式而不是純色!

這是代碼。你可能需要創建自己的圖像和麪具,因爲CORS - 愚蠢的CORS!

<!doctype html> 
<html> 
<head> 
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> 

    <style> 
     canvas{border:1px solid red;} 
     #wrapper{ position:relative;} 
     #overlay,#base{ position:absolute; top:0; left:0;} 

    </style> 

    <script> 
$(function(){ 

    var canvas=document.getElementById("overlay"); 
    var ctx=canvas.getContext("2d"); 

    var img=new Image(); 
    img.onload=function(){ 
     ctx.drawImage(img,0,0,img.width,img.height,0,0,overlay.width,overlay.height); 
    } 
    img.src="http://dl.dropbox.com/u/139992952/stackoverflow/fish%20overlay.png"; 

    function draw(red,green,blue) { 
     ctx.save(); 
     ctx.globalCompositeOperation = 'source-in'; 
     ctx.fillStyle="rgb("+red+","+green+","+blue+")"; 
     ctx.beginPath(); 
     ctx.rect(0,0,overlay.width,overlay.height); 
     ctx.fill(); 
     ctx.restore(); 
    } 

    $("#red").click(function(){ draw(255,0,0); }); 
    $("#green").click(function(){ draw(0,255,0); }); 
    $("#blue").click(function(){ draw(0,0,255); }); 

    }); 

    </script> 

</head> 

<body> 
    <button id="red">Red Fish</button>  
    <button id="green">Green Fish</button> 
    <button id="blue">Blue Fish</button> 
    <div id="wrapper"> 
     <img id="base" src="http://dl.dropbox.com/u/139992952/stackoverflow/fish.png" width=350 height=250> 
     <canvas id="overlay" width=350 height=250></canvas> 
    </div> 
</body> 

</html> 
+0

哦,那太好了!感謝您的屏蔽技巧:) – NibblyPig

+0

我問的主要問題是,我應該直接從spritemap中繪製,還是在我的init()方法中,我應該將spritemap分隔成不同的圖像? – NibblyPig