缩放后在画布上绘图

时间:2017-02-06 17:30:20

标签: javascript canvas html5-canvas zoom draw

我正在研究一种在画布上呈现形状的HTML5应用程序。用户使用自由绘图绘制形状。

由于这个答案,我实施了缩放:https://stackoverflow.com/a/6776341/

但是,一旦画布缩放,当用户继续绘制时,线条会显示偏移量。问题是如何平移点,以便再次在光标下绘制线条?

1 个答案:

答案 0 :(得分:0)

当您从<canvas>元素获得鼠标坐标时,就DOM而言,它们与元素的高度和宽度相关。它们不会根据您缩放画布的上下文的方式而改变。为了获得光标下画布的坐标,你必须转换它们以匹配画布的当前变换。

// mouse event coordinates
var mouseX;
var mouseY;

// current canvas transforms
var originX;
var originY;
var scale;

// adjust mouse coordinates with canvas context's transforms
var canvasX = mouseX / scale + originX;
var canvasY = mouseY / scale + originY;

// should draw a rectangle with the cursor being directly in the center
context.fillRect(canvasX - 10, canvasY - 10, 20, 20);