单击画布中精灵的区域 [英] Click area on sprite in canvas

查看:25
本文介绍了单击画布中精灵的区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 pre-made 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆