How to get a pixel's x,y coordinate color from an image?

后端 未结 4 1903
时光说笑
时光说笑 2020-11-22 09:00

Is there any way to check if a selected(x,y) point of a PNG image is transparent?

4条回答
  •  情书的邮戳
    2020-11-22 09:38

    Canvas would be a great way to do this, as @pst said above. Check out this answer for a good example:

    getPixel from HTML Canvas?

    Some code that would serve you specifically as well:

    var imgd = context.getImageData(x, y, width, height);
    var pix = imgd.data;
    
    for (var i = 0, n = pix.length; i < n; i += 4) {
      console.log pix[i+3]
    }
    

    This will go row by row, so you'd need to convert that into an x,y and either convert the for loop to a direct check or run a conditional inside.

    Reading your question again, it looks like you want to be able to get the point that the person clicks on. This can be done pretty easily with jquery's click event. Just run the above code inside a click handler as such:

    $('el').click(function(e){
       console.log(e.clientX, e.clientY)
    }
    

    Those should grab your x and y values.

提交回复
热议问题