{"id":13472584,"url":"https://github.com/bijection/g9","last_synced_at":"2025-05-15T06:02:22.868Z","repository":{"id":50713371,"uuid":"57250889","full_name":"bijection/g9","owner":"bijection","description":"Automatically Interactive Graphics 🖼✨💯","archived":false,"fork":false,"pushed_at":"2023-09-10T05:25:10.000Z","size":923,"stargazers_count":1961,"open_issues_count":2,"forks_count":49,"subscribers_count":35,"default_branch":"master","last_synced_at":"2025-04-07T02:05:22.533Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"http://omrelli.ug/g9/gallery","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bijection.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2016-04-27T21:42:51.000Z","updated_at":"2025-03-29T12:46:01.000Z","dependencies_parsed_at":"2024-01-06T14:05:10.505Z","dependency_job_id":"f280b6b7-e2d5-41fe-a868-662c565703f2","html_url":"https://github.com/bijection/g9","commit_stats":{"total_commits":126,"total_committers":6,"mean_commits":21.0,"dds":0.06349206349206349,"last_synced_commit":"9cf5b009c7c011e237be086ed71c8b600b409533"},"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bijection%2Fg9","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bijection%2Fg9/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bijection%2Fg9/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bijection%2Fg9/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bijection","download_url":"https://codeload.github.com/bijection/g9/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248843963,"owners_count":21170496,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T16:00:55.947Z","updated_at":"2025-04-14T08:16:01.069Z","avatar_url":"https://github.com/bijection.png","language":"JavaScript","funding_links":[],"categories":["JavaScript","others"],"sub_categories":[],"readme":"# [g9.js](http://omrelli.ug/g9)\n\ng9 is a javascript library for creating **automatically interactive graphics**.\n\nWith g9, interactive visualization is as easy as visualization that isn't. Just write a function which draws shapes based on data, and g9 will automatically figure out how to manipulate that data when you drag the shapes around.\n\n\nFor example, the following code:\n```javascript\ng9({\n    x: 0,\n    y: 0\n}, function(data, ctx){\n    ctx.point(data.x, data.y)\n    ctx.point(data.y, data.x)\n})\n.insertInto('#container')\n```\n\ndraws two dots at (x,y) and (y,x). With no additional effort, it's interactive - dragging either of the dots changes the value of x and y, and moves the other dot: \n\n![basic demo](basic.gif)\n\nThis **automatic interactivity** makes it trivial to manipulable complex visualizations like this fractal:\n\n![dragon demo](dragon.gif)\n\nYou can see (and play with!) more examples [on the website](http://omrelli.ug/g9/gallery), or [head to the docs](#docs) for a full treatment of the API.\n\n\n# Installation\nYou can use g9 with npm (if your're using webpack or browserify) or with a script tag:\n\n\n\n\n## npm\n\n```\nnpm install g9\n```\n\n```javascript\nvar g9 = require('g9')\n// or \nimport g9 from 'g9'\n```\n\n\n\n## `\u003cscript/\u003e`\n\nFirst download a copy of g9 [here](https://raw.githubusercontent.com/bijection/g9/master/dist/g9.js), then\n\n```html\n\u003cscript src='path/to/g9.js'\u003e\u003c/script\u003e\n \n\u003cscript\u003e\n    // g9 is now defined \n\u003c/script\u003e\n```\n\nYou can also hotlink a copy of g9 from a CDN:\n```html\n\u003cscript src='https://cdnjs.cloudflare.com/ajax/libs/g9/1.0.16/g9.js'\u003e\u003c/script\u003e\n \n\u003cscript\u003e\n\t// g9 is now defined \n\u003c/script\u003e\n```\n\n\n# Docs\n\n\n* [g9(initialData, render[, onRender]): g9Canvas](#g9initialdata-render-onrender-g9canvas)\n  + [initialData](#initialdata)\n  + [render(data, ctx: g9Context)](#renderdata-ctx-g9context)\n  + [onRender(data, renderedObjects)](#onrenderdata-renderedobjects)\n* [g9Canvas](#g9canvas)\n  + [g9Canvas.insertInto(selectorOrDOMNode)](#g9canvasinsertintoselectorordomnode)\n  + [g9Canvas.align(xAlign, yAlign)](#g9canvasalignxalign-yalign)\n  + [g9Canvas.node](#g9canvasnode)\n  + [g9Canvas.setData(data)](#g9canvassetdatadata)\n  + [g9Canvas.getData()](#g9canvasgetdata)\n  + [g9Canvas.isManipulating](#g9canvasismanipulating)\n  + [g9Canvas.resize()](#g9canvasresize)\n  + [g9Canvas.desire(id, ...desires)](#g9canvasdesireid-desires)\n* [g9Context](#g9context)\n  + [g9Context.[shape]](#g9contextshape)\n    - [The Affects Argument](#the-affects-argument)\n    - [g9Context.point(cx, cy[, affects])](#g9contextpointcx-cy-affects)\n    - [g9Context.circle(cx, cy, r[, affects])](#g9contextcirclecx-cy-r-affects)\n    - [g9Context.line(x1, y1, x2, y2[, affects])](#g9contextlinex1-y1-x2-y2-affects)\n    - [g9Context.rect(x, y, width, height[, affects])](#g9contextrectx-y-width-height-affects)\n    - [g9Context.text(text, x, y[, affects])](#g9contexttexttext-x-y-affects)\n    - [g9Context.image(href, x, y, width, height[, affects])](#g9contextimagehref-x-y-width-height-affects)\n  + [g9Context.width](#g9contextwidth)\n  + [g9Context.height](#g9contextheight)\n  + [g9Context.pure(pureFn)](#g9contextpurepurefn)\n* [Adding new shapes to g9Context](#adding-new-shapes-to-g9context)\n  + [g9.shapes.myNewShape = shape](#g9shapesmynewshape--shape)\n\n## g9([initialData](#initialdata), [render](#render)[, [onRender](#onrender)]): [g9Canvas](#g9canvas)\nThis is the main g9 function, which returns a [g9Canvas](#g9Canvas) which you can mount in your page with the `g9Canvas.insertInto(selectorOrDOMNode)` method. For example: \n\n```javascript\ng9({foo: 10}, function(data, ctx){\n\tctx.point(data.foo, 17)\n})\n.insertInto('#container')\n```\n\nThe g9Canvas API is covered [here](#g9Canvas).\n\n`g9()` takes the following arguments:\n\n\n### initialData\n`initialData` is a flat object with numeric values, which will be used in the first call to `render`. For example:\n\n```javascript\nvar initialData = {\n    foo: 10\n}\n```\n\n\n\n### render(data, ctx: [g9Context](#g9context))\n\n`render(data, ctx)` is a function that receives a `data` object with the same keys as `initialData`, but possibly different values, and a [g9Context](#g9context) `ctx`. The g9Context API is covered [here](#g9context).\n\n`render` is responsible for calling methods on `ctx` to produce a drawing.\nFor example:\n\n```javascript\nfunction render(data, ctx){\n    ctx.point(data.foo, 17)\n}\n```\ncreates a point at x-coordinate `data.foo` and y-coordinate 17.\n\n\nWhen someone interacts with the graphics, for example by trying to drag an element to a new position, g9 optimizes over the space of possible values for `data` to find a set of values that comes closest to creating the change. In the preceeding example, if `data.foo` is initially 10 and you tried to drag the point to the left, g9 might come up with\n\n```javascript\n{\n    foo: 8\n}\n```\nAfter optimization, g9 rerenders the entire scene with the new data, so that everything is consistent.\n\n\n\n### onRender(data, renderedObjects)\n`onRender(data, renderedObjects)` is an optional argument which, if included, is called after each re-render with the data that determined the render, and the set of rendered objects. Typical uses for `onRender` include debugging compositions and updating other parts of your page.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n## g9Canvas\nA `g9Canvas` is the object returned by a call to g9(initialData, render, onRender)\n\n### g9Canvas.insertInto(selectorOrDOMNode)\nMounts the graphics' svg node as a child of `selectorOrDOMNode`, which can be either a selector or a DOM node, and returns the graphics object to enable chaining.\n\nFor example:\n\n```javascript\ng9({foo: 10}, function(data, ctx){\n\tctx.point(data.foo, 17)\n})\n.insertInto('#container')\n```\n\n\u003e Note: You can change the size of the mounted svg node with javascript, e.g `g9Canvas.node.style.height = '500px'; g9Canvas.resize()`, or css, e.g. `#g9NodesParentElement \u003e svg {width: 100%; height: 300px}`.\n\n\n### g9Canvas.align(xAlign, yAlign)\nSets the position of the origin in relation to which graphics are drawn. `xAlign` and `yAlign` are both strings that default to 'center'. Returns the graphics object to enable chaining.\n\n* `xAlign` can be either 'left', 'center', or 'right'.\n* `yAlign` can be either 'top', 'center', or 'bottom'.\n\nFor example:\n\n```javascript\ng9({foo: 10}, function(data, ctx){\n\tctx.point(data.foo, 17)\n})\n.align('bottom', 'left')\n.insertInto('#container')\n```\n\n\n\n### g9Canvas.node\nA read-only reference to the `svg` DOM node that holds the g9 graphics.\n\n\n\n### g9Canvas.setData(data)\nSets the data currently being visualized by a g9 instance to `data`. This is useful for animations. For example: \n\n```javascript\nvar graphics = g9({foo: 10}, function(data, ctx){\n\tctx.point(data.foo, 17)\n})\n.insertInto('#container')\n\nvar theta = 0\n\nsetInterval(function(){\n\tgraphics.setData( {foo: Math.cos( theta += 0.01 )} )\n}, 30)\n```\n\n\n### g9Canvas.getData()\nGet the data currently being visualized by a g9Canvas. For example:\n\n```javascript\nvar graphics = g9({foo: 10}, function(data, ctx){\n    ctx.point(data.foo, 17)\n})\n.insertInto('#container')\n\nalert(JSON.stringify(graphics.getData()))\n```\n\n\n###g9Canvas.isManipulating\nA boolean property that's true when a user is manupulating a shape on the g9 canvas.\n\n\n### g9Canvas.resize()\nInvalidates the g9 display. Usually a noop, but should be called after programmatically resizing the g9 DOM node or its container.\n\n\n### g9Canvas.desire(id, ...desires)\nInternal method, genreally safe to ignore, but useful for complex animation. For now, the best way to use this is to read the source.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n## g9Context\nA new, immutable g9Context object `ctx` is passed as the second argument to `render` each time `render` is called. It has a variety of drawing methods and some read-only properties that the render function uses to create a drawing.\n\n\n### g9Context.[shape]\nWhen calling a drawing method, you can include any number of ordered arguments, optionally followed by an object that specifies further arguments by name, and / or includes svg properties. For example, all of the following are equivalent: \n\n```javascript\nctx.point(30, 50, ['a'])\n\nctx.point(30, 50, {affects: ['a']})\n\nctx.point(30, {\n\ty: 50,\n\taffects: ['a']\n})\n\nctx.point({\n\tx: 30,\n\ty: 50,\n\taffects: ['a']\n})\n```\n\n#### The Affects Argument\n\nAll g9 shapes take an optional argument `affects`, a list of key names. When you drag a shape with an `affects` list, g9 will only change the values of the keys in the `affects` list.\n\nFor example, dragging the following point will only change the value of `data.x`, and thus the point will only move horizontally:\n```javascript\ng9({\n    x: 0,\n    y: 0\n}, function(data, ctx){\n    \n    ctx.point(data.x, data.y, {affects: ['x']})\n    \n})\n```\n\n\nCurrently, the built-in shapes are\n\n#### g9Context.point(cx, cy[, affects])\n  \nA point. Useful svg properties are `r` (radius), and `fill`. For example:\n\n```javascript\nctx.point(30, 50, {r: 40, \tfill: 'red'\t})\n```\n\n#### g9Context.circle(cx, cy, r[, affects])\n  \nA circle. As opposed to the point, circles can rotate around your mouse as you drag them. Useful svg properties are `stroke` (a color), and `fill`. For example:\n\n```javascript\nctx.circle(30, 50, 40, { stroke: 'blue' })\n```\n\n\n#### g9Context.line(x1, y1, x2, y2[, affects])\n  \nA line. Useful svg properties are `stroke-width`, `stroke` (stroke color), and `stroke-linecap`. For example:\n\n```javascript\nctx.line(30, 50, 60, 100, {\n\t'stroke-width': 10,\n\t'stroke': 'red',\n\t'stroke-linecap': 'round'\n})\n```\n#### g9Context.rect(x, y, width, height[, affects])\n  \nA rectangle. A useful svg property is `fill`. For example:\n\n```javascript\nctx.rect(0, 0, 100, 100, {'fill': '#ff6600'})\n```\n\n\n#### g9Context.text(text, x, y[, affects])\n  \nA text label. Useful svg properties are `font-family`, `font-size`, `fill`, and `text-anchor`. For example:\n\n```javascript\nctx.text('Hello World!', 30, 50, {\n\t'font-family': 'sans-serif',\n\t'font-size': '20px',\n\t'text-anchor': 'middle',\n\t'fill': '#badd09'\n})\n```\n\n#### g9Context.image(href, x, y, width, height[, affects])\n  \nAn image. A useful svg property is `preserveAspectRatio`. For example:\n\n```javascript\nctx.image('http://placehold.it/350x150', 0, 0, 350, 150, {\n\t'preserveAspectRatio': 'xMaxYMax'\n})\n```\n\n### g9Context.width\nRead only. The current width of the svg container, as dertermined by page size and / or css.\n\n### g9Context.height\nRead only. The current height of the svg container, as dertermined by page size and / or css.\n\n### g9Context.pure(pureFn)\n`ctx.pure(pureFn)` is a decorator that speeds up deterministic, stateless (and usually recursive) functions. Internally, `ctx.pure` tells g9 that it doesn't have to execute certain branches when it is optimizing. For recursive funtions, this can make optimization take `O(log(n))` time, instead of `O(n)` time, where `n` is the number of objects drawn by `pureFn`. For example: \n\n```javascript\ng9({\n    deltaAngle:33,\n    attenuation:0.7,\n    startLength:189\n}, function(data, ctx){\n\n    var deltaAngle = data.deltaAngle,\n        attenuation = data.attenuation,\n        startLength = data.startLength\n    \n    var drawTree = function (x1, y1, length, angle, n){\n        var x2 = x1 + length * Math.cos(angle*Math.PI/180);\n        var y2 = y1 + length * Math.sin(angle*Math.PI/180);\n     \n        ctx.point(x2, y2, {affects:['deltaAngle', 'attenuation']})\n        \n        ctx.line(x1,y1,x2,y2)\n\n        if(n \u003e 0) {\n            drawTree(x2, y2, length*attenuation, angle+deltaAngle, n-1);\n            drawTree(x2, y2, length*attenuation, angle-deltaAngle, n-1);\n        }\n\n    }\n    \n    drawTree = ctx.pure(drawTree)\n\n    drawTree(0, ctx.height/2 - 30, startLength, -90, 9)\n\n})\n```\nA live version of this example is on [the examples page](https://omrelli.ug/g9/gallery).\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n## Adding new shapes to g9Context\n\n### g9.shapes.myNewShape = shape\n\n    This is an experimental API and may be subject to change. That said, pull requests with particularly good new shapes are encouraged!\n\ng9 allows you to go beyond basic shapes like circles and rectangles by adding your own shapes, which will then be available as drawing methods on g9Context objects. \n\nYou can add a custom shape in the folowing way: \n```javascript\ng9.shapes.myNewShape = shape\n```\n\nAfter which it will be available as \n```javascript\ng9({\n    x: 0,\n    y: 0\n}, function render(data, ctx){\n    ctx.myNewShape(ctx.x, ctx.y, 1, 3, 5, 'asdf')\n})\n```\n\nA shape is a javascript class with the following properties:\n- **argNames**: an array of the names that should be assigned to arguments passed to the shape\n- **contructor(get_args, minimize_args)**: a constructor method, which usually saves the two functions it recieves.\n    - **get_args()**: A getter that returns a flat set of keys and values that represents that arguments passed to your shape's drawing method on the last render.\n    - **minimize_args(cost(potentialArgs) -\u003e Number[, keys: array])**: changes the values of data with the keys `keys`, or all of the values of data if `keys` is not included, to minimize the number returned by `cost`. `cost` is passed an abject `potentialArgs`, a flat set of keys and values that represent the arguments that *would be passed* to your shape's drawing method for some potential new values of your drawing's `data`. After minimization your graphics are rerendered.\n- **mount(container)**: a method which recieves the relevant g9Canvas.node svg element as its only argument. Typically you use this method to add an svg object to container, attach event handlers, etc.\n- **unmount()**: a method responsible for cleaning up any mutation to the DOM or event listeners created in mount(). \n- **update()**: a method that is called every time the graphics are rendered. `update` usually call `get_args` and uses the result to change the DOM.\n\n\nFor example, you might define an `equilateral_triangle` shape like this:\n```javascript\nfunction equilateral_triangle(get_args, minimize_args){\n    this.minimize_args = minimize_args\n    this.get_args = get_args\n}\n\nequilateral_triangle.argNames = ['x', 'y', 'size', 'affects']\n\nequilateral_triangle.prototype.mount = function(container){\n    this.container = container\n    this.el = document.createElementNS(\"http://www.w3.org/2000/svg\", \"polygon\")\n    this.container.appendChild(this.el)\n    this.el.setAttributeNS(null, 'fill', 'red')\n\n    var startex, startey;\n\n    var self = this\n\n    function onmove(e){\n        var dx = e.clientX - startex\n        var dy = e.clientY - startey\n\n        var current_affects = self.get_args().affects\n\n        self.minimize_args(function(args){\n            var ddx = (args.x - start_args.x) - dx\n            var ddy = (args.y - start_args.y) - dy\n\n            return ddx*ddx + ddy*ddy\n        }, current_affects)\n    }\n\n    function onstart(e){\n\n        var start_args = self.get_args()\n\n        e.preventDefault()\n\n        startex = e.clientX\n        startey = e.clientY\n\n        var onend = function(e){\n            document.removeEventListener('mousemove', onmove)\n            document.removeEventListener('mouseup', onend)\n        }\n\n        document.addEventListener('mousemove', onmove)\n        document.addEventListener('mouseup', onend)\n    }\n\n    this.el.addEventListener('mousedown', onstart)\n}\n\nequilateral_triangle.prototype.unmount = function() {\n    this.container.removeChild(this.el)\n}\n\nequilateral_triangle.prototype.update = function() {\n    g9.utils.setAttributes(this.el, this.get_args())\n\n    var points = [x+Math.cos(0)*size, y+Math.sin(0)*size,\n                  x+Math.cos(2*Math.PI/3)*size, y+Math.sin(2*Math.PI/3)*size,\n                  x+Math.cos(2*Math.PI*2/3)*size, y+Math.sin(2*Math.PI*2/3)*size]\n    this.el.setAttributeNS(null, 'points', points.join(' '))\n}\n\ng9.shapes.equilateral_triangle = equilateral_triangle\n```\n\nAfter which you can use it like so: \n```javascript\ng9({\n    x: 0,\n    y: 0\n}, function render(data, ctx){\n    ctx.equilateral_triangle(ctx.x, ctx.y, 50)\n})\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbijection%2Fg9","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbijection%2Fg9","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbijection%2Fg9/lists"}