Click area on sprite in canvas

I am creating a game in javascript. sprites are currently div elements with a background image that is updated to create animations. I heard that if I create canvas elements and fill the sprite onto the canvas, I can make sprite available by omitting the transparent areas.

I need a solution where you can click my sprites in the game, but the clicked area will correspond to the shape of the sprite. It must also be automatic. I cannot do this with ready-made clicks.

+7
source share
2 answers

I have a tutorial that is almost certainly suitable for impact testing. See the code here.

When you click, the code draws each shape (I use rectangles, but works great with translucent images) on the canvas in memory (ghostcanvas) and checks if the mouse pixel on the pixel is transparent.

Relevant code inserted below:

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(); } 
+7
source

You can have a transparent background and check images for transparency on a pixel with a click. Here is the code from one of my game prototypes:

 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; } 

Before you call, first check if there was a mouseclick in the entire image.

+5
source

All Articles