const emptyInit = function() {}

const defaultOptions = {
    autoresize: false,
    keepaspectratio: false,
    init: emptyInit
}

const addResizeFunction = fn => {
    fn()
    window.addEventListener('resize', () => fn())
}

const canvas2d = (canvas, options) => {
    const opts = Object.assign({}, defaultOptions, options)
    const ctx = canvas.getContext('2d')

    if (opts.autoresize) {
        addResizeFunction(() => {
            const rect = canvas.getBoundingClientRect()
            canvas.width = rect.width
            canvas.height = rect.height
        })
    }

    if (opts.keepaspectratio) {
        addResizeFunction(() => {
            const height = window.innerWidth * canvas.height / canvas.width
            canvas.style.height = height + 'px'
        })
    }

    options.init(ctx)

    return ctx
}

export default canvas2d
