How do I check if a mouse click is inside a rotated text on the HTML5 Canvas in JavaScript?

后端 未结 2 1115
有刺的猬
有刺的猬 2021-01-28 05:06

I have drawn a text on the canvas in coordinates X, Y and saved them. I have a simple method that checks if a mouse click has happened inside the text boundaries. The problem is

2条回答
  •  没有蜡笔的小新
    2021-01-28 05:43

    Create a rect object which is rotated at the same angle as the text, but not drawn.

    Then use:

    // set transforms here.
    // add rect representing text region:
    ctx.beginPath();
    ctx.rect(x, y, w, h);  // region for text
    if (ctx.isPointInPath(mx, my)) {
        // we clicked inside the region
    }
    ctx.setTransform(1,0,0,1,0,0);  // reset transforms after test
    

    Demo:

    var canvas = document.querySelector("canvas"),
        ctx = canvas.getContext("2d"),
        txt = "ROTATED TEXT", tw, region;
    
    // transform and draw some rotated text:
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.font = "32px sans-serif";
    ctx.translate(150, 75);
    ctx.rotate(0.33);
    ctx.translate(-150, -75);
    ctx.fillText(txt, 150, 75);
    tw = ctx.measureText(txt).width;
    
    // define a region for text:
    region = {x: 150 - tw*0.5, y: 75 - 16, w: tw, h:32}; // approx. text region
    
    // function to check if mouse x/y is inside (transformed) region
    function isInText(region, x, y) {
      ctx.beginPath();
      ctx.rect(region.x, region.y, region.w, region.h);
      return ctx.isPointInPath(x, y);
    }
    
    // test for demo
    canvas.onmousemove = function(e) {
      var rect = canvas.getBoundingClientRect(),
          x = e.clientX - rect.left,
          y = e.clientY - rect.top;
      
      // just to visualize:
      ctx.clearRect(0,0,300,150);
      ctx.fillStyle = isInText(region, x, y) ? "red" : "black";
      ctx.fillText(txt, 150, 75);
    };

提交回复
热议问题