I'm using this script that claims to implement matrix3d operation as described in the spec, however the script is missing matrix perspective operations, so I "cooked" something I'm not sure is either accurate or correct.
// the perspective matrix to multiply with
CSSMatrix.Perspective = function(x, y, z){
var m = new CSSMatrix();
m.m13 = x;
m.m23 = y;
m.m33 = z;
return m;
};
and the method to use this matrix
// myMatrix.perspective(x,y,z); to apply a perspective matrix
CSSMatrix.prototype.perspective = function(x, y, z){
if (y == null) y = 0;
if (z == null) z = 0;
return CSSMatrix.multiply(this, CSSMatrix.Perspective(x, y, z));
};
My question is, if y
and z
are undefined
, what values should be used? Is it gonna be like rotate where x
is used for all other axis, or 0 (zero) as in the above code?
I'm also not sure if CSSMatrix.Perspective
matrix is properly written as described in the spec and implemented into the CSSMatrix
prototype.
UPDATE: I've found another implementation of the perspective functions (see below) and created a fiddle to demonstrate it's not working as well.
CSSMatrix.prototype.perspective = function(d){
return CSSMatrix.multiply(this, CSSMatrix.Perspective(d));
};
CSSMatrix.Perspective = function(d){
var m = new CSSMatrix();
m.m43 = -1/d;
return m;
};
Why the two values are different please?
Thank you for any reply.
The issue here seems to be how the 3d matrix is represented in the spec/docs (e.g. Mozilla CDN docs) vs how it's represented in the CSSMatrix polyfill's code. The code uses a transposed version of the matrix represented in the docs. The code works correctly but what the code refers to as the matrix position [3,4] is actually position [4,3] if we consider the maxtrix used in the spec/docs.
Regarding the formula for calculating perspective: as per the MDN docs here, the following matrix should be used/multiplied for applying the perspective (
d
is the perspective value):So you were along the right path, but you were contructing the perspective matrix incorrectly because of the way the polyfill's code references the matrix internally. Instead of
m.m43 = -1/d;
, usem.m34 = -1/d;
I've updated the fiddle with the fixed code here.
As per the spec for the 'Perspective' property, it accepts only one parameter and that is 'length'. It doesn't accept, X, Y and Z.
Ref: W3ORG - Perspective Property
Ref: W3School's Perspective Example
I know, that I haven't given you the solution for your Perspective, but what's written is not the intended behavior. If my understanding about your question is wrong, please let me know, will try to help you with what I can. Thanks.