How do I check if a mouse click is inside a rotated text on the HTML5 Canvas in JavaScript?(如何检查鼠标单击是否在 JavaScript 中 HTML5 Canvas 上的旋转文本内?)
问题描述
我在画布上以 X、Y 坐标绘制了一个文本并保存了它们.我有一个简单的方法来检查是否在文本边界内发生了鼠标单击.问题是当我将文本旋转 45 度时,我无法检查旋转后的文本中是否发生了鼠标点击.
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 when I rotate the text 45 Degree I cannot check whether a mouse click has happened within the rotated text or not.
简而言之,如何检查鼠标点击是否在旋转的文本或形状内?
In short, how can I check whether a mouse click is inside a rotated text or shape?
推荐答案
创建一个与文本同角度旋转的矩形对象,但不绘制.
Create a rect object which is rotated at the same angle as the text, but not drawn.
然后使用:
// 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
演示:
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);
};
<canvas></canvas>
这篇关于如何检查鼠标单击是否在 JavaScript 中 HTML5 Canvas 上的旋转文本内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检查鼠标单击是否在 JavaScript 中 HTML5 Canvas 上的旋转文本内?


基础教程推荐
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 直接将值设置为滑块 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01