2011-09-29 26 views
1

我以這種方式創建圖像:我可以在畫布上打印圖像嗎?

var orc = new Image(); 
     orc.src = "./orc.png"; 

我用圖像中的物體是這樣的:

function Character(hp, image){ 
    this.hp = hp; 
    this.image = image; 
}; 

我把它幾次,如:

unit245 = new Character(100, orc); 

我畫它以這種方式,例如:

ctx.drawImage(unit245.image, 15, 55, 100, 100); 

如何讓鼠標點擊或移動到畫布上的單位245以上?

我需要的是這樣的http://easeljs.com/examples/dragAndDrop.html但沒有任何框架(除了jQuery的)

+0

鼠標座標已經回答了:http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas –

回答

0
在畫布上
function Item(img, x, y){ 
    this.image = img; 
    this.x = x; 
    this.y = y; 
    this.canv = document.createElement("canvas"); 
    this.canv.width = this.image.width; 
    this.canv.height = this.image.height; 
    this.ctx = this.canv.getContext('2d'); 
    this.ctx.drawImage(this.image, 0, 0, CELL_SIZE, CELL_SIZE);  
    this.hit = function (mx, my) { 
     var clr; 
     clr = this.ctx.getImageData(mx - this.x, my - this.y, 1, 1).data; 
     if (clr[3] > 250) { 
      //On object 
      this.image = gold_glow; 
     } else { 
      //Leave object 
      this.image = gold; 
     } 
    }; 
} 
0

HitTesting可以通過檢查什麼存在於當前位置在畫布上,這能夠在鼠標點擊調用或移動事件在完成畫布(這是命中測試的基礎)。這可以通過了解已放置在哪裏,如可以保存圖像的邊界,以及當用戶單擊某處或將鼠標移到畫布上時,可以檢查它是在圖像邊界內還是在圖像邊界之外。數組或列表可以用於此。

Here是如何可以做到這一點

0

你不能。畫布沒有你的unit245Character對象的外表。你將不得不實際手動檢查座標,看看它們是否落在你對角色的範圍之內。

例如(假設你的畫布是一個名爲變種帆布):

canvas.onclick = function(e) { 
    if (e.x >= unit245.x && e.x <= unit245.x + unit245.width && e.y >= unit245.y && e.y <= unit245.y + unit245.height) { 
    alert("You clicked unit245!"); 
    } 
} 

你的情況:

unit245.x = 15 
unit245.y = 55 
unit245.width = 100 
unit245.height = 100 
3

沒有內置的方法。我已經在making movable and selectable shapes on a Canvas上撰寫了一些教程,以幫助人們開始使用這種類型的東西。

總之,您需要記住您繪製的內容和位置,然後檢查每個鼠標單擊以查看您是否點擊過某個內容。

相關問題