Skip to content

Commit

Permalink
adds cx and cy for scale function (#62)
Browse files Browse the repository at this point in the history
Co-authored-by: Rodrigo de Almeida Pereira <rodrigo.pereira@brave.ag>
  • Loading branch information
rodrigoapereira and Rodrigo de Almeida Pereira authored Apr 13, 2020
1 parent 2eda217 commit 1e27575
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
17 changes: 15 additions & 2 deletions src/scale.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,32 @@
import { isUndefined } from './utils'
import { translate } from './translate'
import { transform } from './transform'

/**
* Calculate a scaling matrix
* @param sx {number} Scaling on axis x
* @param [sy = sx] {number} Scaling on axis y (default sx)
* @returns {Matrix} Affine Matrix
*/
export function scale (sx, sy = undefined) {
export function scale (sx, sy = undefined, cx = undefined, cy = undefined) {
if (isUndefined(sy)) sy = sx
return {

const scaleMatrix = {
a: sx,
c: 0,
e: 0,
b: 0,
d: sy,
f: 0
}

if (isUndefined(cx) || isUndefined(cy)) {
return scaleMatrix
}

return transform([
translate(cx, cy),
scaleMatrix,
translate(-cx, -cy)
])
}
32 changes: 31 additions & 1 deletion test/scale.spec.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* global describe, it, expect */
import { applyToPoint } from '../src/applyToPoint'
import { applyToPoint, applyToPoints } from '../src/applyToPoint'
import { scale } from '../src/scale'

describe('scale', () => {
Expand Down Expand Up @@ -32,4 +32,34 @@ describe('scale', () => {
expect(applyToPoint(m, { x: 50, y: 80 })).toEqual({ x: 1000, y: 1600 })
expect(applyToPoint(scale(20, undefined), { x: 50, y: 80 })).toEqual({ x: 1000, y: 1600 })
})

it('should scale points about specified origin', () => {
/*
<rect x="-50" y="-50" width="200" height="200" fill="green" />
<rect x="0" y="0" width="100" height="100" fill="black" />
<circle cx="50" cy="50" r="10" fill="red" />
*/
const m = scale(2, 2, 50, 50)
expect(m).toEqual({
a: 2,
c: 0,
e: -50,
b: 0,
d: 2,
f: -50
})

const points = [
{ x: 0, y: 0 },
{ x: 100, y: 0 },
{ x: 0, y: 100 },
{ x: 100, y: 100 }
]
expect(applyToPoints(m, points)).toEqual([
{ x: -50, y: -50 },
{ x: 150, y: -50 },
{ x: -50, y: 150 },
{ x: 150, y: 150 }
])
})
})

0 comments on commit 1e27575

Please sign in to comment.