javascriptmacospluginssketchappcocoascript

How can I change the document color space to P3 in Sketch?


I'm trying to create a plugin for Sketch, and I'd like to know how to change the color space of a Sketch document file to P3. Can anyone help?

var onRun = function(context) {
    var doc = context.document;

    doc.changeColorSpace(ColorSpace.P3, true);
    var colorName = [doc colorSpace];

    doc.showMessage("Color space changed to Display " + colorName);
}

Why isn’t the code working??


Solution

  • The problem with the code you posted seems to be that you're trying to call a new Sketch JS API method (changeColorSpace()) on an object derived from the old API (context).

    Here's how I'd rewrite your snippet to use the modern Sketch API only:

    // 1. Make sure to import all required APIs once in the beginning of your script
    var Document = require('sketch/dom').Document
    var UI = require('sketch/ui')
    
    var onRun = function(context) {
      // 2. Ignore the `context` argument here and obtain all required objects
      // (the current document in this case) via Sketch API explicitly
      let document = Document.getSelectedDocument()
      document.changeColorSpace(Document.ColorSpace.P3, true)
    
      UI.message('Color space changed to: ' + document.colorSpace)
    }