从Javascript画布获取点的未平移、未旋转(x,y)坐标
在Javascript中,我们通常在发送东西之前通过旋转和平移坐标平面来呈现图形从Javascript画布获取点的未平移、未旋转(x,y)坐标,javascript,geometry,canvas,translation,rotation,Javascript,Geometry,Canvas,Translation,Rotation,在Javascript中,我们通常在发送东西之前通过旋转和平移坐标平面来呈现图形 ctx.save(); ctx.translate(someX, someY); ctx.rotate(someAngle * Math.PI / 180); ctx.beginPath(); ctx.moveTo(x1, y1); // What's the actual (x1,y1)? ctx.lineTo(x2, y2); // What's the actual (x2,y2)? ctx.s
ctx.save();
ctx.translate(someX, someY);
ctx.rotate(someAngle * Math.PI / 180);
ctx.beginPath();
ctx.moveTo(x1, y1); // What's the actual (x1,y1)?
ctx.lineTo(x2, y2); // What's the actual (x2,y2)?
ctx.stroke();
ctx.restore();
既然这样做了,我该如何计算我所画线段端点的实际值呢?因为在平移和旋转之后,(x1,y1)和(x2,y2)离没有平移和旋转的地方很远。有没有一种简单的方法可以找出它们的实际值是什么?我认为唯一的方法是对想要知道实际坐标的点应用与渲染上下文相同的变换。一些库提供矩阵运算,如:
您可以尝试对执行旋转操作。目前无法获取当前变换矩阵,因此您需要自己跟踪任何旋转/平移/缩放 要实际执行转换,需要将转换矩阵乘以点(作为列向量) 您可以重写影响转换的方法来存储您自己的矩阵副本。我还没有测试过这段代码,但类似的东西应该可以工作:
var contextPrototype = CanvasRenderingContext2D.prototype;
contextPrototype.xform = Matrix.I(3);
contextPrototype.realSave = contextPrototype.save;
contextPrototype.save = function() {
if (!this.xformStack) {
this.xformStack = [];
}
this.xformStack.push(this.xform.dup());
this.realSave();
}
contextPrototype.realRestore = contextPrototype.restore;
contextPrototype.restore = function() {
if (this.xformStack && this.xformStack.length > 0) {
this.xform = this.xformStack.pop();
}
this.realRestore();
}
contextPrototype.realScale = contextPrototype.scale;
contextPrototype.scale = function(x, y) {
this.xform = this.xform.multiply($M([
[x, 0, 0],
[0, y, 0],
[0, 0, 1]
]));
this.realScale(x, y);
}
contextPrototype.realRotate = contextPrototype.rotate;
contextPrototype.rotate = function(angle) {
var sin = Math.sin(angle);
var cos = Math.cos(angle);
this.xform = this.xform.multiply($M([
[cos, -sin, 0],
[sin, cos, 0],
[ 0, 0, 1]
]));
this.realRotate(angle);
}
contextPrototype.realTranslate = contextPrototype.translate;
contextPrototype.translate = function(x, y) {
this.xform = this.xform.multiply($M([
[1, 0, x],
[0, 1, y],
[0, 0, 1]
]));
this.realTranslate(x, y);
}
contextPrototype.realTransform = contextPrototype.transform;
contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) {
this.xform = this.xform.multiply($M([
[m11, m21, dx],
[m12, m22, dy],
[ 0, 0, 1]
]));
this.realTransform(m11, m12, m21, m22, dx, dy);
}
contextPrototype.realSetTransform = contextPrototype.setTransform;
contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) {
this.xform = $M([
[m11, m21, dx],
[m12, m22, dy],
[ 0, 0, 1]
]);
this.realSetTransform(m11, m12, m21, m22, dx, dy);
}
为了方便起见,我使用了乘法器,但你可以自己做乘法
要获得变换点,只需将变换矩阵乘以该点:
// Get the transformed point as [x, y]
contextPrototype.getTransformedPoint = function(x, y) {
var point = this.xform.multiply($V([x, y, 1]));
return [point.e(1), point.e(2)];
}
这也需要实现save()和restore(),但它看起来恰到好处,应该打上复选标记。这很好地完成了…非常好,谢谢!!虽然我不明白为什么他们在原著中没有想到这一点/