Simple Button in HTML5 canvas

后端 未结 2 1204
感动是毒
感动是毒 2020-12-31 05:32

I am new to Javascript and i am in the process of making a project web based (HTML) With my basic knowledge i have managed to create a form and drawn a rectangle on it.

2条回答
  •  攒了一身酷
    2020-12-31 05:40

    Path2d may be of interest, though it's experimental:

    https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/isPointInPath

    Basically, you'd do all of your drawing into a Path, and use the .isPointInPath method to do the checking. For a rectangle like you're describing, you can do that math pretty simply, but the glory of this is you can have a complex path set up, and it will do the collision detection for you:

    //get canvas/context
    const canvas = document.getElementById("myCanvas")
    const context = canvas.getContext("2d")
    
    //create your shape data in a Path2D object
    const path = new Path2D()
    path.rect(250, 350, 200, 100)
    path.rect(25,72,32,32)
    path.closePath()
    
    //draw your shape data to the context
    context.fillStyle = "#FFFFFF"
    context.fillStyle = "rgba(225,225,225,0.5)"
    context.fill(path)
    context.lineWidth = 2
    context.strokeStyle = "#000000"
    context.stroke(path)
    
    function getXY(canvas, event){ //adjust mouse click to canvas coordinates
      const rect = canvas.getBoundingClientRect()
      const y = event.clientY - rect.top
      const x = event.clientX - rect.left
      return {x:x, y:y}
    }
    
    document.addEventListener("click",  function (e) {
      const XY = getXY(canvas, e)
      //use the shape data to determine if there is a collision
      if(context.isPointInPath(path, XY.x, XY.y)) {
        // Do Something with the click
        alert("clicked in rectangle")
      }
    }, false)
    

    jsFiddle

提交回复
热议问题