点击画布上精灵的区域 [英] Click area on sprite in canvas
问题描述
我在javascript中创建一个游戏。当前sprite是具有背景图像的div元素,其被更新以创建动画。我听说,如果我使元素画布和blit的sprite到画布上,我可以使sprite可点击,省略透明区域。
I'm creating a game in javascript. currently the sprites are div elements with a background image that is updated to create animation. I have heard that if i make the elements canvas and blit the sprite onto the canvas I can make the sprite clickable, omitting the transparent areas.
我需要一个解决方案,我的可以点击游戏子画面,但是可点击区域适合于子画面的形状。它还需要自动。我不能用预制点击映射来做到这一点。
I need a solution where my game sprites can be clicked but the clickable area is fitted to the shape of the sprite. It also needs the be automatic. I cannot do this with premade click maps.
推荐答案
我有一个教程, 。请参阅此处代码。
I have a tutorial that does almost exactly what you need for the hit-testing. See the code here.
当你点击,代码绘制每个形状(我使用矩形,但它的工作精美的半透明图像)到内存中的画布(ghostcanvas),并检查鼠标像素是否在一个像素
When you click, the code draws each shape (I use rectangles but it works beautifully with semi-transparent images) to a canvas in memory (ghostcanvas) and checks to see if the mouse pixel is on a pixel that is not-transparent.
相关代码贴在下面:
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();
}
这篇关于点击画布上精灵的区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!