JSFiddle - React, Tailwind, and code Playground

by victorrseloy

HTML

<canvas id="canvas" width="200" height="200"></>

JavaScript

var createClickMap = function(canvas, x, y, w, h, f){
    var m = function(x, y, w, h, mx, my){
        
        var xEnd = (x+w);
            yEnd = (y+h);
        

        if(mx > x && mx < xEnd){
          
            if(my > y && my < yEnd){
                return true;
            }    
        }
    
        return false;
    };
    
        canvas.canvas.addEventListener('click',function(v){
        var mX = v.pageX - this.offsetLeft,
            mY = v.pageY - this.offsetTop;
            
            if(m(x, y, w, h, mX, mY)){
                f();
            }
        
    });

}

var drawRectangle = function(context, x, y, w, h, f) {
    
    context.beginPath();
    context.rect(x, y, w, h);
    context.closePath();

    context.fill();
    
    if(typeof f == "function"){
        createClickMap (canvas, x, y, w, h, f);
    }
}
  
    
var canvas =  document.getElementById("canvas").getContext("2d")
var fn1 = function(){alert(1);}
var fn2 = function(){alert(2);}
drawRectangle(canvas,5,5,50,50,fn1 )
canvas.fillStyle = "red";
drawRectangle(canvas,100,100,50,50,fn2 )