Skip to main content
rcraighead
Legend
October 31, 2018
Answered

How to draw a rectangle in millimeters?

  • October 31, 2018
  • 3 replies
  • 3259 views

I want a script to create a rectangle in millimeters. Even when the file is set to "mm" the resulting rectangle is drawn in Points. I can multiply my dimensions by 2.834645669 to attain the correct dimension. Is there a more elegant way to do this? Here's what works so far ("80" and "8" will be replaced by variables).

var doc = app.activeDocument

var myLayer = doc.activeLayer

var mm = Number (2.834645669)

myLayer.pathItems.rectangle ( 200, 200, 80*mm, 8*mm);

This topic has been closed for replies.
Correct answer O2 Creative NZ

All scripting units are in points, I find little helper functions clear and concise,

myLayer.pathItems.rectangle ( inch(200), foot(200), mm(80), mm(8) );

function mm(n) {

  return n * 2.83464567;
}

function cm(n) {

  return n * 28.3464567;
}

function m(n) {

  return n * 283.464567;
}

function inch(n) {

  return n * 72;
}

function foot(n) {

  return n * 864;
}

You could also create a custom function

var myRect = createRectangle(myLayer, 200, 200, 80, 8);

function createRectangle(layer, x, y ,h ,w){

     return layer.pathItems.rectangle(mm(x), mm(y), mm(h), mm(w);)

}

3 replies

rcraighead
Legend
October 31, 2018

I consider both answers "Correct". Guess that's the beauty of scripting; there is usually more than one "correct" answer.

O2 Creative NZCorrect answer
Inspiring
October 31, 2018

All scripting units are in points, I find little helper functions clear and concise,

myLayer.pathItems.rectangle ( inch(200), foot(200), mm(80), mm(8) );

function mm(n) {

  return n * 2.83464567;
}

function cm(n) {

  return n * 28.3464567;
}

function m(n) {

  return n * 283.464567;
}

function inch(n) {

  return n * 72;
}

function foot(n) {

  return n * 864;
}

You could also create a custom function

var myRect = createRectangle(myLayer, 200, 200, 80, 8);

function createRectangle(layer, x, y ,h ,w){

     return layer.pathItems.rectangle(mm(x), mm(y), mm(h), mm(w);)

}

rcraighead
Legend
October 31, 2018

Very helpful. Thanks! I need to learn to use functions.

Silly-V
Legend
October 31, 2018

I'm not sure at this very moment what's the best way to start out as 'mm'  - but check out the UnitValue object in the Core Javascript Objects section of Adobe extendscript. This following snippet prints a rectangle which is 80 points turned into millimeters which unlike your post, divides the 80 points x the millimeter ratio.

    myLayer.pathItems.rectangle(200, 200, new UnitValue(80, "pt").as( "mm"), new UnitValue(80, "pt").as( "mm"));

rcraighead
Legend
October 31, 2018

Thank you. This reads more clearly.