gpt4 book ai didi

javascript - 单击 Canvas 中 Sprite 上的区域

转载 作者:数据小太阳 更新时间:2023-10-29 04:32:54 24 4
gpt4 key购买 nike

我正在用 Javascript 创建游戏。目前, Sprite 是带有背景图像的 div 元素,更新后可以创建动画。我听说如果我制作元素 Canvas 并将 Sprite blit 到 Canvas 上,我可以使 Sprite 可点击,省略透明区域。

我需要一个可以点击我的游戏 Sprite 但可点击区域适合 Sprite 形状的解决方案。它还需要是自动的。我无法使用预制的点击 map 执行此操作。

最佳答案

我有一个教程几乎完全可以满足您的 HitTest 需求。查看代码 here.

当您单击时,代码将每个形状(我使用矩形,但它与半透明图像一起工作时效果很好)绘制到内存中的 Canvas (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();
}

关于javascript - 单击 Canvas 中 Sprite 上的区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5948251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com