Wikipedia:Reference desk/Archives/Computing/2022 November 16

= November 16 =

JavaScript calculations in SVG
Hi, I am creating an SVG image which involves a number of shapes, that taken as a group, need to be rotated about a certain point. I can do it like this:  In the   attribute,   is the angle of rotation in degrees, and   is the centre of rotation (see SVG 1.1 spec for the 'transform' attribute). The angle that I wish to rotate by is supplied to me as degrees, minutes and seconds. Calculating the angle of rotation as a pure degrees is easy (d + m/60 + s/3600), and this is fine for one-off uses, but I need to perform the calculation many times for different sets of source data. What I want to do is input the three components individually without having to perform the calculation on the outside. I thought of using JavaScript, and SVG allows this - the code  can be inserted into the page source before the  tag, and I now have my function. What I don't know how to do is to actually call the function -  isn't being recognised. JavaScript references all seem to assume that you want to hook some event e.g. with  or write directly into the page text, but I want to insert the calculated value into a tag's attribute value. The articles JavaScript and JavaScript syntax don't help at all. Does anybody know how to achieve this? -- Red rose64 &#x1f339; (talk) 12:21, 16 November 2022 (UTC)


 * JavaScript interacts with a webpage using the Document Object Model (DOM). This is most commonly for HTML elements, but works well (on modern browsers) for SVG files too; elements of the SVG can be addressed by their, and from that the JavaScript can manipulate their properties. This example shows a JavaScript program manipulating the elements of an SVG to create a ticking clock.  The problem remains is how the JavaScript gets the parameters (the rotation degrees) that it uses. Depending on your use case, it might work just to bake that into the JavaScript (perhaps a list of settings to use), get it from the user interactively using an HTML form, or the JavaScript might request the data from a file or process on the server whence it came, e.g. using an XMLHttpRequest to fetch data encoded in JSON format. -- Finlay McWalter··–·Talk 17:32, 16 November 2022 (UTC)