In my Ionic 4 drawing app, I have incorporated an image of the number 1 on the canvas using drawImage and made the background transparent. If users (typically kids) draw outside the number 1 image, the accuracy percentage will decrease. While searching for a solution, I couldn't find anything specific but discovered a method to check if a pixel is transparent or not by clicking.
isTransparent(x, y) { // x, y coordinate of pixel
let alpha = this.ctx.getImageData(x, y, 1, 1).data[3]; // 3rd byte is alpha
if (alpha === 0) {
this.accuracy = 0;
console.log("Transparent image clicked!");
} else {
this.accuracy = 100;
console.log("image clicked!");
}
}
You can view the code sample on GitHub and try out the live Demo here.