SVG.Image

by tinyhustlee

HTML

<div id="drawing"></div>

JavaScript

import {
  Array as SVGArray,
  Container,
  Defs,
  Element,
  extend,
  find,
  namespaces as ns,
  nodeOrNew,
  utils,
  wrapWithAttrCheck
} from '@svgdotjs/svg.js'

export default class Filter extends Element {
  constructor (node) {
    super(nodeOrNew('filter', node), node)

    this.$source = 'SourceGraphic'
    this.$sourceAlpha = 'SourceAlpha'
    this.$background = 'BackgroundImage'
    this.$backgroundAlpha = 'BackgroundAlpha'
    this.$fill = 'FillPaint'
    this.$stroke = 'StrokePaint'
    this.$autoSetIn = true
  }

  put (element, i) {
    element = super.put(element, i)

    if (!element.attr('in') && this.$autoSetIn) {
      element.attr('in', this.$source)
    }
    if (!element.attr('result')) {
      element.attr('result', element.id())
    }

    return element
  }

  // Unmask all masked elements and remove itself
  remove () {
    // unmask all targets
    this.targets().each('unfilter')

    // remove mask from parent
    return super.remove()
  }

  targets () {
    return find('svg [filter*="' + this.id() + '"]')
  }

  toString () {
    return 'url(#' + this.id() + ')'
  }
}

// Create Effect class
class Effect extends Element {
  constructor (node) {
    super(node, node)
    this.result(this.id())
  }
  in (effect) {
    // Act as getter
    if (effect == null) {
      const _in = this.attr('in')
      const ref = this.parent() && this.parent().find(`[result="${_in}"]`)[0]
      return ref || _in
    }

    // Avr as setter
    return this.attr('in', effect)
  }
  // Named result
  result (result) {
    return this.attr('result', result)
  }
  // Stringification
  toString () {
    return this.result()
  }
}

// This function takes an array with attr keys and sets for every key the
// attribute to the value of one paramater
// getAttrSetter(['a', 'b']) becomes this.attr({a: param1, b: param2})
const getAttrSetter = (params) => {
  return function (...args) {
    for (let i = params.length; i--;) {
      if (args[i] != null) {
       ...