1
0
Fork 0
Browse Source

feat: add draw module

Signed-off-by: André Jaenisch <andre.jaenisch@posteo.de>
combat-scorched-earth-from-outer-space
André Jaenisch 1 year ago
parent
commit
8be4ce0c69
Signed by: ryuno-ki
GPG Key ID: 5A668E771F1ED854
  1. 38
      src/js/draw.js
  2. 42
      test/js/draw.test.js
  3. 9
      types/draw.d.ts

38
src/js/draw.js

@ -0,0 +1,38 @@
/** @typedef {import('./shape').Shape} Shape */
/**
* Draws a shape onto the canvas.
*
* @param {CanvasRenderingContext2D} context
* @param {Shape} shape
*/
export function drawShape (context, shape) {
context.save()
prepareCanvas(context, shape)
draw(context, shape)
context.restore()
}
/**
* Transforms the coordination system for easier execution.
*
* @param {CanvasRenderingContext2D} context
* @param {Shape} shape
*/
function prepareCanvas (context, shape) {
const { C, G } = shape
const { x, y } = C
context.translate(x, y)
context.rotate(G)
}
/**
* Draws a shape.
*
* @param {CanvasRenderingContext2D} context
* @param {Shape} shape
*/
function draw (context, shape) {
const { W, H } = shape
context.strokeRect(-W / 2, -H / 2, W, H)
}

42
test/js/draw.test.js

@ -0,0 +1,42 @@
import { expect } from 'chai'
import jsdom from 'jsdom'
import { drawShape } from '../../src/js/draw.js'
import { RigidShape } from '../../src/js/shape.js'
import { Vec2 } from '../../src/js/vector.js'
// Requires npm canvas package here to be installed
const { JSDOM } = jsdom
const { window } = new JSDOM('')
const { document } = window
describe('drawShape', function () {
it('should draw a shape onto a canvas', function () {
// Arrange
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
const center = Vec2(500, 200)
const friction = 20
const restitution = 0
const mass = 400
const bounds = 1
const width = 5
const height = 5
const shape = RigidShape({
center,
mass,
friction,
restitution,
bounds,
width,
height
})
// Act
drawShape(context, shape)
// Assert
// TODO: Assert pixel on canvas
})
})

9
types/draw.d.ts vendored

@ -0,0 +1,9 @@
/** @typedef {import('./shape').Shape} Shape */
/**
* Draws a shape onto the canvas.
*
* @param {CanvasRenderingContext2D} context
* @param {Shape} shape
*/
export function drawShape(context: CanvasRenderingContext2D, shape: Shape): void;
export type Shape = import('./shape').Shape;
Loading…
Cancel
Save