我使用绝对定位将多个画布元素叠加在一起。每个画布中都有一些透明空间。当我点击这一叠画布时,我得到了点击事件发生的像素值,并确定该像素是否透明,如下所示:
var context = this.element.getContext('2d');
var rect = this.element.getBoundingClientRect();
var x = Math.round(event.clientX - rect.left);
var y = Math.round(event.clientY - rect.top);
var pixelData = context.getImageData(x, y, 1, 1).data;
if (pixelData[3] === 0) {
console.log('Transparent!')
}
当像素是透明的时,我希望将此图层视为具有css属性pointer-event: none;
,这会导致click事件传递到下一层。
有没有办法实现这个目标?
答案 0 :(得分:1)
如果您有一个canvas元素数组,则只需单击当前画布下方的画布即可。像这样:
var canvasElements = new Array();
canvasElements[0] = canvas.element.getContext('2d');
canvasElements[1] = canvas2.element.getContext('2d');
canvasElements[2] = canvas3.element.getContext('2d');
然后当你运行测试时:
var context = this.element.getContext('2d');
var rect = this.element.getBoundingClientRect();
var x = Math.round(event.clientX - rect.left);
var y = Math.round(event.clientY - rect.top);
for(var i = 0; i < canvasElements.length; i++){
var pixelData = canvasElements[1].getImageData(x, y, 1, 1).data;
if (pixelData[3] === 0) {
console.log('Transparent!');
} else {
break;
//clicked canvas i
}
}