Javascript在画布旋转时找到像素

我正在尝试在画布上编写旋转文本(在各种角度),但希望不要重叠文本.因此,在旋转画布之后,在填充文本之前,我尝试使用measureText().width和get
ImageData()来测试文本背景,以查看没有文本已经在那里搞乱了.旋转画布时,我找不到文本(彩色像素).这是我的问题的简化版本(使用矩形).我想知道为什么没有找到彩色像素?

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid black;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>

var cWidth=300, cHeight= 150;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

// Rotate context around centre point
ctx.translate( cWidth/2, cHeight/2);
ctx.rotate(20 * Math.PI / 180);

// Draw 100x50px rectangle at centre of rotated ctx
ctx.fillStyle = "yellow";
ctx.fillRect(-50, -25, 100, 50);

// Is my rotated rectangle really there? 
// i.e. any coloured pixels at rotated cxt centre
imgData = ctx.getImageData(-50, -25, 100, 50);

// All rectangle pixels should be coloured
for (var j=0; j<imgData.data.length; j++){
	if (imgData.data[j] > 0){
		alert ("Coloured");
		break;
	};
};

// Why none is found?

</script>

</body>
</html>

黄色矩形应与测试图像数据区域位于相同的点和角度.什么地方出了错?我如何测试旋转区域的颜色?作为Javascript的新手,我试着在这个阶段避免使用库.

佩卡

最佳答案 你的代码的问题是getImageData()是针对画布的错误部分. x和y坐标应具有与translate()函数相同的值.这就是你的代码应该是这样的:

// Translate the rectangle, rotate it and fill it 
ctx.translate(cWidth/2, cHeight/2);
ctx.rotate(20 * Math.PI / 180);
ctx.fillStyle = "yellow";
ctx.fillRect(-50, -25, 100, 50);

// Get the rectangle rotation
var imgData = ctx.getImageData(cWidth/2, cHeight/2, 100, 50);

这是完整代码的JSfiddle.我希望我的回答可以帮到你!

点赞