Skip to main content
Participant
January 27, 2023
Answered

Script to Change font size and baseline randomly

  • January 27, 2023
  • 2 replies
  • 1317 views

So, I want to change the font size and baseline of each character in the selection randomly.

 

The baseline part works the way I want it to but for the line:
textRef.textRange.characters[i].characterAttributes.size=newSize;

I keep getting an "Invalid Text Range" error.  Here's the script:

 

//--------------------------
//Reference the document.
var docRef = activeDocument;

//Reference the first selection in the document.
var textRef = docRef.selection[0];

//Get the number of characters in the selected object.
var charCount=textRef.textRange.characters.length;

//Set a variable to serve as alternate positive and negative value.
var shiftSign=1;

//Let the user determine the baseline shift range and varying point size.
var shiftRange = prompt("Enter the distance, in points, by which you want the Baseline Shift to vary.", 1);
var minSize = prompt("Enter the minimum point size:", "12");
var maxSize = prompt("Enter the maximum point size:", "24");

//For each character...
for(i=0; i<charCount; i++){

//...flop the positive/negative...
shiftSign*=-1;

//...reference the range multiplied by a random number between 0 and 1...
var curShift=Math.abs(Math.random()*shiftRange);
var newSize=Math.random()*(maxSize - minSize)+minSize;

//...shift the current character by that amount.
textRef.textRange.characters[i].characterAttributes.baselineShift=curShift*shiftSign;

//...shift the current character size by that amount
textRef.textRange.characters[i].characterAttributes.size=newSize;


}

//-------------------------

 

Thanks for any insight!!

This topic has been closed for replies.
Correct answer Monika Gause

Maybe try TextTweaker: https://github.com/johnwun/js4ai/blob/master/textTweaker.js

2 replies

Monika Gause
Community Expert
Monika GauseCommunity ExpertCorrect answer
Community Expert
January 28, 2023
Participant
January 29, 2023

Thanks!  I'll check it out.  🙂

 

femkeblanco
Legend
January 28, 2023

Try changing

var minSize = prompt("Enter the minimum point size:", "12");
var maxSize = prompt("Enter the maximum point size:", "24");

to

var minSize = Number(prompt("Enter the minimum point size:", "12"));
var maxSize = Number(prompt("Enter the maximum point size:", "24"));

 

femkeblanco
Legend
January 28, 2023

To expound on the above: prompt() returns a string. The plus in the Math.random expression will concatenate rather than add, practically not changing the random number. If the difference between min and max is small, there is a chance the random number will be <0.1, which is an invalid font size.