Dectect click in irregular shapes inside HTML5 canvas

偶尔善良 提交于 2020-01-17 03:38:05

问题


I am new using canvas and I created a simple script to draw irregular polygons in a canvas knowing the coord. Now I need to detect if an user clicks on one of those shapes and wich one (each object has an ID). You can see my script working here.

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
var objetos = [];

// First Shape
objetos.push( {
  id:'First',
    coordinates: {
        p1: {
            x: 30,
            y: 10
        },
        p2: {
            x: 50,
            y: 50
        },
        p3: {
            x: 90,
            y: 90
        },
        p4: {
            x: 50,
            y: 90
        },
    }
});

// Second Shape
objetos.push( {
  id:'Two',
    coordinates: {
        p1: {
            x: 150,
            y: 20
        },
        p2: {
            x: 90,
            y: 50
        },
        p3: {
            x: 90,
            y: 30
        },
    }
});

// 3th Shape
objetos.push( {
  id:'Shape',
    coordinates: {
        p1: {
            x: 150,
            y: 120
        },
        p2: {
            x: 160,
            y: 120
        },
        p3: {
            x: 160,
            y: 50
        },
        p4: {
            x: 150,
            y: 50
        },
    }
});

// Read each object
for (var i in objetos){
    // Draw rhe shapes
    ctx.beginPath();
    var num = 0;
    for (var j in objetos[i].coordinates){

        if(num==0){
            ctx.moveTo(objetos[i].coordinates[j]['x'], objetos[i].coordinates[j]['y']);
        }else{
            ctx.lineTo(objetos[i].coordinates[j]['x'], objetos[i].coordinates[j]['y']);
        }
        num++;
    }
    ctx.closePath();
    ctx.lineWidth = 2;
    ctx.fillStyle = '#8ED6FF';
    ctx.fill();
    ctx.strokeStyle = 'blue';
    ctx.stroke();
}

NOTE: A cursor pointer on hover would be appreciated. =)

EDIT: Note I am using irregular shapes with no predefined number of points. Some scripts (like those on pages linked as "Possible duplication") using circles or regular polygons (certain number of sides with the same lengh do not solve my issue).

来源:https://stackoverflow.com/questions/38111481/dectect-click-in-irregular-shapes-inside-html5-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!