[英]Can I get the current angle of rotation of my canvas context?
我想知道是否有辦法獲得畫布的旋轉角度。 而不是使用這樣的變量來跟蹤它:
var angle = 0; // keeps track of the current angle of the ctx
ctx.rotate( Math.PI / 2 );
angle+= Math.Pi / 2;
...
ctx.rotate( Math.Pi / 7 );
angle+= Math.Pi / 7;
在現代瀏覽器中,您可以使用ctx.currentTransform
屬性。
但不幸的是,它仍然沒有得到廣泛支持(實際上在撰寫本文時它僅在 chrome 中),因此您可能仍然希望在應用它時記錄您的轉換,IIRC,網上有一些庫可以做到這一點。
所以,對於 chrome 和未來的瀏覽器(在某種程度上也是 FF 今天),你可以得到這個變換矩陣,然后你必須得到[a, b, c, d , e, f]
中b
和a
值的反正切[a, b, c, d , e, f]
矩陣。
// returns the current rotation in radians, ranged [0, 2π] function getRotation() { let t = getTransform(ctx); let rad = Math.atan2(tb, ta); if (rad < 0) { // angle is > Math.PI rad += Math.PI * 2; } return rad; } const ctx = document.createElement('canvas').getContext('2d'); function setAngle() { ctx.setTransform(1, 0, 0, 1, 0, 0); // reset the transform matrix let angle = Math.random() * Math.PI * 2; ctx.rotate(angle); console.log(angle, getRotation()); } btn.onclick = setAngle; // Try to support FF // this is only a getter, and it doesn't implement the SVGMatrix's methods if not supported function getTransform(ctx) { if ('currentTransform' in ctx) { return ctx.currentTransform } // restructure FF's array to an Matrix like object else if (ctx.mozCurrentTransform) { let a = ctx.mozCurrentTransform; return {a:a[0], b:a[1], c:a[2], d:a[3], e:a[4], f:a[5]}; } }
<button id="btn">set and get rotation</button>
您可能會注意到設置的角度和得到的角度並不完全相同(至少在 FF 中),我會將其放在舍入問題的后面。
您可以修改CanvasRenderingContext2D
的prototype
來支持這一點。
打字稿代碼
這可確保編輯器將為context.rotation
屬性顯示正確的代碼完成。
interface CanvasRenderingContext2D {
rotation: number;
}
{
const rotate = CanvasRenderingContext2D.prototype.rotate;
Object.assign(CanvasRenderingContext2D.prototype, {
rotate (angle: number) {
rotate.call(this, angle);
this.rotation += angle;
},
rotation: 0
});
}
JavaScript 代碼
如果您不知道 TypeScript 是什么,請使用它。
{
const rotate = CanvasRenderingContext2D.prototype.rotate;
Object.assign(CanvasRenderingContext2D.prototype, {
rotate (angle) {
rotate.call(this, angle);
this.rotation += angle;
},
rotation: 0
});
}
用法
執行上述代碼后創建的任何上下文都將具有rotation
屬性。 對於弧度,請使用context.rotation
。 對於度數,請使用context.rotation * 180 / Math.PI
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.