Reputation: 33
I'm using HTML5 Canvas in Adobe Animate. I'm trying to write a function that allows me to drop a text message anywhere on the stage.
Please see my code below.
function newtext(TextToDisplay, xposition, yposition, textcolor, textfont)
{var textvar = new createjs.Text();
textvar.x = xposition;
textvar.y = yposition;
textvar.color = textcolor;
textvar.font = textfont;
textvar.text = TextToDisplay;
this.addChild(textvar);}
newtext("Hi there!",200,200,"#ff7799","50px Arial");
I'm not sure what I'm doing wrong. I can't find a viewer that includes EaselJS packages, so showing error messages here will not make much sense. Additionally, "Compiler Errors" is greyed out as a window option in Adobe Animate HTML5 Canvas, so I can't see the errors there when I test my code. If anyone can suggest a suitable viewer, that would be helpful as well.
I just wanted to add what I used to pull the code from, and this code works outside of the function.
var fl_TF = new createjs.Text();
var fl_TextToDisplay = "Lorem ipsum dolor sit amet.";
fl_TF.x = 200;
fl_TF.y = 100;
fl_TF.color = "#ff7700";
fl_TF.font = "20px Arial";
fl_TF.text = fl_TextToDisplay;
this.addChild(fl_TF);
A commenter suggested the presence of "this" in the function might be the issue. It may be part of the problem, as well as something else being wrong.
Upvotes: 3
Views: 772
Reputation: 11294
From your description, it looks like the addChild
is failing because the newText()
method is called without a scope.
You should be receiving console logs showing that you "addChild is not a function".
You can not simply remove this
. You have two simple options though:
1) The hacky often used to get around this issue is the "this/that" pattern:
var that = this;
function newText(your args) {
// your other code
that.addChild(fl_TF); // <-- Uses "that" which references the original scope
}
2) You can also just call the method in the correct scope:
newText.call(this, "Hi There", 200, 200, "#ff0000", "50px Arial");
I hope that helps!
Upvotes: 1