Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adds cx and cy for scale function #62

Merged
merged 1 commit into from
Apr 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 }
])
})
})