SVG.hx 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package hide.comp;
  2. import hide.Element;
  3. class SVG extends Component {
  4. var document : js.html.HTMLDocument = null;
  5. public function new(?parent:Element,?el) {
  6. document = parent == null ? js.Browser.document : parent[0].ownerDocument;
  7. if( el == null ) el = new Element(document.createElementNS('http://www.w3.org/2000/svg', 'svg'));
  8. super(parent,el);
  9. element.attr("width", "100%");
  10. element.attr("height", "100%");
  11. }
  12. public function clear() {
  13. element.empty();
  14. }
  15. public function add(el: Element) {
  16. element.append(el);
  17. }
  18. public function make(?parent: Element, name: String, ?attr: Dynamic, ?style: Dynamic) {
  19. var e = document.createElementNS('http://www.w3.org/2000/svg', name);
  20. var el = new Element(e);
  21. if(attr != null)
  22. el.attr(attr);
  23. if(style != null)
  24. el.css(style);
  25. if(parent != null)
  26. parent.append(el);
  27. return el;
  28. }
  29. public function circle(?parent: Element, x:Float, y:Float, radius:Float, ?style:Dynamic) {
  30. return make(parent, "circle", {cx:x, cy:y, r:radius}, style);
  31. }
  32. public function rect(?parent: Element, x:Float, y:Float, width:Float, height:Float, ?style:Dynamic) {
  33. return make(parent, "rect", {x:x, y:y, width:width, height:height}, style);
  34. }
  35. public function line(?parent: Element, x1:Float, y1:Float, x2:Float, y2:Float, ?style:Dynamic) {
  36. return make(parent, "line", {x1:x1, y1:y1, x2:x2, y2:y2}, style);
  37. }
  38. public function curve(?parent: Element, x1:Float, y1:Float, x2:Float, y2:Float, xTurn:Float, yTurn:Float, ?style:Dynamic) {
  39. return make(parent, "path", {d : 'M ${x1} ${y1} Q ${xTurn} ${yTurn}, ${x1 + (x2-x1)/2} ${y1 + (y2-y1)/2}, T ${x2} ${y2}'}, style);
  40. }
  41. public function foreignObject(?parent: Element, x:Float, y:Float, width:Float, height:Float, ?style:Dynamic) {
  42. return make(parent, "foreignObject", {x:x, y:y, width:width, height:height}, style);
  43. }
  44. public function polygon(?parent: Element, points: Array<h2d.col.Point>, ?style:Dynamic) {
  45. // TODO: Use https://www.w3schools.com/graphics/svg_polygon.asp
  46. var lines = ['M${points[0].x},${points[0].y} '];
  47. for(i in 1...points.length) {
  48. lines.push('L${points[i].x},${points[i].y} ');
  49. }
  50. return make(parent, "path", {d: lines.join("")}, style);
  51. }
  52. public function group(?parent: Element, ?className: String, ?attr: Dynamic) {
  53. var g = make(parent, "g", attr);
  54. if(className != null)
  55. g.addClass(className);
  56. return g;
  57. }
  58. public function text(?parent: Element, x: Float, y: Float, text: String, ?style: Dynamic) {
  59. var e = make(parent, "text", {x:x, y:y}, style);
  60. e.text(text);
  61. return e;
  62. }
  63. }