Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active December 22, 2022 18:47
Show Gist options
  • Save mbostock/10591444 to your computer and use it in GitHub Desktop.
Save mbostock/10591444 to your computer and use it in GitHub Desktop.
Perspective Transformation II
license: gpl-3.0

A perspective projection can be precisely specified through four pairs of corresponding points. By dragging the four corners of the grid above, you can adjust the perspective projection interactively and place the grid anywhere you like in the scene.

The points of the grid are transformed using a transformation matrix, which is computed by solving a series of linear equations derived from the four point-pairs using LU decomposition as implemented by numeric.js.

This technique can also be used to compute a CSS matrix3d transform to place a DOM element within a scene.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
position: relative;
width: 960px;
height: 500px;
}
#background {
width: 960px;
height: 500px;
background: url(mosque.jpg);
}
svg {
position: absolute;
top: 0;
left: 0;
}
.line {
stroke: cyan;
stroke-width: 1.5px;
stroke-linecap: square;
}
.handle {
fill: none;
pointer-events: all;
stroke: #fff;
stroke-width: 2px;
cursor: move;
}
#buttons {
position: absolute;
top: 20px;
left: 20px;
z-index: 2;
}
button {
display: block;
width: 10em;
}
button:focus {
outline: none;
}
</style>
<div id="background"></div>
<div id="buttons">
<button data-targets="[[492,329],[542,330],[569,434],[424,424]]">Floor</button>
<button data-targets="[[-28,287],[74,288],[72,413],[-31,404]]">Near Wall</button>
<button data-targets="[[-194,282],[-95,282],[-100,354],[-200,365]]">Far Wall</button>
<button data-targets="[[0,0],[400,0],[400,400],[0,400]]">Reset</button>
</div>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="numeric-solve.min.js"></script>
<script>
var margin = {top: 50, right: 280, bottom: 50, left: 280},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var sourcePoints = [[0, 0], [width, 0], [width, height], [0, height]],
targetPoints = [[0, 0], [width, 0], [width, height], [0, height]];
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var line = svg.selectAll(".line")
.data(d3.range(0, width + 1, 40).map(function(x) { return [[x, 0], [x, height]]; })
.concat(d3.range(0, height + 1, 40).map(function(y) { return [[0, y], [width, y]]; })))
.enter().append("path")
.attr("class", "line line--x");
var handle = svg.selectAll(".handle")
.data(targetPoints)
.enter().append("circle")
.attr("class", "handle")
.attr("transform", function(d) { return "translate(" + d + ")"; })
.attr("r", 7)
.call(d3.behavior.drag()
.origin(function(d) { return {x: d[0], y: d[1]}; })
.on("drag", dragged));
d3.selectAll("button")
.datum(function(d) { return JSON.parse(this.getAttribute("data-targets")); })
.on("click", clicked)
.call(transformed);
function clicked(d) {
d3.transition()
.duration(750)
.tween("points", function() {
var i = d3.interpolate(targetPoints, d);
return function(t) {
handle.data(targetPoints = i(t)).attr("transform", function(d) { return "translate(" + d + ")"; });
transformed();
};
});
}
function dragged(d) {
d3.select(this).attr("transform", "translate(" + (d[0] = d3.event.x) + "," + (d[1] = d3.event.y) + ")");
transformed();
}
function transformed() {
for (var a = [], b = [], i = 0, n = sourcePoints.length; i < n; ++i) {
var s = sourcePoints[i], t = targetPoints[i];
a.push([s[0], s[1], 1, 0, 0, 0, -s[0] * t[0], -s[1] * t[0]]), b.push(t[0]);
a.push([0, 0, 0, s[0], s[1], 1, -s[0] * t[1], -s[1] * t[1]]), b.push(t[1]);
}
var X = solve(a, b, true), matrix = [
X[0], X[3], 0, X[6],
X[1], X[4], 0, X[7],
0, 0, 1, 0,
X[2], X[5], 0, 1
].map(function(x) {
return d3.round(x, 6);
});
line.attr("d", function(d) {
return "M" + project(matrix, d[0]) + "L" + project(matrix, d[1]);
});
}
// Given a 4x4 perspective transformation matrix, and a 2D point (a 2x1 vector),
// applies the transformation matrix by converting the point to homogeneous
// coordinates at z=0, post-multiplying, and then applying a perspective divide.
function project(matrix, point) {
point = multiply(matrix, [point[0], point[1], 0, 1]);
return [point[0] / point[3], point[1] / point[3]];
}
// Post-multiply a 4x4 matrix in column-major order by a 4x1 column vector:
// [ m0 m4 m8 m12 ] [ v0 ] [ x ]
// [ m1 m5 m9 m13 ] * [ v1 ] = [ y ]
// [ m2 m6 m10 m14 ] [ v2 ] [ z ]
// [ m3 m7 m11 m15 ] [ v3 ] [ w ]
function multiply(matrix, vector) {
return [
matrix[0] * vector[0] + matrix[4] * vector[1] + matrix[8 ] * vector[2] + matrix[12] * vector[3],
matrix[1] * vector[0] + matrix[5] * vector[1] + matrix[9 ] * vector[2] + matrix[13] * vector[3],
matrix[2] * vector[0] + matrix[6] * vector[1] + matrix[10] * vector[2] + matrix[14] * vector[3],
matrix[3] * vector[0] + matrix[7] * vector[1] + matrix[11] * vector[2] + matrix[15] * vector[3]
];
}
</script>
GENERATED_FILES = \
numeric-solve.min.js
all: $(GENERATED_FILES)
clean:
rm -rf -- $(GENERATED_FILES) build
numeric-solve.min.js: numeric-solve.js
node_modules/.bin/uglifyjs numeric-solve.js -c -m -o $@
numeric.js
Copyright (C) 2011 by Sébastien Loisel
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(function() {
var abs = Math.abs;
function _foreach2(x, s, k, f) {
if (k === s.length - 1) return f(x);
var i, n = s[k], ret = Array(n);
for (i = n - 1; i >= 0; --i) ret[i] = _foreach2(x[i], s, k + 1, f);
return ret;
}
function _dim(x) {
var ret = [];
while (typeof x === "object") ret.push(x.length), x = x[0];
return ret;
}
function dim(x) {
var y, z;
if (typeof x === "object") {
y = x[0];
if (typeof y === "object") {
z = y[0];
if (typeof z === "object") {
return _dim(x);
}
return [x.length, y.length];
}
return [x.length];
}
return [];
}
function cloneV(x) {
var _n = x.length, i, ret = Array(_n);
for (i = _n - 1; i !== -1; --i) ret[i] = x[i];
return ret;
}
function clone(x) {
return typeof x !== "object" ? x : _foreach2(x, dim(x), 0, cloneV);
}
function LU(A, fast) {
fast = fast || false;
var i, j, k, absAjk, Akk, Ak, Pk, Ai,
max,
n = A.length, n1 = n - 1,
P = new Array(n);
if (!fast) A = clone(A);
for (k = 0; k < n; ++k) {
Pk = k;
Ak = A[k];
max = abs(Ak[k]);
for (j = k + 1; j < n; ++j) {
absAjk = abs(A[j][k]);
if (max < absAjk) {
max = absAjk;
Pk = j;
}
}
P[k] = Pk;
if (Pk != k) {
A[k] = A[Pk];
A[Pk] = Ak;
Ak = A[k];
}
Akk = Ak[k];
for (i = k + 1; i < n; ++i) {
A[i][k] /= Akk;
}
for (i = k + 1; i < n; ++i) {
Ai = A[i];
for (j = k + 1; j < n1; ++j) {
Ai[j] -= Ai[k] * Ak[j];
++j;
Ai[j] -= Ai[k] * Ak[j];
}
if (j===n1) Ai[j] -= Ai[k] * Ak[j];
}
}
return {
LU: A,
P: P
};
}
function LUsolve(LUP, b) {
var i, j,
LU = LUP.LU,
n = LU.length,
x = clone(b),
P = LUP.P,
Pi, LUi, tmp;
for (i = n - 1; i !== -1; --i) x[i] = b[i];
for (i = 0; i < n; ++i) {
Pi = P[i];
if (P[i] !== i) tmp = x[i], x[i] = x[Pi], x[Pi] = tmp;
LUi = LU[i];
for (j = 0; j < i; ++j) {
x[i] -= x[j] * LUi[j];
}
}
for (i = n - 1; i >= 0; --i) {
LUi = LU[i];
for (j = i + 1; j < n; ++j) {
x[i] -= x[j] * LUi[j];
}
x[i] /= LUi[i];
}
return x;
}
solve = function(A, b, fast) {
return LUsolve(LU(A, fast), b);
};
})();
!function(){function r(t,n,o,e){if(o===n.length-1)return e(t);var f,u=n[o],c=Array(u);for(f=u-1;f>=0;--f)c[f]=r(t[f],n,o+1,e);return c}function t(r){for(var t=[];"object"==typeof r;)t.push(r.length),r=r[0];return t}function n(r){var n,o;return"object"==typeof r?(n=r[0],"object"==typeof n?(o=n[0],"object"==typeof o?t(r):[r.length,n.length]):[r.length]):[]}function o(r){var t,n=r.length,o=Array(n);for(t=n-1;-1!==t;--t)o[t]=r[t];return o}function e(t){return"object"!=typeof t?t:r(t,n(t),0,o)}function f(r,t){t=t||!1;var n,o,f,u,a,h,i,l,g,v=r.length,y=v-1,b=new Array(v);for(t||(r=e(r)),f=0;v>f;++f){for(i=f,h=r[f],g=c(h[f]),o=f+1;v>o;++o)u=c(r[o][f]),u>g&&(g=u,i=o);for(b[f]=i,i!=f&&(r[f]=r[i],r[i]=h,h=r[f]),a=h[f],n=f+1;v>n;++n)r[n][f]/=a;for(n=f+1;v>n;++n){for(l=r[n],o=f+1;y>o;++o)l[o]-=l[f]*h[o],++o,l[o]-=l[f]*h[o];o===y&&(l[o]-=l[f]*h[o])}}return{LU:r,P:b}}function u(r,t){var n,o,f,u,c,a=r.LU,h=a.length,i=e(t),l=r.P;for(n=h-1;-1!==n;--n)i[n]=t[n];for(n=0;h>n;++n)for(f=l[n],l[n]!==n&&(c=i[n],i[n]=i[f],i[f]=c),u=a[n],o=0;n>o;++o)i[n]-=i[o]*u[o];for(n=h-1;n>=0;--n){for(u=a[n],o=n+1;h>o;++o)i[n]-=i[o]*u[o];i[n]/=u[n]}return i}var c=Math.abs;solve=function(r,t,n){return u(f(r,n),t)}}();
{
"name": "anonymous",
"version": "0.0.1",
"private": true,
"dependencies": {
"uglify-js": "2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment