[英]Click area on sprite in canvas
我正在用 Javascript 創建一個游戲。 目前,精靈是帶有更新以創建動畫的背景圖像的 div 元素。 我聽說如果我制作元素畫布並將精靈 blit 到畫布上,我可以使精靈可點擊,省略透明區域。
我需要一個解決方案,可以點擊我的游戲精靈,但可點擊區域適合精靈的形狀。 它還需要是自動的。 我不能用預制的點擊地圖來做到這一點。
我有一個教程,幾乎完全符合您進行命中測試所需的操作。 請參閱此處的代碼。
當您單擊時,代碼將每個形狀(我使用矩形,但它與半透明圖像配合得很好)繪制到內存中的畫布 (ghostcanvas) 並檢查鼠標像素是否位於不透明的像素上。
貼出相關代碼如下:
function myDown(e){
getMouse(e);
clear(gctx); // clear the ghost canvas from its last use
// run through all the boxes
var l = boxes.length;
for (var i = l-1; i >= 0; i--) {
// draw shape onto ghost context
drawshape(gctx, boxes[i], 'black');
// get image data at the mouse x,y pixel
var imageData = gctx.getImageData(mx, my, 1, 1);
var index = (mx + my * imageData.width) * 4;
// if the mouse pixel exists, select and break
if (imageData.data[3] > 0) {
mySel = boxes[i];
offsetx = mx - mySel.x;
offsety = my - mySel.y;
mySel.x = mx - offsetx;
mySel.y = my - offsety;
isDrag = true;
canvas.onmousemove = myMove;
invalidate();
clear(gctx);
return;
}
}
// havent returned means we have selected nothing
mySel = null;
// clear the ghost canvas for next time
clear(gctx);
// invalidate because we might need the selection border to disappear
invalidate();
}
您可以將背景設置為透明,並在單擊的像素處檢查圖像的透明度。 這是我的一個游戲原型中的一些代碼:
function getAlphaInImage(img, x, y) {
var tmp = document.createElement("CANVAS");
tmp.setAttribute('width', img.width);
tmp.setAttribute('height', img.height);
var tmpCtx = tmp.getContext('2d');
tmpCtx.drawImage(img, 0, 0);
var imageData = tmpCtx.getImageData(x, y, 1, 1);
var alpha = imageData.data[3];
tmp = null;
imageData = null;
return alpha;
}
在調用之前,我首先檢查鼠標點擊是否在整個圖像內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.