我正在尝试在 Canvas 上(以各种 Angular )书写旋转文本,但不希望文本重叠。因此,在旋转 Canvas 之后和填充文本之前,我尝试使用 measureText().width
和 getImageData()
来测试文本背景,以查看是否已经没有文本弄乱新的。旋转 Canvas 时我找不到文本(彩色像素)。这是我的问题的简化版本(使用矩形)。我想知道为什么没有找到彩色像素?
<!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>
佩卡
最佳答案
问题是翻译功能。您需要考虑位移。
试试这个:
imgData = ctx.getImageData(-50+cWidth/2,-25+cHeight/2,100,50);
关于Javascript 在 Canvas 旋转时查找像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38048356/