Closed Mark-Theodore-Fox closed 4 years ago
I saw your question on stackoverflow but forgot about it.
Your issue is not realated to svg.js. You just havent understood javascript correctly yet ;).
Here is your code with comments:
// A function is declared. Every time the function is called, its body is executed
// A function can return a value (e.g. return 0). This is not the case here.
// The function gets passed a parameter "Name" which is only accessible in the function
function CreateTriangle(Name) {
// define local variable "Name" which OVERWRITES the already defined variable Name (the parameter of the function)
// svg.js draws a polygon and saves its result in the local variable
// since there is nothing else to do, the function finishes and returns nothing
var Name = draw.polygon("50 15, 100 100, 0 100").fill("#fff").stroke({ width: 0 })
}
// The function is called with a parameter. However, since the parameter is overwritten anyway, its useless
CreateTriangle("MyFirstTriangle");
// You try to access a variable with the name "MyFirstTriangle" but never defined any variable with that name.
// Hence the error "ReferenceError: MyFirstTriangle is not defined"
MyFirstTriangle.animate(4000, '<>', 500 * i).rotate(30 * i);
And here is what you probably wanted:
function CreateTriangle() {
return draw.polygon("50 15, 100 100, 0 100").fill("#fff").stroke({ width: 0 })
}
var MyFirstTriangle = CreateTriangle();
MyFirstTriangle.animate(4000, '<>', 500 * i).rotate(30 * i);
BTW: The variable "i" you are using in your code is also not defined. I guess its a variable from a loop which you didnt show?
Hi Ulrich, This is fantastic, I cannot thank you enough for this response. All the best, Mark
No problem :).
Btw: javascript as any programming language is mostly programmed in a certain style. Its called camelCase. It helps when you also use that style because it becomes easier for other programmers do understand your code :)
I've written a JavaScript function that creates a triangle (MyFirstTriangle). The triangle displays perfectly as one would expect. However, when I try to apply an animation to the triangle I get the "ReferenceError: MyFirstTriangle is not defined".
When I create the same triangle directly (as in, not through a function), then the animation works perfectly. Are there some inherent limitations regarding the use of functions with SVG.JS?