From a655234cc394e0db71799d5d30c9ab9bc775cf77 Mon Sep 17 00:00:00 2001 From: Tim Schaub Date: Fri, 24 Jun 2016 10:03:13 -0600 Subject: [PATCH] Convenience function for common composite transform --- src/ol/transform.js | 26 ++++++++++++++++++++++++++ test/spec/ol/transform.test.js | 23 +++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/src/ol/transform.js b/src/ol/transform.js index cdd9e13377..b028d13158 100644 --- a/src/ol/transform.js +++ b/src/ol/transform.js @@ -166,6 +166,32 @@ ol.transform.translate = function(transform, dx, dy) { }; +/** + * Creates a composite transform given an initial translation, scale, rotation, and + * final translation (in that order only, not commutative). + * @param {!ol.Transform} transform The transform (will be modified in place). + * @param {number} dx1 Initial translation x. + * @param {number} dy1 Initial translation y. + * @param {number} sx Scale factor x. + * @param {number} sy Scale factor y. + * @param {number} angle Rotation (in counter-clockwise radians). + * @param {number} dx2 Final translation x. + * @param {number} dy2 Final translation y. + * @return {!ol.Transform} The composite transform. + */ +ol.transform.compose = function(transform, dx1, dy1, sx, sy, angle, dx2, dy2) { + var sin = Math.sin(angle); + var cos = Math.cos(angle); + transform[0] = sx * cos; + transform[1] = sy * sin; + transform[2] = -sx * sin; + transform[3] = sy * cos; + transform[4] = dx2 * sx * cos - dy2 * sx * sin + dx1; + transform[5] = dx2 * sy * sin + dy2 * sy * cos + dy1; + return transform; +}; + + /** * Invert the given transform. * @param {!ol.Transform} transform Transform. diff --git a/test/spec/ol/transform.test.js b/test/spec/ol/transform.test.js index 0a9906b764..b838a91ae9 100644 --- a/test/spec/ol/transform.test.js +++ b/test/spec/ol/transform.test.js @@ -72,6 +72,29 @@ describe('ol.transform', function() { }); }); + describe('ol.transform.compose()', function() { + it('composes a translate, scale, rotate, translate transform', function() { + var dx1 = 3; + var dy1 = 4; + var sx = 1.5; + var sy = -1.5; + var angle = Math.PI / 3; + var dx2 = -dx1 / 2; + var dy2 = -dy1 / 2; + + var expected = ol.transform.create(); + ol.transform.translate(expected, dx1, dy1); + ol.transform.scale(expected, sx, sy); + ol.transform.rotate(expected, angle); + ol.transform.translate(expected, dx2, dy2); + + var composed = ol.transform.create(); + var composedReturn = ol.transform.compose(composed, dx1, dy1, sx, sy, angle, dx2, dy2); + expect(composed).to.equal(composedReturn); + expect(composed).to.eql(expected); + }); + }); + describe('ol.transform.invert()', function() { it('inverts a transform', function() { var transform = [1, 0, 1, 0, 1, 0];