I am trying to build a plugin for XD to automate the creation of design elements. I have written a function to build a button using a text element and a rectangle. I need to base the width of the rectangle on the width of the text but have hit a problem, the width property of the text comes up as “undefined”. Is this a bug or am I doing something wrong?
I am creating the rectangle and text with the following function:
function createButton(selection) {
// Create the outline of the button const newButtonOutline = new Rectangle(); newButtonOutline.width = 100; newButtonOutline.height = 50; newButtonOutline.stroke = new Color("#2D3494"); newButtonOutline.strokeWidth = 2; newButtonOutline.cornerRadii = { topLeft: 10, topRight: 10, bottomRight: 10, bottomLeft: 10 }; // Create the text for the button const newButtonLabel = new Text(); newButtonLabel.text = "Submit Button"; newButtonLabel.fontSize = 18; newButtonLabel.fill = new Color("#000000"); // Add the text and outline to the artboard selection.insertionParent.addChild(newButtonOutline); newButtonOutline.moveInParentCoordinates(100, 100); selection.insertionParent.addChild(newButtonLabel); newButtonLabel.moveInParentCoordinates(100, 100); selection.items = [newButtonLabel, newButtonOutline];
// console log the items that have been created.
console.log (selection.items);
console.log (selection.items[0][‘width’]);
console.log (selection.items[1][‘width’]);//align the button elements and group together commands.alignHorizontalCenter(); commands.alignVerticalCenter(); commands.group();
}
I added three console logs to the code to detect what objects are selected, and provide the widths of text object and rectangle object. The output of these console logs is as follows:
[ Text (‘Submit Button’) {
width: 113, height: 20
global X,Y: 62, 130
parent: Artboard (‘iPad – 1’)
fill: ff000000
},
Rectangle (‘Rectangle 1’) {
width: 100, height: 50
global X,Y: 62, 146
parent: Artboard (‘iPad – 1’)
stroke: ff2d3494
} ]
undefined
100
As you can see it is correctly logging my newly created text and rectangle, but then it gets weird. The log for the width of the text is undefined, but the width of the rectangle is correctly stated as 100. Am I doing something wrong here or is this a bug? Any help with getting the width of this text would be greatly appreciated!