Skip to content

SVG and javascript#2

jackdarker edited this page Sep 27, 2021 · 2 revisions

Be aware that svgo.js might modify and remove parts from your svg:

  • attributes might get removed if unknown except data-* and aria-*
  • if a styleclass is assigned only to one element, the class might be removed and the elements style is modified instead ?!

Here are some rules I follow when creating svg in Inkscape:

  • if you specify a different fill or stroke (per style or class) in <use>-elements and the template elements has those values set, the new fill or stroke will NOT be overridden. Therefor set them to undefined in template
  • place the templates on a template layer and outside the page-area
  • you might use the Extension->stylesheet->Merge style into css feature to create style-classes in the svg. Then you can assign the class to the elements (only via XML-view). Check also that no unecessary style are shown in the XML.
  • f.e. I have a styleclasses to hide elements, highlighted elements, normal presentation
  • add at least on template-clone for every styleclass. If the class is not used, it might get removed automatically
  • in the object-properties-panel you can unfold the interactivity-dropout where you can add javascript for different events (onmouseover:style.opacity = 0.5;). If you add those to the template, it will affect all users of the template and the event will be triggered by every user!
  • I create data-* attributes (via XML-view) to assign data to the elements to be used by javascript (see below)

In javascript you can now do this:
var node = SVG(window.gm.images[MapName]());
node.find("#AM_Lv2_A1")[0].addClass('roomNotFound'); //Find one element with this id and assign a style-class
var list=node.find('[data-reveal]'); //Find elements that have a certain attribute (see here for selektors)[https://developer.mozilla.org/de/docs/Web/CSS/CSS_Selectors]
node.addTo(draw);

F.e. I have a map of a dungeon and depending on the players exploration I would like to reveal it only partwise.
So I set different bitcoded attributes like 'data-reveal="80"' to mark whitch elemnts should be revealed together. Before the map is drawn I just need to filter all nodes with node.find('[data-reveal]'), fetch the attributes with parseInt(elem.attr('[data-reveal]')) and compare this code with a bitmask the player already has unlocked. if code|bitmask===0 the I add the hide-class (this sets style="display:none")

Clone this wiki locally