簡體   English   中英

如何重置畫布上下文的比例?

[英]How can I reset the scale of a canvas' context?

我有一個變量context,它是畫布的2d上下文。

var canvas = document.getElementById('canvas');
context = canvas.getContext('2d');

多次調用context.scale(x,y)根據之前的縮放比例縮放上下文。 例如, context.scale(2,2); context.scale(2,2) context.scale(2,2); context.scale(2,2)等效於context.scale(4,4) 如何重置上下文的縮放比例?

scale會將當前變換矩陣乘以比例尺矩陣,因此,這些比例尺因子的確會相乘。 您可以使用狀態堆棧來保存和還原當前轉換:

context.save();
context.scale(2, 2);
... // anything drawn here is twice as big
context.restore();

或者,您可以通過直接加載單位矩陣來重置轉換:

context.scale(2, 2);
...
context.setTransform(1, 0, 0, 1, 0, 0);

以下方法更加清晰,但是它是實驗性的。 也就是說,除IE和Edge之外的所有東西都支持它。

context.resetTransform();

截至2019年,明智的選擇仍然是:

ctx.setTransform(1, 0, 0, 1, 0, 0);

https://developer.mozilla.org/zh-CN/docs/Web/API/CanvasRenderingContext2D/resetTransform#Browser_compatibility

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM