Tutorials > 

To Zoom in to an AutoCAD Entity

 
 
 

The AutoCAD JavaScript API tutorial demonstrates how you can implement a command in AutoCAD to zoom to the extents of a selected entity.

  1. Use the following JavaScript code to create a command to zoom to the extents of a selected entity:
    // Command to zoom to the extents of a selected entity
    
    function zoomEntity() {
      try {
        
        // Set the options for our user prompt
    
        var peo = new Acad.PromptEntityOptions();
        peo.setMessageAndKeywords("\nSelect an entity", "");
        peo.allowObjectOnLockedLayer = true;
    
        // Ask the user to select an entity
    
        Acad.Editor.getEntity(peo).then(onComplete, onError);
      }
      catch(e) {
        console.log(e.message);
      }
    }
    
    function onComplete(jsonPromptResult) {
      try {
        
        // Parse the JSON string containing the prompt result
    
        var resultObj = JSON.parse(jsonPromptResult);
        if (resultObj && resultObj.status == 5100) {
          
          // If it was successful, get the selected entity...
    
          var entity = new Acad.DBEntity(resultObj.objectId);
    
          // ... and its extents
    
          var ext = entity.getExtents();
    
          // Zoom to the object's extents, choosing to animate the
          // view transition (if possible to do so)
    
          Acad.Editor.CurrentViewport.zoomExtents(
            ext.minPoint3d, ext.maxPoint3d, true
          );
        }
      }
      catch(e) {
        console.log(e.message); 
      }
    }
    
    function onError(jsonPromptResult) {
      console.log("\nProblem encountered.");
    }
    
    // Add the command, we'll make it transparent
    
    Acad.Editor.addCommand(
      "ZOOM_CMDS",
      "ZEN",
      "ZEN",
      Acad.CommandFlag.TRANSPARENT,
      zoomEntity
    );
    
    console.log("\nRegistered ZEN command.\n");
    NoteSave the file as ZoomEntity.js.
  2. Register the domain from where you want to load the JavaScript file using the TRUSTEDDOMAINS sysvar.
    (setvar "TRUSTEDDOMAINS" (strcat 
    (getvar "TRUSTEDDOMAINS") ";mywesbite.com"))
  3. Use the WEBLOAD command in AutoCAD to load the ZoomEntity.js file.
    (command "_.WEBLOAD" 
    "http://mywebsite.com/files/ZoomEntity.js")
  4. Execute the ZEN command from the command line to zoom to an entity.