Hit detection on non-transparent pixel

后端 未结 3 1943
[愿得一人]
[愿得一人] 2020-12-16 17:49

Given a PNG in a web context with some transparent pixels and some non-transparent pixels, is there a way in Javascript to determine if a user has clicked on a non-transpare

相关标签:
3条回答
  • 2020-12-16 18:24

    1) Create HTML5 canvas of same size as your image
    2) Get Canvas's context, drawImage(yourImage, 0, 0)
    3) d = context.getImageData(0, 0, w of img, h of img)
    4) d.data[(y*width+x)*4+3] for the alpha

    canvas = document.createElement("canvas");  //Create HTML5 canvas: supported in latest firefox/chrome/safari/konquerer.  Support in IE9
    canvas.width = img.width;                   //Set width of your rendertarget
    canvas.height = img.height;                 // \  height \   \     \
    ctx = canvas.getContext("2d");              //Get the 2d context [the thing you draw on]
    ctx.drawImage(img, 0, 0);                   //Draw the picture on it.
    id = ctx.getImageData(0,0, img.width, img.height);  //Get the pixelData of image
    //id.data[(y*width+x)*4+3] for the alpha value of pixel at x,y, 0->255
    
    0 讨论(0)
  • 2020-12-16 18:46

    I know these things are out of fashion these days, but HTML image maps are still valid, and can accomplish adding hit targets to nearly-arbitrary shapes within an image. If you don't actually want to reload another page on click, you could probably change the anchor in the URL with this technique and pick up the change with a Javascript interval.

    0 讨论(0)
  • 2020-12-16 18:50

    Canvas is the way to go for this purpose. But also remember that older internet explorer versions will not be capable of the getImageData() function. Even if you include excanvas.

    I made a small jquery plugin exactly for this purpose, maybe it will help you solving your problem without to completely reinvent the wheel. http://www.cw-internetdienste.de/pixelselection/

    0 讨论(0)
提交回复
热议问题