Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active November 27, 2023 17:54
  • Star 14 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mbostock/10571478 to your computer and use it in GitHub Desktop.
Perspective Transformation
license: gpl-3.0

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

The image is transformed using a matrix3d CSS transform. The transformation matrix 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 apply a perspective transform manually for simple 2D shapes, such as lines and circles.

<!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: #000;
stroke-opacity: .5;
stroke-width: 1px;
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 transform = ["", "-webkit-", "-moz-", "-ms-", "-o-"].reduce(function(p, v) { return v + "transform" in document.body.style ? v : p; }) + "transform";
var sourcePoints = [[0, 0], [width, 0], [width, height], [0, height]],
targetPoints = [[0, 0], [width, 0], [width, height], [0, height]];
d3.select("body").selectAll("svg")
.data(["transform", "flat"])
.enter().append("svg")
.attr("id", function(d) { return d; })
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var svgTransform = d3.select("#transform")
.style(transform + "-origin", margin.left + "px " + margin.top + "px 0");
var svgFlat = d3.select("#flat");
svgTransform.select("g").append("image")
.attr("xlink:href", "sailboat.png")
.attr("width", width)
.attr("height", height);
svgTransform.select("g").selectAll(".line--x")
.data(d3.range(0, width + 1, 40))
.enter().append("line")
.attr("class", "line line--x")
.attr("x1", function(d) { return d; })
.attr("x2", function(d) { return d; })
.attr("y1", 0)
.attr("y2", height);
svgTransform.select("g").selectAll(".line--y")
.data(d3.range(0, height + 1, 40))
.enter().append("line")
.attr("class", "line line--y")
.attr("x1", 0)
.attr("x2", width)
.attr("y1", function(d) { return d; })
.attr("y2", function(d) { return d; });
var handle = svgFlat.select("g").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);
});
svgTransform.style(transform, "matrix3d(" + matrix + ")");
}
</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"
}
}
@villanus
Copy link

AMAZING!!!!

What would be the necessary changes to make the whole Sailboat svg dragabble?
(Not just by corners, but also from center just to reposition)

Also, is it possible to layer another transparent PNG on top of the sailboat (for example to mimic wall shadows?)
Then you can have:

  • a jpeg photo of the walls (back)
  • b photo or SVG file (middle) "Sailboat"
  • c front layer which would be a transparent PNG of the walls shadows. This would really finish off the effect.
    This c layer would have to be designed in photoshop similar to how tshirt mock up generators create wrinkles.

Thanks!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment