You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Svg.js 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import {
  2. adopt,
  3. nodeOrNew,
  4. register,
  5. wrapWithAttrCheck
  6. } from '../utils/adopter.js'
  7. import { svg, xlink, xmlns } from '../modules/core/namespaces.js'
  8. import { registerMethods } from '../utils/methods.js'
  9. import Container from './Container.js'
  10. import Defs from './Defs.js'
  11. import { globals } from '../utils/window.js'
  12. export default class Svg extends Container {
  13. constructor(node, attrs = node) {
  14. super(nodeOrNew('svg', node), attrs)
  15. this.namespace()
  16. }
  17. // Creates and returns defs element
  18. defs() {
  19. if (!this.isRoot()) return this.root().defs()
  20. return adopt(this.node.querySelector('defs')) || this.put(new Defs())
  21. }
  22. isRoot() {
  23. return (
  24. !this.node.parentNode ||
  25. (!(this.node.parentNode instanceof globals.window.SVGElement) &&
  26. this.node.parentNode.nodeName !== '#document-fragment')
  27. )
  28. }
  29. // Add namespaces
  30. namespace() {
  31. if (!this.isRoot()) return this.root().namespace()
  32. return this.attr({ xmlns: svg, version: '1.1' }).attr(
  33. 'xmlns:xlink',
  34. xlink,
  35. xmlns
  36. )
  37. }
  38. removeNamespace() {
  39. return this.attr({ xmlns: null, version: null })
  40. .attr('xmlns:xlink', null, xmlns)
  41. .attr('xmlns:svgjs', null, xmlns)
  42. }
  43. // Check if this is a root svg
  44. // If not, call root() from this element
  45. root() {
  46. if (this.isRoot()) return this
  47. return super.root()
  48. }
  49. }
  50. registerMethods({
  51. Container: {
  52. // Create nested svg document
  53. nested: wrapWithAttrCheck(function () {
  54. return this.put(new Svg())
  55. })
  56. }
  57. })
  58. register(Svg, 'Svg', true)