How to Use Effects & Filters - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/guides/using-effects/?platform=web&language=javascript
# How to Use Effects & Filters
Some [design blocks](/docs/cesdk/engine/guides/blocks/) in CE.SDK such as pages and graphic blocks allow you to add effects to them. An effect can modify the visual output of a block's [fill](/docs/cesdk/engine/guides/using-fills/). CreativeEditor SDK supports many different types of effects, such as adjustments, LUT filters, pixelization, glow, vignette and more.
Similarly to blocks, each effect instance has a numeric id which can be used to query and [modify its properties](/docs/cesdk/engine/api/block-properties/).
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-using-effects?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Using+Effects&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-using-effects).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-using-effects?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Using+Effects&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-using-effects)
##
Setup
This example uses the headless Creative Engine. See the [Setup](/docs/cesdk/engine/quickstart/) article for a detailed guide. To get started right away, you can also access the `block` API within a running CE.SDK instance via `cesdk.engine.block`. Check out the [APIs Overview](/docs/cesdk/engine/api/) to see that illustrated in more detail.
We create a scene containing a graphic block with an image fill and want to apply effects to this image.
```
import CreativeEngine from 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.43.0/index.js';
const config = {
license: 'mtLT-_GJwMhE7LDnO8KKEma7qSuzWuDxiKuQcxHKmz3fjaXWY2lT3o3Z2VdL5twm',
userId: 'guides-user',
baseURL: 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.43.0/assets'
};
CreativeEngine.init(config).then(async (engine) => {
document.getElementById('cesdk_container').append(engine.element);
const scene = engine.scene.create();
const page = engine.block.create('page');
engine.block.setWidth(page, 800);
engine.block.setHeight(page, 600);
engine.block.appendChild(scene, page);
engine.scene.zoomToBlock(page, 40, 40, 40, 40);
const block = engine.block.create('graphic');
engine.block.setShape(block, engine.block.createShape('rect'));
const imageFill = engine.block.createFill('image');
engine.block.setString(
imageFill,
'fill/image/imageFileURI',
'https://img.ly/static/ubq_samples/sample_1.jpg'
);
engine.block.setFill(block, imageFill);
engine.block.setPositionX(block, 100);
engine.block.setPositionY(block, 50);
engine.block.setWidth(block, 300);
engine.block.setHeight(block, 300);
engine.block.appendChild(page, block);
```
##
Accessing Effects
Not all types of design blocks support effects, so you should always first call the `supportsEffects(id: number): boolean` API before accessing any of the following APIs.
```
engine.block.supportsEffects(scene); // Returns false
engine.block.supportsEffects(block); // Returns true
```
##
Creating an Effect
In order to add effects to our block, we first have to create a new effect instance, which we can do by calling `createEffect(type: EffectType): number` and passing it the type of effect that we want. In this example, we create a pixelization and an adjustment effect.
Please refer to [the API docs](/docs/cesdk/engine/api/block-effects/) for a complete list of supported effect types.
```
const pixelize = engine.block.createEffect('pixelize');
const adjustments = engine.block.createEffect('adjustments');
```
##
Adding Effects
Now we have two effects but the output of our scene looks exactly the same as before. That is because we still need to append these effects to the graphic design block's list of effects, which we can do by calling `appendEffect(id: number, effect: number): void`.
We can also insert or remove effects from specific indices of a block's effect list using the `insertEffect(id: number, effect: number, index: number): void` and `removeEffect(id: number, index: number): void` APIs.
Effects will be applied to the block in the order they are placed in the block's effects list. If the same effect appears multiple times in the list, it will also be applied multiple times. In our case, the adjustments effect will be applied to the image first, before the result of that is then pixelated.
```
engine.block.appendEffect(block, pixelize);
engine.block.insertEffect(block, adjustments, 0);
// engine.block.removeEffect(rect, 0);
```
##
Querying Effects
Use the `getEffects(id: number): number[]` API to query the ordered list of effect ids of a block.
```
// This will return [adjustments, pixelize]
const effectsList = engine.block.getEffects(block);
```
##
Destroying Effects
If we created an effect that we don't want anymore, we have to make sure to destroy it using the same `destroy(id: number): void` API that we also call for design blocks.
Effects that are attached to a design block will be automatically destroyed when the design block is destroyed.
```
const unusedEffect = engine.block.createEffect('half_tone');
engine.block.destroy(unusedEffect);
```
##
Effect Properties
Just like design blocks, effects with different types have different properties that you can query and modify via the API. Use `findAllProperties(id: number): string[]` in order to get a list of all properties of a given effect.
Please refer to the [API docs](/docs/cesdk/engine/api/block-effects/) for a complete list of all available properties for each type of effect.
```
const allPixelizeProperties = engine.block.findAllProperties(pixelize);
const allAdjustmentProperties = engine.block.findAllProperties(adjustments);
```
Once we know the property keys of an effect, we can use the same APIs as for design blocks in order to [modify those properties](/docs/cesdk/engine/api/block-properties/).
Our adjustment effect here for example will not modify the output unless we at least change one of its adjustment properties - such as the brightness - to not be zero.
```
engine.block.setInt(pixelize, 'pixelize/horizontalPixelSize', 20);
engine.block.setFloat(adjustments, 'effect/adjustments/brightness', 0.2);
```
##
Disabling Effects
You can temporarily disable and enable the individual effects using the `setEffectEnabled(id: number, enabled: boolean): void` API. When the effects are applied to a block, all disabled effects are simply skipped. Whether an effect is currently enabled or disabled can be queried with `isEffectEnabled(id: number): boolean`.
```
engine.block.setEffectEnabled(pixelize, false);
engine.block.setEffectEnabled(
pixelize,
!engine.block.isEffectEnabled(pixelize)
);
```
Use the API to refresh the Asset Library - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/guides/refresh-asset-library/
CESDK/CE.SDK/Web Editor/Guides
# Use the API to refresh the Asset Library
Learn how to refresh the asset library in the CreativeEditorSDK on demand.
In this example, we explain how to use the `refetchAssetSources` API to refresh the asset library after a specific action is taken.
By default, the CreativeEditorSDK takes care of refreshing the asset library entries in most cases. For example, when uploading or deleting elements. In other cases, however, we might need to refresh the asset library on demand. An example would be a custom asset source that can be updated from outside the CreativeEditorSDK.
##
API Signature
The `refetchAssetSources` API will trigger a refetch of the asset source and update the asset library panel with the new items accordingly and can be used like the following:
```
// To refetch a specific asset source, you can pass the ID of the asset source as a parameter
cesdk.refetchAssetSources('ly.img.audio.upload');
// To refetch multiple asset sources, you can pass an array containing the IDs of the asset sources
cesdk.refetchAssetSources(['ly.img.video.upload', 'ly.img.image.upload']);
// To refetch all asset sources, you can call the API without any parameters
cesdk.refetchAssetSources();
```
##
Prerequisites
* [Get the latest stable version of **Node.js & NPM**](https://www.npmjs.com/get-npm)
* (Optional): [Get the latest stable version of **Yarn**](https://yarnpkg.com/getting-started)
##
1\. Add the CreativeEditorSDK to Your Project
```
npm install --save @cesdk/engine@1.43.0
```
##
2\. Configure a custom asset source
We will take Cloudinary as an example by adding a custom asset source to the configuration. Check out the [Customize The Asset Library](/docs/cesdk/ui/guides/customize-asset-library/) guide for detailed information about adding customizing the asset library.
```
const config = {
/* ...configuration options */
assetSources: {
'cloudinary-images': {
findAssets: () => {
/* fetch the images from Cloudinary to display in the asset panel */
}
}
},
ui: {
elements: {
libraries: {
insert: {
/* append the Cloudinary asset source to the image asset library entry */
}
}
}
}
};
```
##
3\. Refresh the asset source when a new image is uploaded
Let's consider that an image can be uploaded to Cloudinary from our application outside of the context of the CreativeEditorSDK. In this case, we can use the `refetchAssetSources` API to refresh the `cloudinary-images` asset source and update the asset panel with the new items.
```
CreativeEditorSDK.create(config).then(async (instance) => {
await instance.createDesignScene();
// create a Cloudinary upload widget
const myWidget = cloudinary.createUploadWidget(
{
cloudName: 'my-cloud-name'
},
(error, result) => {
if (!error && result && result.event === 'success') {
// refresh the asset panel after the image has been successfully uploaded
instance.refetchAssetSources('cloudinary-images');
}
}
);
// attach the widget to the upload button
document.getElementById('upload_widget').addEventListener('click', () => {
myWidget.open();
});
});
```
[
Previous
Fonts & Typefaces
](/docs/cesdk/ui/guides/fonts-typefaces/)[
Next
Placeholders
](/docs/cesdk/ui/guides/placeholders/)
Exporting to PDF with an underlayer - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/guides/underlayer/?platform=web&language=javascript
# Exporting to PDF with an underlayer
When printing on a non-white medium or on a special medium like fabric or glass, printing your design over an underlayer helps achieve the desired result. An underlayer will typically be printed using a special ink and be of the exact shape of your design.
When exporting to PDF, you can specify that an underlayer be automatically generated in the [ExportOptions](/docs/cesdk/engine/guides/export-blocks/). An underlayer will be generated by detecting the contour of all elements on a page and inserting a new block with the shape of the detected contour. This new block will be positioned behind all existing block. After exporting, the new block will be removed. The result will be a PDF file containing an additional shape of the same shape as your design and sitting behind it.
The ink to be used by the printer is specified in the [ExportOptions](/docs/cesdk/engine/guides/export-blocks/) with a [spot color](/docs/cesdk/engine/guides/colors/). You can also adjust the scale of the underlayer shape with a negative or positive offset, in design units.
####
Warning
Do not flatten the resulting PDF file or you will lose the underlayer shape which sits behind your design.
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-underlayer?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Underlayer&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-underlayer).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-underlayer?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Underlayer&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-underlayer)
##
Setup the scene
We first create a new scene with a graphic block that has a color fill.
```
document.getElementById('cesdk_container').append(engine.element);
const scene = engine.scene.create();
const page = engine.block.create('page');
engine.block.setWidth(page, 800);
engine.block.setHeight(page, 600);
engine.block.appendChild(scene, page);
engine.scene.zoomToBlock(page, 40, 40, 40, 40);
const block = engine.block.create('graphic');
engine.block.setShape(block, engine.block.createShape('star'));
engine.block.setPositionX(block, 350);
engine.block.setPositionY(block, 400);
engine.block.setWidth(block, 100);
engine.block.setHeight(block, 100);
const fill = engine.block.createFill('color');
engine.block.setFill(block, fill);
const rgbaBlue = { r: 0.0, g: 0.0, b: 1.0, a: 1.0 };
engine.block.setColor(fill, `fill/color/value`, rgbaBlue);
```
##
Add the underlayer's spot color
Here we instantiate a spot color with the known name of the ink the printer should use for the underlayer. The visual color approximation is not so important, so long as the name matches what the printer expects.
```
engine.editor.setSpotColorRGB('RDG_WHITE', 0.8, 0.8, 0.8);
```
##
Exporting with an underlayer
We enable the automatic generation of an underlayer on export with the option `exportPdfWithUnderlayer = true`. We specify the ink to use with `underlayerSpotColorName = 'RDG_WHITE'`. In this instance, we make the underlayer a bit smaller than our design so we specify an offset of 2 design units (e.g. millimeters) with `underlayerOffset = -2.0`.
```
await block
.export(page, 'application/pdf', {
exportPdfWithUnderlayer: true,
underlayerSpotColorName: 'RDG_WHITE',
underlayerOffset: -2.0
})
.then((blob) => {
const element = document.createElement('a');
element.setAttribute('href', window.URL.createObjectURL(blob));
element.setAttribute('download', 'underlayer_example.pdf');
element.style.display = 'none';
element.click();
element.remove();
});
```
How to Use Fills - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/guides/using-fills/?platform=web&language=javascript
# How to Use Fills
Some [design blocks](/docs/cesdk/engine/guides/blocks/) in CE.SDK allow you to modify or replace their fill. The fill is an object that defines the contents within the shape of a block. CreativeEditor SDK supports many different types of fills, such as images, solid colors, gradients and videos.
Similarly to blocks, each fill has a numeric id which can be used to query and [modify its properties](/docs/cesdk/engine/api/block-properties/).
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-using-fills?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Using+Fills&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-using-fills).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-using-fills?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Using+Fills&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-using-fills)
##
Setup
This example uses the headless CreativeEngine. See the [Setup](/docs/cesdk/engine/quickstart/) article for a detailed guide. To get started right away, you can also access the `block` API within a running CE.SDK instance via `cesdk.engine.block`. Check out the [APIs Overview](/docs/cesdk/engine/api/) to see that illustrated in more detail.
```
import CreativeEngine from 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.43.0/index.js';
const config = {
license: 'mtLT-_GJwMhE7LDnO8KKEma7qSuzWuDxiKuQcxHKmz3fjaXWY2lT3o3Z2VdL5twm',
userId: 'guides-user',
baseURL: 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.43.0/assets'
};
CreativeEngine.init(config).then(async (engine) => {
document.getElementById('cesdk_container').append(engine.element);
const scene = engine.scene.create();
const page = engine.block.create('page');
engine.block.setWidth(page, 800);
engine.block.setHeight(page, 600);
engine.block.appendChild(scene, page);
engine.scene.zoomToBlock(page, 40, 40, 40, 40);
const block = engine.block.create('graphic');
engine.block.setShape(block, engine.block.createShape('rect'));
engine.block.setFill(block, engine.block.createFill('color'));
engine.block.setWidth(block, 100);
engine.block.setHeight(block, 100);
engine.block.appendChild(page, block);
```
##
Accessing Fills
Not all types of design blocks support fills, so you should always first call the `supportsFill(id: number): boolean` API before accessing any of the following APIs.
```
engine.block.supportsFill(scene); // Returns false
engine.block.supportsFill(block); // Returns true
```
In order to receive the fill id of a design block, call the `getFill(id: number): number` API. You can now pass this id into other APIs in order to query more information about the fill, e.g. its type via the `getType(id: number): ObjectType` API.
```
const colorFill = engine.block.getFill(block);
const defaultRectFillType = engine.block.getType(colorFill);
```
##
Fill Properties
Just like design blocks, fills with different types have different properties that you can query and modify via the API. Use `findAllProperties(id: number): string[]` in order to get a list of all properties of a given fill.
For the solid color fill in this example, the call would return `["fill/color/value", "type"]`.
Please refer to the [API docs](/docs/cesdk/engine/api/block-fill-types/) for a complete list of all available properties for each type of fill.
```
const allFillProperties = engine.block.findAllProperties(colorFill);
```
Once we know the property keys of a fill, we can use the same APIs as for design blocks in order to modify those properties. For example, we can use `setColor(id: number, property: string, value: Color): void` in order to change the color of the fill to red.
Once we do this, our graphic block with rect shape will be filled with solid red.
```
engine.block.setColor(colorFill, 'fill/color/value', {
r: 1.0,
g: 0.0,
b: 0.0,
a: 1.0
});
```
##
Disabling Fills
You can disable and enable a fill using the `setFillEnabled(id: number, enabled: boolean): void` API, for example in cases where the design block should only have a stroke but no fill. Notice that you have to pass the id of the design block and not of the fill to the API.
```
engine.block.setFillEnabled(block, false);
engine.block.setFillEnabled(block, !engine.block.isFillEnabled(block));
```
##
Changing Fill Types
All design blocks that support fills allow you to also exchange their current fill for any other type of fill. In order to do this, you need to first create a new fill object using `createFill(type: FillType): number`.
We currently support the following fill types:
* `'//ly.img.ubq/fill/color'`
* `'//ly.img.ubq/fill/gradient/linear'`
* `'//ly.img.ubq/fill/gradient/radial'`
* `'//ly.img.ubq/fill/gradient/conical'`
* `'//ly.img.ubq/fill/image'`
* `'//ly.img.ubq/fill/video'`
* `'//ly.img.ubq/fill/pixelStream'`
Note: short types are also accepted, e.g. `'image'` instead of `'//ly.img.ubq/fill/image'`.
```
const imageFill = engine.block.createFill('image');
engine.block.setString(
imageFill,
'fill/image/imageFileURI',
'https://img.ly/static/ubq_samples/sample_1.jpg'
);
```
In order to assign a fill to a design block, simply call `setFill(id: number, fill: number): void`. Make sure to delete the previous fill of the design block first if you don't need it any more, otherwise we will have leaked it into the scene and won't be able to access it any more, because we don't know its id.
Notice that we don't use the `appendChild` API here, which only works with design blocks and not fills.
When a fill is attached to one design block, it will be automatically destroyed when the block itself gets destroyed.
```
engine.block.destroy(engine.block.getFill(block));
engine.block.setFill(block, imageFill);
/* The following line would also destroy imageFill */
// engine.block.destroy(circle);
```
##
Duplicating Fills
If we duplicate a design block with a fill that is only attached to this block, the fill will automatically be duplicated as well. In order to modify the properties of the duplicate fill, we have to query its id from the duplicate block.
```
const duplicateBlock = engine.block.duplicate(block);
engine.block.setPositionX(duplicateBlock, 450);
const autoDuplicateFill = engine.block.getFill(duplicateBlock);
engine.block.setString(
autoDuplicateFill,
'fill/image/imageFileURI',
'https://img.ly/static/ubq_samples/sample_2.jpg'
);
// const manualDuplicateFill = engine.block.duplicate(autoDuplicateFill);
// /* We could now assign this fill to another block. */
// engine.block.destroy(manualDuplicateFill);
```
##
Sharing Fills
It is also possible to share a single fill instance between multiple design blocks. In that case, changing the properties of the fill will apply to all of the blocks that it's attached to at once.
Destroying a block with a shared fill will not destroy the fill until there are no other design blocks left that still use that fill.
```
const sharedFillBlock = engine.block.create('graphic');
engine.block.setShape(sharedFillBlock, engine.block.createShape('rect'));
engine.block.setPositionX(sharedFillBlock, 350);
engine.block.setPositionY(sharedFillBlock, 400);
engine.block.setWidth(sharedFillBlock, 100);
engine.block.setHeight(sharedFillBlock, 100);
engine.block.appendChild(page, sharedFillBlock);
engine.block.setFill(sharedFillBlock, engine.block.getFill(block));
```
Control Audio & Video - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/api/block-video/?platform=web&language=javascript#time-offset-and-duration
# Control Audio & Video
In this example, we will show you how to use the [CreativeEditor SDK](https://img.ly/products/creative-sdk)'s CreativeEngine to configure and control audio and video through the `block` API.
##
Setup
This example uses the headless CreativeEngine. See the [Setup](/docs/cesdk/engine/quickstart/) article for a detailed guide. To get started right away, you can also access the `block` API within a running CE.SDK instance via `cesdk.engine.block`. Check out the [APIs Overview](../) to see that illustrated in more detail.
##
Time Offset and Duration
The time offset determines when a block becomes active during playback on the page's timeline, and the duration decides how long this block is active. Blocks within tracks are a special case in that they have an implicitly calculated time offset that is determined by their order and the total duration of their preceding blocks in the same track. As with any audio/video-related property, not every block supports these properties. Use `supportsTimeOffset` and `supportsDuration` to check.
```
supportsTimeOffset(id: DesignBlockId): boolean
```
Returns whether the block has a time offset property.
* `id`: The block to query.
* Returns true, if the block has a time offset property.
```
engine.block.supportsTimeOffset(audio);
```
```
setTimeOffset(id: DesignBlockId, offset: number): void
```
Set the time offset of the given block relative to its parent. The time offset controls when the block is first active in the timeline. The time offset is not supported by the page block.
* `id`: The block whose time offset should be changed.
* `offset`: The new time offset in seconds.
```
engine.block.setTimeOffset(audio, 2);
```
```
getTimeOffset(id: DesignBlockId): number
```
Get the time offset of the given block relative to its parent.
* `id`: The block whose time offset should be queried.
* Returns the time offset of the block.
```
engine.block.getTimeOffset(audio); /* Returns 2 */
```
```
supportsDuration(id: DesignBlockId): boolean
```
Returns whether the block has a duration property.
* `id`: The block to query.
* Returns true if the block has a duration property.
```
engine.block.supportsDuration(page);
```
```
setDuration(id: DesignBlockId, duration: number): void
```
Set the playback duration of the given block in seconds. The duration defines for how long the block is active in the scene during playback. If a duration is set on the page block, it becomes the duration source block. The duration is ignored when the scene is not in "Video" mode.
* `id`: The block whose duration should be changed.
* `duration`: The new duration in seconds.
```
engine.block.setDuration(page, 10);
```
```
getDuration(id: DesignBlockId): number
```
Get the playback duration of the given block in seconds.
* `id`: The block whose duration should be returned.
* Returns The block's duration.
```
engine.block.getDuration(page); /* Returns 10 */
```
```
supportsPageDurationSource(page: DesignBlockId, id: DesignBlockId): boolean
```
Returns whether the block can be marked as the element that defines the duration of the given page.
* `id`: The block to query.
* Returns true, if the block can be marked as the element that defines the duration of the given page.
```
engine.block.supportsPageDurationSource(page, block);
```
```
setPageDurationSource(page: DesignBlockId, id: DesignBlockId): void
```
Set an block as duration source so that the overall page duration is automatically determined by this. If no defining block is set, the page duration is calculated over all children. Only one block per page can be marked as duration source. Will automatically unmark the previously marked. Note: This is only supported for blocks that have a duration.
* `page`: The page block for which it should be enabled.
* `id`: The block that should be updated.
```
engine.block.setPageDurationSource(page, block);
```
```
isPageDurationSource(id: DesignBlockId): boolean
```
Query whether the block is a duration source block for the page.
* `id`: The block whose duration source property should be queried.
* Returns If the block is a duration source for a page.
```
engine.block.isPageDurationSource(block);
```
```
removePageDurationSource(id: DesignBlockId): void
```
Remove the block as duration source block for the page. If a scene or page is given as block, it is deactivated for all blocks in the scene or page.
* `id`: The block whose duration source property should be removed.
```
engine.block.removePageDurationSource(page);
```
```
setNativePixelBuffer(id: number, buffer: HTMLCanvasElement | HTMLVideoElement): void
```
Update the pixels of the given pixel stream fill block.
* `id`: The pixel stream fill block.
* `buffer`: Use pixel data from a canvas or a video element.
```
const pixelStreamFill = engine.block.createFill('pixelStream');
```
##
Trim
You can select a specific range of footage from your audio/video resource by providing a trim offset and a trim length. The footage will loop if the trim's length is shorter than the block's duration. This behavior can also be disabled using the `setLooping` function.
```
supportsTrim(id: DesignBlockId): boolean
```
Returns whether the block has trim properties.
* `id`: The block to query.
* Returns true, if the block has trim properties.
```
engine.block.supportsTrim(videoFill);
```
```
setTrimOffset(id: DesignBlockId, offset: number): void
```
Set the trim offset of the given block or fill. Sets the time in seconds within the fill at which playback of the audio or video clip should begin. This requires the video or audio clip to be loaded.
* `id`: The block whose trim should be updated.
* `offset`: The new trim offset.
```
engine.block.setTrimOffset(videoFill, 1);
```
```
getTrimOffset(id: DesignBlockId): number
```
Get the trim offset of this block. \* This requires the video or audio clip to be loaded.
* `id`: The block whose trim offset should be queried.
* Returns the trim offset in seconds.
```
engine.block.getTrimOffset(videoFill); /* Returns 1 */
```
```
setTrimLength(id: DesignBlockId, length: number): void
```
Set the trim length of the given block or fill. The trim length is the duration of the audio or video clip that should be used for playback. After reaching this value during playback, the trim region will loop. This requires the video or audio clip to be loaded.
* `id`: The object whose trim length should be updated.
* `length`: The new trim length in seconds.
```
engine.block.setTrimLength(videoFill, 5);
```
```
getTrimLength(id: DesignBlockId): number
```
Get the trim length of the given block or fill.
* `id`: The object whose trim length should be queried.
* Returns the trim length of the object.
```
engine.block.getTrimLength(videoFill); /* Returns 5 */
```
##
Playback Control
You can start and pause playback and seek to a certain point on the scene's timeline. There's also a solo playback mode to preview audio and video blocks individually while the rest of the scene stays frozen. Finally, you can enable or disable the looping behavior of blocks and control their audio volume.
```
setPlaying(id: DesignBlockId, enabled: boolean): void
```
Set whether the block should be playing during active playback.
* `id`: The block that should be updated.
* `enabled`: Whether the block should be playing its contents.
```
engine.block.setPlaying(page, true);
```
```
isPlaying(id: DesignBlockId): boolean
```
Returns whether the block is playing during active playback.
* `id`: The block to query.
* Returns whether the block is playing during playback.
```
engine.block.isPlaying(page);
```
```
setSoloPlaybackEnabled(id: DesignBlockId, enabled: boolean): void
```
Set whether the given block or fill should play its contents while the rest of the scene remains paused. Setting this to true for one block will automatically set it to false on all other blocks.
* `id`: The block or fill to update.
* `enabled`: Whether the block's playback should progress as time moves on.
```
engine.block.setSoloPlaybackEnabled(videoFill, true);
```
```
isSoloPlaybackEnabled(id: DesignBlockId): boolean
```
Return whether the given block or fill is currently set to play its contents while the rest of the scene remains paused.
* `id`: The block or fill to query.
* Returns Whether solo playback is enabled for this block.
```
engine.block.isSoloPlaybackEnabled(videoFill);
```
```
supportsPlaybackTime(id: DesignBlockId): boolean
```
Returns whether the block has a playback time property.
* `id`: The block to query.
* Returns whether the block has a playback time property.
```
engine.block.supportsPlaybackTime(page);
```
```
setPlaybackTime(id: DesignBlockId, time: number): void
```
Set the playback time of the given block.
* `id`: The block whose playback time should be updated.
* `time`: The new playback time of the block in seconds.
```
engine.block.setPlaybackTime(page, 1);
```
```
getPlaybackTime(id: DesignBlockId): number
```
Get the playback time of the given block.
* `id`: The block to query.
* Returns the playback time of the block in seconds.
```
engine.block.getPlaybackTime(page);
```
```
isVisibleAtCurrentPlaybackTime(id: DesignBlockId): boolean
```
Returns whether the block should be visible on the canvas at the current playback time.
* `id`: The block to query.
* Returns Whether the block should be visible on the canvas at the current playback time.
```
engine.block.isVisibleAtCurrentPlaybackTime(block);
```
```
supportsPlaybackControl(id: DesignBlockId): boolean
```
Returns whether the block supports a playback control.
* `block`: The block to query.
* Returns Whether the block has playback control.
```
engine.block.supportsPlaybackControl(videoFill);
```
```
setLooping(id: DesignBlockId, looping: boolean): void
```
Set whether the block should restart from the beginning again or stop.
* `block`: The block or video fill to update.
* `looping`: Whether the block should loop to the beginning or stop.
```
engine.block.setLooping(videoFill, true);
```
```
isLooping(id: DesignBlockId): boolean
```
Query whether the block is looping.
* `block`: The block to query.
* Returns Whether the block is looping.
```
engine.block.isLooping(videoFill);
```
```
setMuted(id: DesignBlockId, muted: boolean): void
```
Set whether the audio of the block is muted.
* `block`: The block or video fill to update.
* `muted`: Whether the audio should be muted.
```
engine.block.setMuted(videoFill, true);
```
```
isMuted(id: DesignBlockId): boolean
```
Query whether the block is muted.
* `block`: The block to query.
* Returns Whether the block is muted.
```
engine.block.isMuted(videoFill);
```
```
setVolume(id: DesignBlockId, volume: number): void
```
Set the audio volume of the given block.
* `block`: The block or video fill to update.
* `volume`: The desired volume with a range of `0, 1`.
```
engine.block.setVolume(videoFill, 0.5); /* 50% volume */
```
```
getVolume(id: DesignBlockId): number
```
Get the audio volume of the given block.
* `block`: The block to query.
* Returns The volume with a range of `0, 1`.
```
engine.block.getVolume(videoFill);
```
```
getVideoWidth(id: DesignBlockId): number
```
Get the video width in pixels of the video resource that is attached to the given block.
* `block`: The video fill.
* Returns The video width in pixels or an error.
```
const videoWidth = engine.block.getVideoWidth(videoFill);
```
```
getVideoHeight(id: DesignBlockId): number
```
Get the video height in pixels of the video resource that is attached to the given block.
* `block`: The video fill.
* Returns The video height in pixels or an error.
```
const videoHeight = engine.block.getVideoHeight(videoFill);
```
##
Resource Control
Until an audio/video resource referenced by a block is loaded, properties like the duration of the resource aren't available, and accessing those will lead to an error. You can avoid this by forcing the resource you want to access to load using `forceLoadAVResource`.
```
forceLoadAVResource(id: DesignBlockId): Promise
```
Begins loading the required audio and video resource for the given video fill or audio block.
* `id`: The video fill or audio block whose resource should be loaded.
* Returns A Promise that resolves once the resource has finished loading.
```
await engine.block.forceLoadAVResource(videoFill);
```
```
unstable_isAVResourceLoaded(id: DesignBlockId): boolean
```
Returns whether the audio and video resource for the given video fill or audio block is loaded.
* `id`: The video fill or audio block.
* Returns The loading state of the resource.
```
const isLoaded = engine.block.unstable_isAVResourceLoaded(videoFill);
```
```
getAVResourceTotalDuration(id: DesignBlockId): number
```
Get the duration in seconds of the video or audio resource that is attached to the given block.
* `id`: The video fill or audio block.
* Returns The video or audio file duration.
```
engine.block.getAVResourceTotalDuration(videoFill);
```
##
Thumbnail Previews
For a user interface, it can be helpful to have image previews in the form of thumbnails for any given video resource. For videos, the engine can provide one or more frames using `generateVideoThumbnailSequence`. Pass the video fill that references the video resource. In addition to video thumbnails, the engine can also render compositions of design blocks over time. To do this pass in the respective design block. The video editor uses these to visually represent blocks in the timeline.
In order to visualize audio signals `generateAudioThumbnailSequence` can be used. This generates a sequence of values in the range of 0 to 1 that represent the loudness of the signal. These values can be used to render a waveform pattern in any custom style.
Note: there can be at most one thumbnail generation request per block at any given time. If you don't want to wait for the request to finish before issuing a new request, you can cancel it by calling the returned function.
```
generateVideoThumbnailSequence(id: DesignBlockId, thumbnailHeight: number, timeBegin: number, timeEnd: number, numberOfFrames: number, onFrame: (frameIndex: number, result: ImageData | Error) => void): () => void
```
Generate a sequence of thumbnails for the given video fill or design block. Note: there can only be one thumbnail generation request in progress for a given block.
* `id`: The video fill or design block.
* `thumbnailHeight`: The height of a thumbnail. The width will be calculated from the video aspect ratio.
* `timeBegin`: The time in seconds relative to the time offset of the design block at which the thumbnail sequence should start.
* `timeEnd`: The time in seconds relative to the time offset of the design block at which the thumbnail sequence should end.
* `numberOfFrames`: The number of frames to generate.
* `onFrame`: Gets passed the frame index and RGBA image data.
* Returns A method that will cancel any thumbnail generation request in progress for this block.
```
const cancelVideoThumbnailGeneration = engine.block.generateVideoThumbnailSequence(
videoFill /* video fill or any design block */,
128 /* thumbnail height, width will be calculated from aspect ratio */,
0.5 /* begin time */,
9.5 /* end time */,
10 /* number of thumbnails to generate */,
async (frame, width, height, imageData) => {
const image = await createImageBitmap(imageData);
// Draw the image...
}
);
```
```
generateAudioThumbnailSequence(id: DesignBlockId, samplesPerChunk: number, timeBegin: number, timeEnd: number, numberOfSamples: number, numberOfChannels: number, onChunk: (chunkIndex: number, result: Float32Array | Error) => void): () => void
```
Generate a thumbnail sequence for the given audio block or video fill. A thumbnail in this case is a chunk of samples in the range of 0 to 1. In case stereo data is requested, the samples are interleaved, starting with the left channel.
* `id`: The audio block or video fill.
* `samplesPerChunk`: The number of samples per chunk. `onChunk` is called when this many samples are ready.
* `timeBegin`: The time in seconds at which the thumbnail sequence should start.
* `timeEnd`: The time in seconds at which the thumbnail sequence should end.
* `numberOfSamples`: The total number of samples to generate.
* `numberOfChannels`: The number of channels in the output. 1 for mono, 2 for stereo.
* `onChunk`: This gets passed an index and a chunk of samples whenever it's ready, or an error.
```
const cancelAudioThumbnailGeneration = engine.block.generateAudioThumbnailSequence(
audio /* audio or video fill */,
20 /* number of samples per chunk */,
0.5 /* begin time */,
9.5 /* end time */,
10 * 20 /* total number of samples, will produce 10 calls with 20 samples per chunk */,
2, /* stereo, interleaved samples for the left and right channels */,
(chunkIndex, chunkSamples) => {
drawWavePattern(chunkSamples);
}
);
```
Integrate Creative Editor - CE.SDK | IMG.LY Docs [web/angular/javascript] https://img.ly/docs/cesdk/ui/quickstart/?platform=web&language=javascript&framework=angular
# Integrate Creative Editor
In this example, we will show you how to integrate [CreativeEditor SDK](https://img.ly/products/creative-sdk) in an Angular app.
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/integrate-with-angular?title=IMG.LY%27s+CE.SDK%3A+Integrate+With+Angular&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/integrate-with-angular).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/integrate-with-angular?title=IMG.LY%27s+CE.SDK%3A+Integrate+With+Angular&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/integrate-with-angular)
##
Prerequisites
* (Optional): [Get the latest stable version of **Node.js & NPM**](https://www.npmjs.com/get-npm)
* [Setup Angular](https://angular.io/guide/setup-local)
##
Setup
Note that, for convenience we serve all SDK assets (e.g. images, stickers, fonts etc.) from our CDN by default. For use in a production environment we recommend [serving assets from your own servers](/docs/cesdk/ui/guides/assets-served-from-your-own-servers/).
###
1\. Add CE.SDK to your Project
Install the `@cesdk/cesdk-js` dependency via `npm install --save @cesdk/cesdk-js`.
The SDK is served entirely via CDN, so we just need to import the `CreativeEditorSDK` module and the stylesheet containing the default theme settings.
```
import CreativeEditorSDK, { Configuration } from '@cesdk/cesdk-js';
```
###
2\. Acquire a container element reference
We need to provide a container to the CE.SDK. This is done through an `ElementRef`. For this example, the container is specified as a `
` that fills the whole browser window in `app.component.html`:
``
```
@ViewChild('cesdk_container') containerRef: ElementRef = {} as ElementRef;
```
###
3\. Instantiate CreativeEditor SDK
The last step involves the configuration and instantiation of the SDK. We need to provide the aforementioned container and optionally a license file to instantiate the SDK.
```
const config: Configuration = {
license:
'mtLT-_GJwMhE7LDnO8KKEma7qSuzWuDxiKuQcxHKmz3fjaXWY2lT3o3Z2VdL5twm',
// Serve assets from IMG.LY cdn or locally
baseURL: 'https://cdn.img.ly/packages/imgly/cesdk-js/1.43.0/assets',
// Enable local uploads in Asset Library
callbacks: { onUpload: 'local' }
};
CreativeEditorSDK.create(this.containerRef.nativeElement, config).then(
async (instance: any) => {
// Do something with the instance of CreativeEditor SDK, for example:
// Populate the asset library with default / demo asset sources.
instance.addDefaultAssetSources();
instance.addDemoAssetSources({ sceneMode: 'Design' });
await instance.createDesignScene();
}
);
```
###
4\. Serving Webpage locally
In order to use the editor we need run `ng serve` for a dev server.
This will bring up a server at [`http://localhost:4200/`](http://localhost:4200/)
###
Congratulations!
You've got CE.SDK up and running. Get to know the SDK and dive into the next steps, when you're ready:
* [Perform Basic Configuration](/docs/cesdk/ui/configuration/basics/)
* [Serve assets from your own servers](/docs/cesdk/ui/guides/assets-served-from-your-own-servers/)
* [Create and use a license key](/docs/cesdk/engine/quickstart/#licensing)
* [Configure Callbacks](/docs/cesdk/ui/configuration/callbacks/)
* [Add Localization](/docs/cesdk/ui/guides/i18n/)
* [Adapt the User Interface](/docs/cesdk/ui/guides/theming/)
Modify Appearance - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/api/block-appearance/?platform=web&language=javascript
# Modify Appearance
In this example, we will show you how to use the [CreativeEditor SDK](https://img.ly/products/creative-sdk)'s CreativeEngine to modify a blocks appearance through the `block` API.
##
Setup
This example uses the headless CreativeEngine. See the [Setup](/docs/cesdk/engine/quickstart/) article for a detailed guide. To get started right away, you can also access the `block` API within a running CE.SDK instance via `cesdk.engine.block`. Check out the [APIs Overview](../) to see that illustrated in more detail.
##
Common Properties
Common properties are properties that occur on multiple block types. For instance, fill color properties are available for all the shape blocks and the text block. That's why we built convenient setter and getter functions for these properties. So you don't have to use the generic setters and getters and don't have to provide a specific property path. There are also `has*` functions to query if a block supports a set of common properties.
###
Opacity
Set the translucency of the entire block.
```
supportsOpacity(id: DesignBlockId): boolean
```
Query if the given block has an opacity.
* `id`: The block to query.
* Returns true, if the block has an opacity.
```
engine.block.supportsOpacity(image);
```
```
setOpacity(id: DesignBlockId, opacity: number): void
```
Set the opacity of the given design block. Required scope: 'layer/opacity'
* `id`: The block whose opacity should be set.
* `opacity`: The opacity to be set. The valid range is 0 to 1.
```
engine.block.setOpacity(image, 0.5);
```
```
getOpacity(id: DesignBlockId): number
```
Get the opacity of the given design block.
* `id`: The block whose opacity should be queried.
* Returns The opacity.
```
engine.block.getOpacity(image);
```
###
Blend Mode
Define the blending behavior of a block.
```
supportsBlendMode(id: DesignBlockId): boolean
```
Query if the given block has a blend mode.
* `id`: The block to query.
* Returns true, if the block has a blend mode.
```
engine.block.supportsBlendMode(image);
```
```
setBlendMode(id: DesignBlockId, blendMode: BlendMode): void
```
Set the blend mode of the given design block. Required scope: 'layer/blendMode'
* `id`: The block whose blend mode should be set.
* `blendMode`: The blend mode to be set.
* Returns
```
engine.block.setBlendMode(image, 'Multiply');
```
```
getBlendMode(id: DesignBlockId): BlendMode
```
Get the blend mode of the given design block.
* `id`: The block whose blend mode should be queried.
* Returns The blend mode.
```
engine.block.getBlendMode(image);
```
```
type BlendMode = 'PassThrough' | 'Normal' | 'Darken' | 'Multiply' | 'ColorBurn' | 'Lighten' | 'Screen' | 'ColorDodge' | 'Overlay' | 'SoftLight' | 'HardLight' | 'Difference' | 'Exclusion' | 'Hue' | 'Saturation' | 'Color' | 'Luminosity'
```
```
engine.block.setBlendMode(image, 'Multiply');
```
Adding New Buttons - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/customization/guides/addingNewButtons/#adding-a-document-button-to-the-dock
CESDK/CE.SDK/Web Editor/Customization/Guides
# Adding New Buttons
Learn how to add new buttons to different location of the web editor
Customization not only includes changing the existing behavior but also extends to adding new features tailored to your needs. This guide will show you how to add new buttons to different locations within the web editor.
##
Adding a Document Button to the Dock
In our default configuration of the web editor, we only show dock buttons that open asset libraries. In this example, we want to extend that functionality by adding a button that opens the document inspector.
In the default view of the web editor, the inspector panel is not always visible. Additionally, the document inspector only appears if no block is selected. If your use case requires a simple user interface with just the inspector bar and an easy way for the customer to access the document inspector, we can now add a custom button to achieve this.
First, we need to register a new component. This component will check if the document inspector is already open. To open it, we will deselect all blocks and use the [Panel API](/docs/cesdk/ui/customization/api/panel/) to open the inspector panel.
```
cesdk.ui.registerComponent(
'document.dock',
({ builder: { Button }, engine }) => {
const inspectorOpen = cesdk.ui.isPanelOpen('//ly.img.panel/inspector');
Button('open-document', {
label: 'Document',
// Using the open state to mark the button as selected
isSelected: inspectorOpen,
onClick: () => {
// Deselect all blocks to enable the document inspector
engine.block.findAllSelected().forEach((blockId) => {
engine.block.setSelected(blockId, false);
});
if (inspectorOpen) {
cesdk.ui.closePanel('//ly.img.panel/inspector');
} else {
cesdk.ui.openPanel('//ly.img.panel/inspector');
}
}
});
}
);
```
That is all for the component for now. What is left to do is to add this component to the dock order.
```
cesdk.ui.setDockOrder([
...cesdk.ui.getDockOrder(),
// We add a spacer to push the document inspector button to the bottom
'ly.img.spacer',
// The id of the component we registered earlier
'document.dock'
]);
```
##
Add a Button to the Canvas Menu to Mark Blocks
In our next example, we aim to establish a workflow where a designer can review a design and mark blocks that need to be reviewed by another designer. We will define a field in the metadata for this purpose and add a button to the canvas menu that toggles this marker.
Once again, we start by registering a new component.
```
cesdk.ui.registerComponent(
'marker.canvasMenu',
({ builder: { Button }, engine }) => {
const selectedBlockIds = engine.block.findAllSelected();
// Only show the button if exactly one block is selected
if (selectedBlockIds.length !== 1) return;
const selectedBlockId = selectedBlockIds[0];
// Check if the block is already marked
const isMarked = engine.block.hasMetadata(selectedBlockId, 'marker');
Button('marker-button', {
label: isMarked ? 'Unmark' : 'Mark',
// Change the color if the block is marked to indicate the state
color: isMarked ? 'accent' : undefined,
onClick: () => {
if (isMarked) {
engine.block.removeMetadata(selectedBlockId, 'marker');
} else {
// Metadata is a simple key-value store. We do not care about the
// actual value but only if it was set.
engine.block.setMetadata(selectedBlockId, 'marker', 'marked');
}
}
});
}
);
```
Now, instead of appending this button, we want to put it at the beginning as this needs to be a prominent feature.
```
cesdk.ui.setCanvasMenuOrder([
'marker.canvasMenu',
...cesdk.ui.getCanvasMenuOrder()
]);
```
[
Previous
Moving Existing Buttons
](/docs/cesdk/ui/customization/guides/movingExistingButtons/)[
Next
One-Click Quick Action Plugins
](/docs/cesdk/ui/customization/guides/oneClickQuickActionPlugins/)
Save Scenes to an Archive - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/guides/save-scene-to-archive/?platform=web&language=javascript
# Save Scenes to an Archive
In this example, we will show you how to save scenes as an archive with the [CreativeEditor SDK](https://img.ly/products/creative-sdk).
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-save-scene-to-archive?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Save+Scene+To+Archive&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-save-scene-to-archive).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-save-scene-to-archive?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Save+Scene+To+Archive&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-save-scene-to-archive)
The CreativeEngine allows you to save scenes in a binary format to share them between editors or store them for later editing. As an archive, the resulting `Blob` includes all pages and any hidden elements and all the asset data.
To get hold of such a `Blob`, you need to use `engine.scene.saveToArchive()`. This is an asynchronous method returning a `Promise`. After waiting for the `Promise` to resolve, we receive a `Blob` holding the entire scene currently loaded in the editor including its assets' data.
```
engine.scene
.saveToArchive()
.then((blob) => {
const formData = new FormData();
formData.append('file', blob);
fetch('/upload', {
method: 'POST',
body: formData
});
})
.catch((error) => {
console.error('Save failed', error);
});
```
That `Blob` can then be treated as a form file parameter and sent to a remote location.
```
const formData = new FormData();
formData.append('file', blob);
fetch('/upload', {
method: 'POST',
body: formData
});
```
##
Loading Scene Archives
Loading a scene archives requires unzipping the archives contents to a location, that's accessible to the CreativeEngine. One could for example unzip the archive via `unzip archive.zip` and then serve its contents using `$ npx serve`. This spins up a local test server, that serves everything contained in the current directory at `http://localhost:3000`
The archive can then be loaded by calling `await engine.scene.loadFromURL('http://localhost:3000/scene.scene')`. See [loading scenes](/docs/cesdk/engine/guides/load-scene-from-url/) for more details. All asset paths in the archive are then resolved relative to the location of the `scene.scene` file. For an image, that would result in `'http://localhost:3000/images/1234.jpeg'`. After loading all URLs are fully resolved with the location of the `scene.scene` file and the scene behaves like any other scene.
##
Resolving assets from a different source
The engine will use its [URI resolver](/docs/cesdk/engine/guides/resolve-custom-uri/) to resolve all asset paths it encounters. This allows you to redirect requests for the assets contained in archive to a different location. To do so, you can add a custom resolver, that redirects requests for assets to a different location. Assuming you store your archived scenes in a `scenes/` directory, this would be an example of how to do so:
Load Scenes From a Blob - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/guides/load-scene-from-blob/?platform=web&language=javascript
# Load Scenes From a Blob
In this example, we will show you how to load scenes with the [CreativeEditor SDK](https://img.ly/products/creative-sdk).
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-load-scene-from-blob?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Load+Scene+From+Blob&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-load-scene-from-blob).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-load-scene-from-blob?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Load+Scene+From+Blob&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-load-scene-from-blob)
Loading an existing scene allows resuming work on a previous session or adapting an existing template to your needs. This can be done by passing a binary string that describes a scene to the `engine.scene.loadFromString()` function.
####
Warning
Saving a scene can be done as a either _scene file_ or as an _archive file_ (c.f. [Saving scenes](/docs/cesdk/engine/guides/save-scene/)). A _scene file_ does not include any fonts or images. Only the source URIs of assets, the general layout, and element properties are stored. When loading scenes in a new environment, ensure previously used asset URIs are available. Conversely, an _archive file_ contains within it the scene's assets and references them as relative URIs.
In this example, we fetch a scene from a remote URL and load it as `sceneBlob`.
```
const sceneUrl =
'https://cdn.img.ly/assets/demo/v1/ly.img.template/templates/cesdk_postcard_1.scene';
const sceneBlob = await fetch(sceneUrl).then((response) => {
return response.blob();
});
```
To acquire a scene string from `sceneBlob`, we need to read its contents into a string.
```
const blobString = await sceneBlob.text();
```
We can then pass that string to the `engine.scene.loadFromString(sceneContent: string): Promise` function. The editor will reset and present the given scene to the user. The function is asynchronous and the returned `Promise` resolves if the scene load succeeded.
```
let scene = await engine.scene
.loadFromString(blobString)
.then(() => {
console.log('Load succeeded');
let text = engine.block.findByType('text')[0];
engine.block.setDropShadowEnabled(text, true);
})
.catch((error) => {
console.error('Load failed', error);
});
```
From this point on we can continue to modify our scene. In this example, assuming the scene contains a text element, we add a drop shadow to it. See [Modifying Scenes](/docs/cesdk/engine/guides/blocks/) for more details.
```
let text = engine.block.findByType('text')[0];
engine.block.setDropShadowEnabled(text, true);
```
Scene loads may be reverted using `cesdk.engine.editor.undo()`.
To later save your scene, see [Saving Scenes](/docs/cesdk/engine/guides/save-scene/).
Source Sets - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/guides/source-sets/?platform=web&language=javascript
# Source Sets
Source sets allow specifying an entire set of sources, each with a different size, that should be used for drawing a block. The appropriate source is then dynamically chosen based on the current drawing size. This allows using the same scene to render a preview on a mobile screen using a small image file and a high-resolution file for print in the backend.
This guide will show you how to specify source sets both for existing blocks and when defining assets.
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-source-sets?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Source+Sets&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-source-sets).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-source-sets?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Source+Sets&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-source-sets)
###
Drawing
When an image needs to be drawn, the current drawing size in screen pixels is calculated and the engine looks up the most appropriate source file to draw at that resolution.
1. If a source set is set, the source with the closest size exceeding the drawing size is used
2. If no source set is set, the full resolution image is downscaled to a maximum edge length of 4096 (configurable via `maxImageSize` setting) and drawn to the target area
This also gives more control about up- and downsampling to you, as all intermediate resolutions can be generated using tooling of your choice.
**Source sets are also used during export of your designs and will resolve to the best matching asset for the export resolution.**
##
Setup the scene
We first create a new scene with a new page.
```
document.getElementById('cesdk_container').append(engine.element);
const scene = engine.scene.create();
const page = engine.block.create('page');
engine.block.setWidth(page, 800);
engine.block.setHeight(page, 600);
engine.block.appendChild(scene, page);
engine.scene.zoomToBlock(page, 50, 50, 50, 50);
```
##
Using a Source Set for an existing Block
To make use of a source set for an existing image fill, we use the `setSourceSet` API. This defines a set of sources and specifies height and width for each of these sources. The engine then chooses the appropriate source during drawing. You may query an existing source set using `getSourceSet`. You can add sources to an existing source set with `addImageFileURIToSourceSet`.
```
let block = engine.block.create('graphic');
engine.block.setShape(block, engine.block.createShape('rect'));
const imageFill = engine.block.createFill('image');
engine.block.setSourceSet(imageFill, 'fill/image/sourceSet', [
{
uri: 'https://img.ly/static/ubq_samples/sample_1_512x341.jpg',
width: 512,
height: 341
},
{
uri: 'https://img.ly/static/ubq_samples/sample_1_1024x683.jpg',
width: 1024,
height: 683
},
{
uri: 'https://img.ly/static/ubq_samples/sample_1_2048x1366.jpg',
width: 2048,
height: 1366
}
]);
engine.block.setFill(block, imageFill);
console.log(engine.block.getSourceSet(imageFill, 'fill/image/sourceSet'));
engine.block.appendChild(page, block);
```
##
Using a Source Set in an Asset
For assets, source sets can be defined in the `payload.sourceSet` field. This is directly translated to the `sourceSet` property when applying the asset. The resulting block is configured in the same way as the one described above. The code demonstrates how to add an asset that defines a source set to a local source and how `applyAsset` handles a populated `payload.sourceSet`.
```
const assetWithSourceSet = {
id: 'my-image',
meta: {
kind: 'image',
fillType: '//ly.img.ubq/fill/image'
},
payload: {
sourceSet: [
{
uri: 'https://img.ly/static/ubq_samples/sample_1_512x341.jpg',
width: 512,
height: 341
},
{
uri: 'https://img.ly/static/ubq_samples/sample_1_1024x683.jpg',
width: 1024,
height: 683
},
{
uri: 'https://img.ly/static/ubq_samples/sample_1_2048x1366.jpg',
width: 2048,
height: 1366
}
]
}
};
```
##
Video Source Sets
Source sets can also be used for video fills. This is done by setting the `sourceSet` property of the video fill. The engine will then use the source with the closest size exceeding the drawing size.
Thumbnails will use the smallest source if `features/matchThumbnailSourceToFill` is disabled, which is the default.
For low end devices or scenes with large videos, you can force the preview to always use the smallest source when editing by enabling `features/forceLowQualityVideoPreview`. On export, the highest quality source is used in any case.
```
const videoFill = engine.block.createFill('video');
engine.block.setSourceSet(videoFill, 'fill/video/sourceSet', [
{
uri: 'https://img.ly/static/example-assets/sourceset/1x.mp4',
width: 1920,
height: 1080
}
]);
await engine.block.addVideoFileURIToSourceSet(
videoFill,
'fill/video/sourceSet',
'https://img.ly/static/example-assets/sourceset/2x.mp4'
);
```
Observe Editing State - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/api/editor-state/?platform=web&language=javascript
# Observe Editing State
In this example, we will show you how to use the [CreativeEditor SDK](https://img.ly/products/creative-sdk)'s CreativeEngine to set and query the editor state in the `editor` API, i.e., what type of content the user is currently able to edit.
##
Setup
This example uses the headless CreativeEngine. See the [Setup](/docs/cesdk/engine/quickstart/) article for a detailed guide. To get started right away, you can also access the `block` API within a running CE.SDK instance via `cesdk.engine.block`. Check out the [APIs Overview](../) to see that illustrated in more detail.
##
State
The editor state consists of the current edit mode, which informs what type of content the user is currently able to edit. The edit mode can be set to either `'Transform'`, `'Crop'`, `'Text'`, or a custom user-defined one. You can also query the intended mouse cursor and the location of the text cursor while editing text.
Instead of having to constantly query the state in a loop, you can also be notified when the state has changed to then act on these changes in a callback.
```
onStateChanged: (callback: () => void) => (() => void)
```
Subscribe to changes to the editor state.
* `callback`: This function is called at the end of the engine update, if the editor state has changed.
* Returns A method to unsubscribe.
```
const unsubscribeState = engine.editor.onStateChanged(() =>
```
```
setEditMode(mode: EditMode): void
```
Set the edit mode of the editor. An edit mode defines what type of content can currently be edited by the user. Hint: the initial edit mode is "Transform".
* `mode`: "Transform", "Crop", "Text", "Playback", "Trim" or a custom value.
```
engine.editor.setEditMode('Crop');
```
```
getEditMode(): EditMode
```
Get the current edit mode of the editor. An edit mode defines what type of content can currently be edited by the user.
* Returns "Transform", "Crop", "Text", "Playback", "Trim" or a custom value.
```
engine.editor.getEditMode(); // 'Crop'
```
```
unstable_isInteractionHappening(): boolean
```
If an user interaction is happening, e.g., a resize edit with a drag handle or a touch gesture.
* Returns True if an interaction is happening.
```
engine.editor.unstable_isInteractionHappening();
```
##
Cursor
```
getCursorType(): 'Arrow' | 'Move' | 'MoveNotPermitted' | 'Resize' | 'Rotate' | 'Text'
```
Get the type of cursor that should be displayed by the application.
* Returns The cursor type.
```
engine.editor.getCursorType();
```
```
getCursorRotation(): number
```
Get the rotation with which to render the mouse cursor.
* Returns The angle in radians.
```
engine.editor.getCursorRotation();
```
```
getTextCursorPositionInScreenSpaceX(): number
```
Get the current text cursor's x position in screen space.
* Returns The text cursor's x position in screen space.
```
engine.editor.getTextCursorPositionInScreenSpaceX();
```
```
getTextCursorPositionInScreenSpaceY(): number
```
Get the current text cursor's y position in screen space.
* Returns The text cursor's y position in screen space.
```
engine.editor.getTextCursorPositionInScreenSpaceY();
```
Creating a Scene from Scratch - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/guides/create-scene-from-scratch/?platform=web&language=javascript
# Creating a Scene from Scratch
In this example, we will show you how to initialize the [CreativeEditor SDK](https://img.ly/products/creative-sdk) from scratch and add a star shape.
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-create-scene-from-scratch?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Create+Scene+From+Scratch&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-create-scene-from-scratch).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-create-scene-from-scratch?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Create+Scene+From+Scratch&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-create-scene-from-scratch)
We create an empty scene via `engine.scene.create()` which sets up the default scene block with a camera attached. Afterwards, the scene can be populated by creating additional blocks and appending them to the scene. See [Modifying Scenes](/docs/cesdk/engine/guides/blocks/) for more details.
```
let scene = await engine.scene.create();
```
We first add a page with `create(type: DesignBlockType): number` specifying a `"page"` and set a parent-child relationship between the scene and this page.
```
let page = engine.block.create('page');
engine.block.appendChild(scene, page);
```
To this page, we add a graphic block, again with `create(type: DesignBlockType): number`. To make it more interesting, we set a star shape and a color fill to this block to give it a visual representation. Like for the page, we set the parent-child relationship between the page and the newly added block. From then on, modifications to this block are relative to the page.
```
let block = engine.block.create('graphic');
engine.block.setShape(block, engine.block.createShape('star'));
engine.block.setFill(block, engine.block.createFill('color'));
engine.block.appendChild(page, block);
```
This example first appends a page child to the scene as would typically be done but it is not strictly necessary and any child block can be appended directly to a scene.
To later save your scene, see [Saving Scenes](/docs/cesdk/engine/guides/save-scene/).
How to Write Custom Panels - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/customization/api/customPanel/
CESDK/CE.SDK/Web Editor/Customization/API Reference
# How to Write Custom Panels
Learn how to add your own content in a custom panel
Similar to registering [custom components](/docs/cesdk/ui/customization/api/registerComponents/), the CE.SDK web editor allows you to render custom panels. Built-in UI elements ensure that your custom panel blends seamlessly with the editor's look and feel, while still enabling you to adapt the editor to your unique workflows.
```
registerPanel(panelId: string, renderFunction: ({ builder, engine, state }) => void)
```
Registers a panel whose content can be rendered with a panel builder, similar to how custom components are registered.
The builder's render function is called with three arguments: the builder, the engine, and the state. The builder object is used to define which base components (such as buttons) should be rendered. The engine is used to retrieve any state from the engine. The render function will be called again if any engine-related state changes occur due to engine calls or the local state was updated.
* `panelId`: The unique ID of the new registered panel.
* `renderFunction`: The render function of the panel.
##
When is a Panel Rendered?
It is important concept to understand when a panel re-renders after its initial rendering. The component assumes that all its state is stored in the `engine` or the local state. Whenever we detect a change that is relevant for this panel it will re-render.
###
Using the Engine
Inside the render function, any calls that retrieve values from the engine will be tracked. If a change is detected, the render function will be automatically re-called.
For example, in a panel, we could query for all selected blocks and decide whether to render a button based on the result. The engine detects the call to findAllSelected and knows that if the selection changes, it needs to re-render the panel. This behavior applies to all methods provided by the engine.
###
Using Local State
Besides the `engine`, the render function also receives a `state` argument to manage local state. This can be used to control input components or store state in general. When the state changes, the panel will be re-rendered as well.
The `state` argument is a function that is called with a unique ID for the state. Any subsequent call to the state within this panel will return the same state. The second optional argument is the default value for this state. If the state has not been set yet, it will return this value. Without this argument, you'll need to handle `undefined` values manually.
The return value of the state call is an object with `value` and `setValue` properties, which can be used to get and set the state. Since these property names match those used by input components, the object can be directly spread into the component options.
```
cesdk.ui.registerPanel('counter', ({ builder, state }) => {
const urlState = state('url', '');
const { value, setValue } = state('counter', 0);
builder.Section('counter', {
children: () => {
builder.TextInput('text-input-1', {
inputLabel: 'TextInput 1',
...urlState
});
builder.Button('submit-button', {
label: 'Submit',
onClick: () => {
const pressed = value + 1;
setValue(pressed);
console.log(
`Pressed ${pressed} times with the current URL ${urlState.value}`
);
}
});
}
});
});
```
##
Integrate the Panel into the Editor
After registering a component, it is not automatically opened or integrated in any other way. The CE.SDK editor is just aware that there is a panel with this id.
###
Opening a Panel
Once a panel is registered, it can be controlled using the [Panel API](/docs/cesdk/ui/customization/api/panel/), just like any other panel. For instance, you can open a custom panel with `cesdk.ui.openPanel(registeredPanelId)`. Other settings, such as position and floating, can also be adjusted accordingly.
In most cases, you will want to open it using a custom button, .e.g in a button inside the [Dock](/docs/cesdk/ui/customization/api/dock/) or [Inspector Bar](/docs/cesdk/ui/customization/api/inspectorBar/).
###
Setting the Title of a Custom Panel
The title of a panel is determined by a translation based on the panel's ID. For example, if the panel ID is `myCustomPanel`, the corresponding translation key would be `panel.myCustomPanel`.
```
cesdk.setTranslations({
en: {
'panel.myCustomPanel': 'My Custom Panel',
},
de: {
'panel.myCustomPanel': 'Mein eigenes Panel',
}
});
```
##
Using the Builder
The `builder` object passed to the render function provides a set of methods to create UI elements. Calling this method will add a builder component to the user interface. This includes buttons, dropdowns, text, etc.
##
Builder Components
The following builder components can be used inside a registered panel.
###
Button
A simple button to react on a user click.
Property
Description
Property
`label`
Description
The label inside the button. If it is a i18n key, it will be used for translation.
Property
`labelAlignment`
Description
How the label inside the button is aligned. Either `left` or `center`.
Property
`inputLabel`
Description
An optional label next to/above the button. If it is a i18n key, it will be used for translation.
Property
`inputLabelPosition`
Description
Input label position relative to the button - either `'top'` or `'left'`.
Property
`tooltip`
Description
A tooltip displayed upon hover. If it is a i18n key, it will be used for translation.
Property
`onClick`
Description
Executed when the button is clicked.
Property
`variant`
Description
The variant of the button. `regular` is the default variant, `plain` is a variant without any background or border.
Property
`color`
Description
The color of the button. `accent` is the accent color to stand out, `danger` is a red color.
Property
`icon`
Description
The icon of the button. See [Icon API](/docs/cesdk/ui/customization/api/icons/) for more information about how to add new icons.
Property
`size`
Description
The size of the button. Either `'normal'` or `'large'`.
Property
`isActive`
Description
A boolean to indicate that the button is active.
Property
`isSelected`
Description
A boolean to indicate that the button is selected.
Property
`isDisabled`
Description
A boolean to indicate that the button is disabled.
Property
`isLoading`
Description
A boolean to indicate that the button is in a loading state.
Property
`loadingProgress`
Description
A number between 0 and 1 to indicate the progress of a loading button.
Property
`suffix`
Description
An object with properties similar to those of a Button. When provided, it will render a button without a label on the right side of the component. If the object includes only an icon (with a tooltip), only the icon will be displayed. An empty object will render as an empty space, which can be useful for aligning multiple components.
###
ButtonGroup
Grouping of multiple buttons in a single segmented control.
Property
Description
Property
`inputLabel`
Description
An optional label next to/above the button group. If it is a i18n key, it will be used for translation.
Property
`inputLabelPosition`
Description
Input label position relative to the button group - either `'top'` or `'left'`.
Property
`children`
Description
A function executed to render grouped buttons. Only the `Button`, `Dropdown` and `Select` builder components are allowed to be rendered inside this function.
Property
`suffix`
Description
An object with properties similar to those of a Button. When provided, it will render a button without a label on the right side of the component. If the object includes only an icon (with a tooltip), only the icon will be displayed. An empty object will render as an empty space, which can be useful for aligning multiple components.
###
Checkbox
A labeled checkbox.
Property
Description
Property
`inputLabel`
Description
An optional label next to the checkbox. If it is a i18n key, it will be used for translation.
Property
`inputLabelPosition`
Description
Input label position relative to the checkbox - either `'left'` (default) or `'right'`.
Property
`icon`
Description
The icon of the checkbox. See [Icon API](/docs/cesdk/ui/customization/api/icons/) for more information about how to add new icons.
Property
`isDisabled`
Description
A boolean to indicate that the checkbox is disabled.
###
ColorInput
A big color swatch that opens a color picker when clicked.
Property
Description
Property
`inputLabel`
Description
An optional label next to the color input. If it is a i18n key, it will be used for translation.
Property
`inputLabelPosition`
Description
Input label position relative to the color input - either `'left'` (default) or `'top'`.
Property
`icon`
Description
The icon of the checkbox. See [Icon API](/docs/cesdk/ui/customization/api/icons/) for more information about how to add new icons.
Property
`isDisabled`
Description
A boolean to indicate that the color input is disabled.
Property
`value`
Description
The color value that the input is showing.
Property
`setValue`
Description
A callback that receives the new color value when the user picks one.
Property
`suffix`
Description
An object with properties similar to those of a Button. When provided, it will render a button without a label on the right side of the component. If the object includes only an icon (with a tooltip), only the icon will be displayed. An empty object will render as an empty space, which can be useful for aligning multiple components.
###
Dropdown
A button that opens a dropdown with additional content when the user clicks on it.
Property
Description
Property
`label`
Description
The label inside the button. If it is a i18n key, it will be used for translation.
Property
`tooltip`
Description
A tooltip displayed upon hover. If it is a i18n key, it will be used for translation.
Property
`variant`
Description
The variant of the button. `regular` is the default variant, `plain` is a variant without any background or border.
Property
`color`
Description
The color of the button. `accent` is the accent color to stand out, `danger` is a red color.
Property
`icon`
Description
The icon of the button. See [Icon API](/docs/cesdk/ui/customization/api/icons/) for more information about how to add new icons.
Property
`isActive`
Description
A boolean to indicate that the button is active.
Property
`isSelected`
Description
A boolean to indicate that the button is selected.
Property
`isDisabled`
Description
A boolean to indicate that the button is disabled.
Property
`isLoading`
Description
A boolean to indicate that the button is in a loading state.
Property
`loadingProgress`
Description
A number between 0 and 1 to indicate the progress of a loading button.
Property
`children`
Description
A function executed to render the content of the dropdown. Every builder component called in this children function, will be rendered in the dropdown.
Property
`suffix`
Description
An object with properties similar to those of a Button. When provided, it will render a button without a label on the right side of the component. If the object includes only an icon (with a tooltip), only the icon will be displayed. An empty object will render as an empty space, which can be useful for aligning multiple components.
###
Heading
Renders its content as heading to the panel.
Property
Description
Property
`content`
Description
The content of the header as a string.
###
Library
A complete asset library with a search option.
Property
Description
Property
`entries`
Description
An array of Asset Library entry IDs that determines which assets are shown in which way. See [Asset Library Entry](/docs/cesdk/ui/customization/api/assetLibraryEntry/) for reference.
Property
`onSelect`
Description
A callback receiving the selected asset when the user picks one.
Property
`searchable`
Description
When set, makes the Library searchable.
###
MediaPreview
A large preview area showing an image or color. Optionally contains a button in the bottom right corner, offering contextual action.
Property
Description
Property
`size`
Description
Size of the preview, either `'small'` or `'medium'` (default).
Property
`preview`
Description
Determines the kind of preview. Can be either an image, or a color. Use an object with the following shape: `{ type: 'image', uri: string }` or `{ type: 'color', color: string }`
Property
`action`
Description
Button option object that is passed along to the overlayed button. See [Button](/docs/cesdk/ui/customization/api/customPanel/#button) for reference.
###
NumberInput
A number input field.
Property
Description
Property
`inputLabel`
Description
An optional label next to/above the number input. If it is a i18n key, it will be used for translation.
Property
`inputLabelPosition`
Description
Input label position relative to the input - either `'top'` or `'left'`.
Property
`value`
Description
The number contained in the input.
Property
`setValue`
Description
A callback that receives the new number when it is changed by the user.
Property
`min`
Description
Minimum value of the input.
Property
`max`
Description
Maximum value of the input.
Property
`step`
Description
Interval of changes when using the arrow keys to change the number.
Property
`suffix`
Description
An object with properties similar to those of a Button. When provided, it will render a button without a label on the right side of the component. If the object includes only an icon (with a tooltip), only the icon will be displayed. An empty object will render as an empty space, which can be useful for aligning multiple components.
###
Select
A dropdown to select one of multiple choices.
Property
Description
Property
`inputLabel`
Description
An optional label next to/above the control. If it is a i18n key, it will be used for translation.
Property
`inputLabelPosition`
Description
Input label position relative to the control - either `'top'` or `'left'`.
Property
`tooltip`
Description
A tooltip displayed upon hover. If it is a i18n key, it will be used for translation.
Property
`value`
Description
The currently selected value.
Property
`setValue`
Description
A callback that receives the new selection when it is changed by the user.
Property
`values`
Description
The set of values from which the user can select.
Property
`isDisabled`
Description
A boolean to indicate that the control is disabled.
Property
`isLoading`
Description
A boolean to indicate that the control is in a loading state.
Property
`loadingProgress`
Description
A number between 0 and 1 to indicate the progress of loading.
Property
`suffix`
Description
An object with properties similar to those of a Button. When provided, it will render a button without a label on the right side of the component. If the object includes only an icon (with a tooltip), only the icon will be displayed. An empty object will render as an empty space, which can be useful for aligning multiple components.
###
Separator
Adds a separator (`` element) in the panel to help the visual separation of entries. This builder component has no properties.
###
Slider
A slider for intuitively adjusting a number.
Property
Description
Property
`inputLabel`
Description
An optional label next to/above the text field. If it is a i18n key, it will be used for translation.
Property
`inputLabelPosition`
Description
Input label position relative to the input - either `'top'` or `'left'`.
Property
`value`
Description
The text contained in the field.
Property
`setValue`
Description
A callback that receives the new text when it is changed by the user.
Property
`min`
Description
Minimum value of the slider.
Property
`max`
Description
Maximum value of the slider.
Property
`step`
Description
Interval of the slider movement.
Property
`centered`
Description
Adds a snapping point in the middle of the slider.
Property
`suffix`
Description
An object with properties similar to those of a Button. When provided, it will render a button without a label on the right side of the component. If the object includes only an icon (with a tooltip), only the icon will be displayed. An empty object will render as an empty space, which can be useful for aligning multiple components.
###
Text
A piece of non-interactive text.
Property
Description
Property
`content`
Description
The content of the text as a string.
###
TextArea
A large text field accepting user input.
Property
Description
Property
`inputLabel`
Description
An optional label above the text field. If it is a i18n key, it will be used for translation.
Property
`value`
Description
The text contained in the field.
Property
`setValue`
Description
A callback that receives the new text when it is changed by the user.
Property
`isDisabled`
Description
A boolean to indicate that the text area is disabled.
###
TextInput
A small text field accepting user input.
Property
Description
Property
`inputLabel`
Description
An optional label next to/above the text field. If it is a i18n key, it will be used for translation.
Property
`inputLabelPosition`
Description
Input label position relative to the input - either `'top'` or `'left'`.
Property
`value`
Description
The text contained in the field.
Property
`setValue`
Description
A callback that receives the new text when it is changed by the user.
Property
`isDisabled`
Description
A boolean to indicate that the text field is disabled.
Property
`suffix`
Description
An object with properties similar to those of a Button. When provided, it will render a button without a label on the right side of the component. If the object includes only an icon (with a tooltip), only the icon will be displayed. An empty object will render as an empty space, which can be useful for aligning multiple components.
[
Previous
Custom Components
](/docs/cesdk/ui/customization/api/registerComponents/)[
Next
Feature
](/docs/cesdk/ui/customization/api/features/)
Controlling the UI with the Feature API - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/customization/api/features/
CESDK/CE.SDK/Web Editor/Customization/API Reference
# Controlling the UI with the Feature API
Use the Feature API to control what the user can do
##
Enable Feature
The following API allows to enable a custom or built-in feature (see the list of [built-in features](/docs/cesdk/ui/customization/api/features/#built-in-features) below):
```
enable(featureId: FeatureId | FeatureId[], predicate: FeaturePredicate)
```
The `predicate` is either a boolean that forces the features to be enabled or not, or a function that takes a context and returns a boolean value. (The type `FeaturePredicate` is `boolean | ((context: EnableFeatureContext) => boolean)`, where `EnableFeatureContext` is `{engine: CreativeEngine, isPreviousEnable: () => boolean}`.)
Providing a function has the added benefit of receiving the return value of any previous predicates. This is useful for overwriting the default behavior under specific circumstances, or for chaining more complex predicates.
###
Example: Chaining Predicates
```
// Enable the feature by default
cesdk.feature.enable('my.feature', true);
// Disable the feature after 10 pm
cesdk.feature.enable(
'my.feature',
({isPreviousEnable}) =>
(new Date().getHours() >= 22 ? false : isPreviousEnable())
);
```
Tip: `FeatureId` can be an arbitrary string, so you can use this mechanism to toggle your own custom features, as well.
###
Example: Overwriting Defaults
Let's say you introduced a new kind of block that represents an Avatar. Regardless of scopes or the current mode of the editor, you want to hide the duplicate & delete button in the canvas menu for this kind of block. You can achieve this by adding new predicates to change the default feature behavior:
```
cesdk.feature.enable(
'ly.img.delete',
({engine, isPreviousEnable}) => {
const selectedBlock = engine.block.findAllSelected()[0];
const kind = engine.block.getKind( selectedBlock );
if (kind === 'avatar') {
return false;
} else {
return isPreviousEnable();
}
}
);
cesdk.feature.enable(
'ly.img.duplicate',
({engine, isPreviousEnable}) => {
const selectedBlock = engine.block.findAllSelected()[0];
const kind = engine.block.getKind( selectedBlock );
if (kind === 'avatar') {
return false;
} else {
return isPreviousEnable();
}
}
);
```
##
Check Feature
The following API allows to query if the feature is currently enabled:
```
isEnabled(featureId: FeatureId, context: FeatureContext)
```
The type `FeatureContext` is `{engine: CreativeEngine}`, meaning that you will need to supply the active engine instance when checking a feature, for Example:
```
if (!cesdk.feature.isEnabled('ly.img.navigate.close', { engine })) {
return null;
}
```
##
Built-In Features
The following features are built-in to CE.SDK:
Feature ID
Description
Feature ID
`ly.img.navigate.back`
Description
Controls visibility of the "Back" button in the Navigation Bar.
Defaults to the value of the configuration option `ui.elements.navigation.action.back`, or `true` if not set.
Feature ID
`ly.img.navigate.close`
Description
Controls visibility of the "Close" button in the Navigation Bar.
Defaults to the value of the configuration option `ui.elements.navigation.action.close`, or `true` if not set.
Feature ID
`ly.img.delete`
Description
Controls the ability to delete a block. Changes visibility of the "Delete" button in the Canvas Menu, as well as the ability to delete by pressing the `delete` key. Will return `false` when the operation would delete all pages of the document. Will return `false` when target block is a page and configuration option `ui.elements.blocks['//ly.img.ubq/page'].manage` is `false`, or during `'Video'` scene mode.
Feature ID
`ly.img.duplicate`
Description
Controls visibility of the "Duplicate" button in the Canvas Menu. Does currently **not** influence the ability to copy/paste using keyboard shortcuts. Will return `false` when target block is a page and configuration option `ui.elements.blocks['//ly.img.ubq/page'].manage` is `false`, or during `'Video'` scene mode, or when scene layout is set to `'Free'` or `'DepthStack'`.
Feature ID
`ly.img.placeholder`
Description
Controls visibility of the "Placeholder" button in the Canvas Menu. Will return `true` for blocks of type `'//ly.img.ubq/text'`, `'//ly.img.ubq/group'`, `'//ly.img.ubq/page'`, `'//ly.img.ubq/audio'`, or `'//ly.img.ubq/graphic'`.
Feature ID
`ly.img.preview`
Description
Controls existence of the "Preview" button in the Navigation Bar. Returns `true` when `cesdk.engine.editor.getRole()` returns `Creator`, e.g. when editing in the Creator role.
Feature ID
`ly.img.page.move`
Description
Controls the ability to move pages, by showing the "Move Up/Down/Left/Right" buttons in the Canvas Menu. Returns `false` during `'Video'` scene mode, or when scene layout is set to `'Free'` or `'DepthStack'`. Note that the "Move Up/Left" components will not show up when the target page is already the first page of the document, and "Move Down/Right" will not show up when the target page is already the last page of the document.
Feature ID
`ly.img.page.add`
Description
Controls the ability to add pages, by showing the "Add Page" button in the Canvas Bar. Returns `false` during `'Video'` scene mode, or when scene layout is set to `'Free'` or `'DepthStack'`.
Feature ID
`ly.img.group`
Description
Controls features for creating and dissolving groups, currently: The existence of "Group" and "Ungroup" buttons in the Inspector Bar. Returns `false` during `'Video'` scene mode.
Feature ID
`ly.img.replace`
Description
Controls presence of the "Replace" button in the Canvas Menu, and in the Fill Panel for image and video fills. Returns `false` by default for stickers.
Feature ID
`ly.img.text.edit`
Description
Controls presence of the "Edit" button in the Canvas Menu. Only returns `true` for text blocks by default.
Feature ID
`ly.img.text.typeface`
Description
Controls presence of the Typeface dropdown, and can disable the corresponding dropdown in the Advanced UI Inspector Panel. Only returns `true` for text blocks by default.
Feature ID
`ly.img.text.fontSize`
Description
Controls presence of the Font Size input, and can disable the corresponding input in the Advanced UI Inspector Panel. Only returns `true` for text blocks by default.
Feature ID
`ly.img.text.fontStyle`
Description
Controls presence of the Font Style controls (Bold toggle, Italic toggle), in the Canvas Menu, and can disable the corresponding inputs in the Advanced UI Inspector Panel. Only returns `true` for text blocks by default.
Feature ID
`ly.img.text.alignment`
Description
Controls presence of the Text Horizontal Alignment dropdown, and can disable the corresponding controls in the Advanced UI Inspector Panel. Only returns `true` for text blocks by default.
Feature ID
`ly.img.text.advanced`
Description
Controls the presence of the Advanced text controls in the Editor. Only returns `true` for text blocks by default.
Feature ID
`ly.img.adjustment`
Description
Controls visibility of the "Adjustments" button, and can disable the corresponding button in the Advanced UI Inspector Panel. Returns `false` for stickers by default.
Feature ID
`ly.img.filter`
Description
Controls visibility of the "Filter" button, and can disable the corresponding button in the Advanced UI Inspector Panel. Returns `false` for stickers by default.
Feature ID
`ly.img.effect`
Description
Controls visibility of the "Effect" button, and can disable the corresponding button in the Advanced UI Inspector Panel. Returns `false` for stickers by default.
Feature ID
`ly.img.blur`
Description
Controls visibility of the "Blur" button, and can disable the corresponding button in the Advanced UI Inspector Panel. Returns `false` for stickers by default.
Feature ID
`ly.img.shadow`
Description
Controls visibility of the Shadow button, and can disable the corresponding control in the Advanced UI Inspector Panel. Returns `false` for pages by default.
Feature ID
`ly.img.cutout`
Description
Controls visibility of the Cutout controls (Cutout Type, Cutout Offset, Cutout Smoothing), and can disable the corresponding controls in the Advanced UI Inspector Panel. Only returns `true` for cutouts by default.
Feature ID
`ly.img.fill`
Description
Controls presence of the Fill button (opening the Fill Panel), and can disable the corresponding button in the Advanced UI Inspector Panel. Returns `false` for stickers by default.
Feature ID
`ly.img.shape.options`
Description
Controls presence of the Shape Options dropdown in the Default UI Inspector Bar, and can disable the corresponding button in the Advanced UI Inspector Panel. Returns `true` by default, but note that the component itself checks for the target block type and will only render for shape blocks.
Feature ID
`ly.img.combine`
Description
Controls presence of the Combine dropdown, and can disable the corresponding button in the Advanced UI Inspector Panel. Returns `true` by default, but note that the component itself checks for the target block type and will only render if the selection contains only shape blocks and text, or only cutouts.
Feature ID
`ly.img.trim`
Description
Controls presence of the Trim button, and can disable the corresponding button in the Fill Panel. Only returns `true` when scene mode is `'Video'`.
Feature ID
`ly.img.crop`
Description
Controls presence of the Trim button, and can disable the corresponding button in the Fill Panel. Returns `false` for stickers by default.
Feature ID
`ly.img.volume`
Description
Controls presence of the Volume control, and can disable the corresponding button in the Fill Panel. Only returns `true` when scene mode is `'Video'`.
Feature ID
`ly.img.stroke`
Description
Controls presence of the Stroke controls (Color, Width, Stroke), and can disable the corresponding controls in the Advanced UI Inspector Panel. Returns `false` for stickers by default.
Feature ID
`ly.img.position`
Description
Controls presence of the Position dropdown, and can disable the corresponding controls in the Advanced UI Inspector Panel. Returns `false` if target block is a page.
Feature ID
`ly.img.options`
Description
Controls presence of the Options button (`...` button) in the Default UI Inspector Bar. Returns `true` by default.
Feature ID
`ly.img.animations`
Description
Controls presence of the Animations button. Returns `true` by default for Graphic and Text blocks in video mode.
[
Previous
Custom Panels
](/docs/cesdk/ui/customization/api/customPanel/)[
Next
Asset Library Entry
](/docs/cesdk/ui/customization/api/assetLibraryEntry/)
Modify Properties - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/api/block-properties/?platform=web&language=javascript
# Modify Properties
In this example, we will show you how to use the [CreativeEditor SDK](https://img.ly/products/creative-sdk)'s CreativeEngine to modify block properties through the `block` API.
##
Setup
This example uses the headless CreativeEngine. See the [Setup](/docs/cesdk/engine/quickstart/) article for a detailed guide. To get started right away, you can also access the `block` API within a running CE.SDK instance via `cesdk.engine.block`. Check out the [APIs Overview](../) to see that illustrated in more detail.
##
UUID
A universally unique identifier (UUID) is assigned to each block upon creation and can be queried. This is stable across save & load and may be used to reference blocks.
```
getUUID(id: DesignBlockId): string
```
Get a block's UUID.
* `id`: The block to query.
```
const uuid = engine.block.getUUID(block);
```
##
Reflection
For every block, you can get a list of all its properties by calling `findAllProperties(id: number): string[]`. Properties specific to a block are prefixed with the block's type followed by a forward slash. There are also common properties shared between blocks which are prefixed by their respective type. A list of all properties can be found in the [Blocks Overview](/docs/cesdk/engine/api/block/).
```
const propertyNamesStar = engine.block.findAllProperties(starShape); // Array [ "shape/star/innerDiameter", "shape/star/points", "opacity/value", ... ]
const propertyNamesImage = engine.block.findAllProperties(imageFill); // Array [ "fill/image/imageFileURI", "fill/image/previewFileURI", "fill/image/externalReference", ... ]
const propertyNamesText = engine.block.findAllProperties(text); // Array [ "text/text", "text/fontFileUri", "text/externalReference", "text/fontSize", "text/horizontalAlignment", ... ]
```
```
findAllProperties(id: DesignBlockId): string[]
```
Get all available properties of a block.
* `id`: The block whose properties should be queried.
* Returns A list of the property names.
```
const propertyNamesStar = engine.block.findAllProperties(starShape); // Array [ "shape/star/innerDiameter", "shape/star/points", "opacity/value", ... ]
const propertyNamesImage = engine.block.findAllProperties(imageFill); // Array [ "fill/image/imageFileURI", "fill/image/previewFileURI", "fill/image/externalReference", ... ]
const propertyNamesText = engine.block.findAllProperties(text); // Array [ "text/text", "text/fontFileUri", "text/externalReference", "text/fontSize", "text/horizontalAlignment", ... ]
```
Given a property, you can query its type as an enum using `getPropertyType(property: string): 'Bool' | 'Int' | 'Float' | 'String' | 'Color' | 'Enum' | 'Struct'`.
```
const pointsType = engine.block.getPropertyType('shape/star/points'); // "Int"
```
```
getPropertyType(property: string): PropertyType
```
Get the type of a property given its name.
* `property`: The name of the property whose type should be queried.
* Returns The property type.
```
const pointsType = engine.block.getPropertyType('shape/star/points'); // "Int"
```
The property type `'Enum'` is a special type. Properties of this type only accept a set of certain strings. To get a list of possible values for an enum property call `getEnumValues(enumProperty: string): string[]`.
```
const alignmentType = engine.block.getPropertyType('text/horizontalAlignment'); // "Enum"
```
```
getEnumValues(enumProperty: string): T[]
```
Get all the possible values of an enum given an enum property.
* `enumProperty`: The name of the property whose enum values should be queried.
* Returns A list of the enum value names as string.
```
const alignmentType = engine.block.getPropertyType('text/horizontalAlignment'); // "Enum"
```
Some properties can only be written to or only be read. To find out what is possible with a property, you can use the `isPropertyReadable` and `isPropertyWritable` methods.
```
const readable = engine.block.isPropertyReadable('shape/star/points');
const writable = engine.block.isPropertyWritable('shape/star/points');
```
```
isPropertyReadable(property: string): boolean
```
Check if a property with a given name is readable
* `property`: The name of the property whose type should be queried.
* Returns Whether the property is readable or not. Will return false for unknown properties
```
const readable = engine.block.isPropertyReadable('shape/star/points');
```
```
isPropertyWritable(property: string): boolean
```
Check if a property with a given name is writable
* `property`: The name of the property whose type should be queried.
* Returns Whether the property is writable or not. Will return false for unknown properties
```
const writable = engine.block.isPropertyWritable('shape/star/points');
```
##
Generic Properties
There are dedicated setter and getter functions for each property type. You have to provide a block and the property path. Use `findAllProperties` to get a list of all the available properties a block has.
Please make sure you call the setter and getter function matching the type of the property you want to set or query or else you will get an error. Use \`getPropertyType\` to figure out the pair of functions you need to use.
```
findAllProperties(id: DesignBlockId): string[]
```
Get all available properties of a block.
* `id`: The block whose properties should be queried.
* Returns A list of the property names.
```
const propertyNamesStar = engine.block.findAllProperties(starShape); // Array [ "shape/star/innerDiameter", "shape/star/points", "opacity/value", ... ]
const propertyNamesImage = engine.block.findAllProperties(imageFill); // Array [ "fill/image/imageFileURI", "fill/image/previewFileURI", "fill/image/externalReference", ... ]
const propertyNamesText = engine.block.findAllProperties(text); // Array [ "text/text", "text/fontFileUri", "text/externalReference", "text/fontSize", "text/horizontalAlignment", ... ]
```
```
setBool(id: DesignBlockId, property: string, value: boolean): void
```
Set a bool property of the given design block to the given value.
* `id`: The block whose property should be set.
* `property`: The name of the property to set.
* `value`: The value to set.
```
engine.block.setBool(scene, 'scene/aspectRatioLock', false);
```
```
getBool(id: DesignBlockId, property: string): boolean
```
Get the value of a bool property of the given design block.
* `id`: The block whose property should be queried.
* `property`: The name of the property to query.
* Returns The value of the property.
```
engine.block.getBool(scene, 'scene/aspectRatioLock');
```
```
setInt(id: DesignBlockId, property: string, value: number): void
```
Set an int property of the given design block to the given value.
* `id`: The block whose property should be set.
* `property`: The name of the property to set.
* `value`: The value to set.
```
engine.block.setInt(starShape, 'shape/star/points', points + 2);
```
```
getInt(id: DesignBlockId, property: string): number
```
Get the value of an int property of the given design block.
* `id`: The block whose property should be queried.
* `property`: The name of the property to query.
* Returns The value of the property.
```
const points = engine.block.getInt(starShape, 'shape/star/points');
```
```
setFloat(id: DesignBlockId, property: string, value: number): void
```
Set a float property of the given design block to the given value.
* `id`: The block whose property should be set.
* `property`: The name of the property to set.
* `value`: The value to set.
```
engine.block.setFloat(starShape, 'shape/star/innerDiameter', 0.75);
```
```
getFloat(id: DesignBlockId, property: string): number
```
Get the value of a float property of the given design block.
* `id`: The block whose property should be queried.
* `property`: The name of the property to query.
* Returns The value of the property.
```
engine.block.getFloat(starShape, 'shape/star/innerDiameter');
```
```
setDouble(id: DesignBlockId, property: string, value: number): void
```
Set a double property of the given design block to the given value.
* `id`: The block whose property should be set.
* `property`: The name of the property to set.
* `value`: The value to set.
```
const audio = engine.block.create('audio');
engine.block.appendChild(scene, audio);
engine.block.setDouble(audio, 'playback/duration', 1.0);
```
```
getDouble(id: DesignBlockId, property: string): number
```
Get the value of a double property of the given design block.
* `id`: The block whose property should be queried.
* `property`: The name of the property to query.
* Returns The value of the property.
```
engine.block.getDouble(audio, 'playback/duration');
```
```
setString(id: DesignBlockId, property: string, value: string): void
```
Set a string property of the given design block to the given value.
* `id`: The block whose property should be set.
* `property`: The name of the property to set.
* `value`: The value to set.
```
engine.block.setString(text, 'text/text', '*o*');
engine.block.setString(
imageFill,
'fill/image/imageFileURI',
'https://img.ly/static/ubq_samples/sample_4.jpg'
);
```
```
getString(id: DesignBlockId, property: string): string
```
Get the value of a string property of the given design block.
* `id`: The block whose property should be queried.
* `property`: The name of the property to query.
* Returns The value of the property.
```
engine.block.getString(text, 'text/text');
engine.block.getString(imageFill, 'fill/image/imageFileURI');
```
```
setColor(id: DesignBlockId, property: string, value: Color): void
```
Set a color property of the given design block to the given value.
* `id`: The block whose property should be set.
* `property`: The name of the property to set.
* `value`: The value to set.
```
engine.block.setColor(colorFill, 'fill/color/value', {
```
```
getColor(id: DesignBlockId, property: string): Color
```
Get the value of a color property of the given design block.
* `id`: The block whose property should be queried.
* `property`: The name of the property to query.
* Returns The value of the property.
```
engine.block.getColor(colorFill, 'fill/color/value');
```
```
setEnum(id: DesignBlockId, property: string, value: T): void
```
Set an enum property of the given design block to the given value.
* `id`: The block whose property should be set.
* `property`: The name of the property to set.
* `value`: The enum value as string.
```
engine.block.setEnum(text, 'text/horizontalAlignment', 'Center');
engine.block.setEnum(text, 'text/verticalAlignment', 'Center');
```
```
getEnum(id: DesignBlockId, property: string): T
```
Get the value of an enum property of the given design block.
* `id`: The block whose property should be queried.
* `property`: The name of the property to query.
* Returns The value as string.
```
engine.block.getEnum(text, 'text/horizontalAlignment');
engine.block.getEnum(text, 'text/verticalAlignment');
```
```
type HorizontalTextAlignment = 'Left' | 'Right' | 'Center'
```
The horizontal text alignment options.
```
const alignmentType = engine.block.getPropertyType('text/horizontalAlignment'); // "Enum"
```
```
type VerticalTextAlignment = 'Top' | 'Bottom' | 'Center'
```
The vertical text alignment options.
```
engine.block.setEnum(text, 'text/verticalAlignment', 'Center');
```
```
setGradientColorStops(id: DesignBlockId, property: string, colors: GradientColorStop[]): void
```
Set a gradient color stops property of the given design block.
* `id`: The block whose property should be set.
* `property`: The name of the property to set.
```
engine.block.setGradientColorStops(gradientFill, 'fill/gradient/colors', [
{ color: { r: 1.0, g: 0.8, b: 0.2, a: 1.0 }, stop: 0 },
{ color: { r: 0.3, g: 0.4, b: 0.7, a: 1.0 }, stop: 1 }
]);
```
```
getGradientColorStops(id: DesignBlockId, property: string): GradientColorStop[]
```
Get the gradient color stops property of the given design block.
* `id`: The block whose property should be queried.
* `property`: The name of the property to query.
* Returns The gradient colors.
```
engine.block.getGradientColorStops(gradientFill, 'fill/gradient/colors');
```
```
setSourceSet(id: DesignBlockId, property: string, sourceSet: Source[]): void
```
Set the property of the given block.
* `id`: The block whose property should be set.
* `property`: The name of the property to set.
* `sourceSet`: The block's new source set.
```
const imageFill = engine.block.createFill('image');
engine.block.setSourceSet(imageFill, 'fill/image/sourceSet', [
{
uri: 'http://img.ly/my-image.png',
width: 800,
height: 600
}
]);
```
```
getSourceSet(id: DesignBlockId, property: string): Source[]
```
Get the source set value of the given property.
* `id`: The block that should be queried.
* `property`: The name of the property to query.
* Returns The block's source set.
```
const sourceSet = engine.block.getSourceSet(imageFill, 'fill/image/sourceSet');
```
```
addImageFileURIToSourceSet(id: DesignBlockId, property: string, uri: string): Promise
```
Add a source to the `sourceSet` property of the given block. If there already exists in source set an image with the same width, that existing image will be replaced.
* `id`: The block to update.
* `property`: The name of the property to modify.
* `uri`: The source to add to the source set.
```
await engine.block.addImageFileURIToSourceSet(imageFill, 'fill/image/sourceSet', 'https://img.ly/static/ubq_samples/sample_1.jpg');
```
```
addVideoFileURIToSourceSet(id: DesignBlockId, property: string, uri: string): Promise
```
Add a video file URI to the `sourceSet` property of the given block. If there already exists in source set an video with the same width, that existing video will be replaced.
* `id`: The block to update.
* `property`: The name of the property to modify.
* `uri`: The source to add to the source set.
```
const videoFill = engine.block.createFill('video');
await engine.block.addVideoFileURIToSourceSet(videoFill, 'fill/video/sourceSet', 'https://img.ly/static/example-assets/sourceset/1x.mp4');
```
Adding Icons - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/customization/api/icons/#built-in-icons
CESDK/CE.SDK/Web Editor/Customization/API Reference
# Adding Icons
Explore how to add new icons in the editor.
Using our API, you can register your own icon sets for usage within the CE.SDK editor. The API is as follows:
##
Add new Icon Set
```
cesdk.ui.addIconSet(id: string, svgSprite: string)
```
The icon set is a string containing a SVG sprite with symbols. The id of each symbol is used to reference the icon in the editor. These ids need to start with a `@` to be recognized in the editor.
Please Note: The SVG sprite will be injected into the (shadow) DOM without any sanitization. Make sure to only use trusted sources to prevent e.g. XSS attacks. If you are unsure about the source of the sprite, consider using libraries like DOMPurify to sanitize the SVG string before adding it.
##
Examples
###
Register an Icon Set
Registering an SVG string with a single symbol might look like this:
```
cesdk.ui.addIconSet(
'@imgly/custom',
`
`
);
```
###
Replace a Dock Icon
You could use your custom icon set to replace the "Image" icon of the default Dock:
```
cesdk.ui.setDockOrder(
cesdk.ui.getDockOrder().map((entry) => {
if (entry.key === 'ly.img.image')
return {
...entry,
icon: '@some/icon/ZoomIn' // Note the ID referencing the SVG symbol
};
else return entry;
})
);
```
###
Use within a custom Component
Using your new symbol in a [custom component](/docs/cesdk/ui/customization/api/registerComponents/) is then done by referencing the symbol ID directly:
```
cesdk.ui.registerComponent('CustomIcon', ({ builder: { Button } }) => {
Button('customIcon', {
label: 'Custom Icon',
icon: '@some/icon/ZoomIn', // Note the ID referencing the SVG symbol
onClick: () => {
console.log('Custom Icon clicked');
}
});
});
```
##
Built-In Icons
These built-in icons can be referenced by their name string directly:
###
Set 'Essentials'
Name
Icon
Name
`@imgly/Adjustments`
Icon

Name
`@imgly/Animation`
Icon

Name
`@imgly/Appearance`
Icon

Name
`@imgly/Apps`
Icon

Name
`@imgly/ArrowDown`
Icon

Name
`@imgly/ArrowLeft`
Icon

Name
`@imgly/ArrowRight`
Icon

Name
`@imgly/ArrowUp`
Icon

Name
`@imgly/ArrowsDirectionHorizontal`
Icon

Name
`@imgly/ArrowsDirectionVertical`
Icon

Name
`@imgly/AsClip`
Icon

Name
`@imgly/AsOverlay`
Icon

Name
`@imgly/Audio`
Icon

Name
`@imgly/AudioAdd`
Icon

Name
`@imgly/Backward`
Icon

Name
`@imgly/Blendmode`
Icon

Name
`@imgly/Blur`
Icon

Name
`@imgly/BooleanExclude`
Icon

Name
`@imgly/BooleanIntersect`
Icon

Name
`@imgly/BooleanSubstract`
Icon

Name
`@imgly/BooleanUnion`
Icon

Name
`@imgly/CaseAsTyped`
Icon

Name
`@imgly/CaseLowercase`
Icon

Name
`@imgly/CaseSmallCaps`
Icon

Name
`@imgly/CaseTitleCase`
Icon

Name
`@imgly/CaseUppercase`
Icon

Name
`@imgly/CheckboxCheckmark`
Icon

Name
`@imgly/CheckboxMixed`
Icon

Name
`@imgly/Checkmark`
Icon

Name
`@imgly/ChevronDown`
Icon

Name
`@imgly/ChevronLeft`
Icon

Name
`@imgly/ChevronRight`
Icon

Name
`@imgly/ChevronUp`
Icon

Name
`@imgly/Collage`
Icon

Name
`@imgly/ColorFill`
Icon

Name
`@imgly/ColorGradientAngular`
Icon

Name
`@imgly/ColorGradientLinear`
Icon

Name
`@imgly/ColorGradientRadial`
Icon

Name
`@imgly/ColorOpacity`
Icon

Name
`@imgly/ColorSolid`
Icon

Name
`@imgly/ConnectionLostSlash`
Icon

Name
`@imgly/Copy`
Icon

Name
`@imgly/CornerJoinBevel`
Icon

Name
`@imgly/CornerJoinMiter`
Icon

Name
`@imgly/CornerJoinRound`
Icon

Name
`@imgly/Crop`
Icon

Name
`@imgly/CropCoverMode`
Icon

Name
`@imgly/CropCropMode`
Icon

Name
`@imgly/CropFitMode`
Icon

Name
`@imgly/CropFreefromMode`
Icon

Name
`@imgly/Cross`
Icon

Name
`@imgly/CrossRoundSolid`
Icon

Name
`@imgly/CustomLibrary`
Icon

Name
`@imgly/Download`
Icon

Name
`@imgly/DropShadow`
Icon

Name
`@imgly/Duplicate`
Icon

Name
`@imgly/Edit`
Icon

Name
`@imgly/Effects`
Icon

Name
`@imgly/ExternalLink`
Icon

Name
`@imgly/EyeClosed`
Icon

Name
`@imgly/EyeOpen`
Icon

Name
`@imgly/Filter`
Icon

Name
`@imgly/FlipHorizontal`
Icon

Name
`@imgly/FlipVertical`
Icon

Name
`@imgly/FontAutoSizing`
Icon

Name
`@imgly/FontSize`
Icon

Name
`@imgly/Forward`
Icon

Name
`@imgly/FullscreenEnter`
Icon

Name
`@imgly/FullscreenLeave`
Icon

Name
`@imgly/Group`
Icon

Name
`@imgly/GroupEnter`
Icon

Name
`@imgly/GroupExit`
Icon

Name
`@imgly/Home`
Icon

Name
`@imgly/Image`
Icon

Name
`@imgly/Info`
Icon

Name
`@imgly/LayerBringForward`
Icon

Name
`@imgly/LayerBringForwardArrow`
Icon

Name
`@imgly/LayerBringToFront`
Icon

Name
`@imgly/LayerBringToFrontArrow`
Icon

Name
`@imgly/LayerSendBackward`
Icon

Name
`@imgly/LayerSendBackwardArrow`
Icon

Name
`@imgly/LayerSendToBack`
Icon

Name
`@imgly/LayerSendToBackArrow`
Icon

Name
`@imgly/LayoutHorizontal`
Icon

Name
`@imgly/LayoutVertical`
Icon

Name
`@imgly/Library`
Icon

Name
`@imgly/LineHeight`
Icon

Name
`@imgly/LinkClosed`
Icon

Name
`@imgly/LinkOpen`
Icon

Name
`@imgly/LoadingSpinner`
Icon

Name
`@imgly/LockClosed`
Icon

Name
`@imgly/LockOpen`
Icon

Name
`@imgly/Minus`
Icon

Name
`@imgly/MoreOptionsHorizontal`
Icon

Name
`@imgly/MoreOptionsVertical`
Icon

Name
`@imgly/Move`
Icon

Name
`@imgly/Next`
Icon

Name
`@imgly/None`
Icon

Name
`@imgly/ObjectAlignBottom`
Icon

Name
`@imgly/ObjectAlignDistributedHorizontal`
Icon

Name
`@imgly/ObjectAlignDistributedVertical`
Icon

Name
`@imgly/ObjectAlignHorizontalCenter`
Icon

Name
`@imgly/ObjectAlignLeft`
Icon

Name
`@imgly/ObjectAlignRight`
Icon

Name
`@imgly/ObjectAlignTop`
Icon

Name
`@imgly/ObjectAlignVerticalCenter`
Icon

Name
`@imgly/OrientationToggleLandscape`
Icon

Name
`@imgly/OrientationTogglePortrait`
Icon

Name
`@imgly/PageResize`
Icon

Name
`@imgly/Paste`
Icon

Name
`@imgly/Pause`
Icon

Name
`@imgly/PlaceholderConnected`
Icon

Name
`@imgly/PlaceholderStripes`
Icon

Name
`@imgly/Play`
Icon

Name
`@imgly/Plus`
Icon

Name
`@imgly/Position`
Icon

Name
`@imgly/Previous`
Icon

Name
`@imgly/Redo`
Icon

Name
`@imgly/Rename`
Icon

Name
`@imgly/Reorder`
Icon

Name
`@imgly/Repeat`
Icon

Name
`@imgly/RepeatOff`
Icon

Name
`@imgly/Replace`
Icon

Name
`@imgly/Reset`
Icon

Name
`@imgly/RotateCCW90`
Icon

Name
`@imgly/RotateCW`
Icon

Name
`@imgly/RotateCW90`
Icon

Name
`@imgly/Save`
Icon

Name
`@imgly/Scale`
Icon

Name
`@imgly/Search`
Icon

Name
`@imgly/Settings`
Icon

Name
`@imgly/SettingsCog`
Icon

Name
`@imgly/ShapeOval`
Icon

Name
`@imgly/ShapePolygon`
Icon

Name
`@imgly/ShapeRectangle`
Icon

Name
`@imgly/ShapeStar`
Icon

Name
`@imgly/Shapes`
Icon

Name
`@imgly/Share`
Icon

Name
`@imgly/SidebarOpen`
Icon

Name
`@imgly/Split`
Icon

Name
`@imgly/Sticker`
Icon

Name
`@imgly/Stop`
Icon

Name
`@imgly/Straighten`
Icon

Name
`@imgly/StrokeDash`
Icon

Name
`@imgly/StrokeDotted`
Icon

Name
`@imgly/StrokePositionCenter`
Icon

Name
`@imgly/StrokePositionInside`
Icon

Name
`@imgly/StrokePositionOutside`
Icon

Name
`@imgly/StrokeSolid`
Icon

Name
`@imgly/StrokeWeight`
Icon

Name
`@imgly/Template`
Icon

Name
`@imgly/Text`
Icon

Name
`@imgly/TextAlignBottom`
Icon

Name
`@imgly/TextAlignCenter`
Icon

Name
`@imgly/TextAlignLeft`
Icon

Name
`@imgly/TextAlignMiddle`
Icon

Name
`@imgly/TextAlignRight`
Icon

Name
`@imgly/TextAlignTop`
Icon

Name
`@imgly/TextAutoHeight`
Icon

Name
`@imgly/TextAutoSize`
Icon

Name
`@imgly/TextBold`
Icon

Name
`@imgly/TextFixedSize`
Icon

Name
`@imgly/TextItalic`
Icon

Name
`@imgly/Timeline`
Icon

Name
`@imgly/ToggleIconOff`
Icon

Name
`@imgly/ToggleIconOn`
Icon

Name
`@imgly/TransformSection`
Icon

Name
`@imgly/TrashBin`
Icon

Name
`@imgly/TriangleDown`
Icon

Name
`@imgly/TriangleUp`
Icon

Name
`@imgly/TrimMedia`
Icon

Name
`@imgly/Typeface`
Icon

Name
`@imgly/Undo`
Icon

Name
`@imgly/Ungroup`
Icon

Name
`@imgly/Upload`
Icon

Name
`@imgly/Video`
Icon

Name
`@imgly/VideoCamera`
Icon

Name
`@imgly/Volume`
Icon

Name
`@imgly/VolumeMute`
Icon

Name
`@imgly/ZoomIn`
Icon

Name
`@imgly/ZoomOut`
Icon

[
Previous
Asset Library Entry
](/docs/cesdk/ui/customization/api/assetLibraryEntry/)[
Next
Panel
](/docs/cesdk/ui/customization/api/panel/)
Modify Crop - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/api/block-crop/?platform=web&language=javascript
# Modify Crop
In this example, we will show you how to use the [CreativeEditor SDK](https://img.ly/products/creative-sdk)'s CreativeEngine to modify a blocks crop through the `block` API.
##
Setup
This example uses the headless CreativeEngine. See the [Setup](/docs/cesdk/engine/quickstart/) article for a detailed guide. To get started right away, you can also access the `block` API within a running CE.SDK instance via `cesdk.engine.block`. Check out the [APIs Overview](../) to see that illustrated in more detail.
##
Common Properties
Common properties are properties that occur on multiple block types. For instance, fill color properties are available for all the shape blocks and the text block. That's why we built convenient setter and getter functions for these properties. So you don't have to use the generic setters and getters and don't have to provide a specific property path. There are also `has*` functions to query if a block supports a set of common properties.
###
Crop
Manipulate the cropping region of a block by setting its scale, rotation, and translation.
```
supportsCrop(id: DesignBlockId): boolean
```
Query if the given block has crop properties.
* `id`: The block to query.
* Returns true, if the block has crop properties.
```
engine.block.supportsCrop(image);
```
```
setCropScaleX(id: DesignBlockId, scaleX: number): void
```
Set the crop scale in x direction of the given design block. Required scope: 'layer/crop'
* `id`: The block whose crop should be set.
* `scaleX`: The scale in x direction.
```
engine.block.setCropScaleX(image, 2.0);
```
```
setCropScaleY(id: DesignBlockId, scaleY: number): void
```
Set the crop scale in y direction of the given design block. Required scope: 'layer/crop'
* `id`: The block whose crop should be set.
* `scaleY`: The scale in y direction.
```
engine.block.setCropScaleY(image, 1.5);
```
```
setCropScaleRatio(id: DesignBlockId, scaleRatio: number): void
```
Set the crop scale ratio of the given design block. This will uniformly scale the content up or down. The center of the scale operation is the center of the crop frame. Required scope: 'layer/crop'
* `id`: The block whose crop should be set.
* `scaleRatio`: The crop scale ratio.
```
engine.block.setCropScaleRatio(image, 3.0);
```
```
setCropRotation(id: DesignBlockId, rotation: number): void
```
Set the crop rotation of the given design block. Required scope: 'layer/crop'
* `id`: The block whose crop should be set.
* `rotation`: The rotation in radians.
```
engine.block.setCropRotation(image, Math.PI);
```
```
setCropTranslationX(id: DesignBlockId, translationX: number): void
```
Set the crop translation in x direction of the given design block. Required scope: 'layer/crop'
* `id`: The block whose crop should be set.
* `translationX`: The translation in x direction.
```
engine.block.setCropTranslationX(image, -1.0);
```
```
setCropTranslationY(id: DesignBlockId, translationY: number): void
```
Set the crop translation in y direction of the given design block. Required scope: 'layer/crop'
* `id`: The block whose crop should be set.
* `translationY`: The translation in y direction.
```
engine.block.setCropTranslationY(image, 1.0);
```
```
adjustCropToFillFrame(id: DesignBlockId, minScaleRatio: number): number
```
Adjust the crop position/scale to at least fill the crop frame.
* `id`: The block whose crop scale ratio should be queried.
* `minScaleRatio`: The minimal crop scale ratio to go down to.
```
engine.block.adjustCropToFillFrame(image, 1.0);
```
```
setContentFillMode(id: DesignBlockId, mode: ContentFillMode): void
```
Set a block's content fill mode. Required scope: 'layer/crop'
* `id`: The block to update.
* `mode`: The content fill mode mode: crop, cover or contain.
```
engine.block.setContentFillMode(image, 'Contain');
```
```
resetCrop(id: DesignBlockId): void
```
Resets the manually set crop of the given design block. The block's content fill mode is set to 'cover'. If the block has a fill, the crop values are updated so that it covers the block. Required scope: 'layer/crop'
* `id`: The block whose crop should be reset.
```
engine.block.resetCrop(image);
```
```
getCropScaleX(id: DesignBlockId): number
```
Get the crop scale on the x axis of the given design block.
* `id`: The block whose scale should be queried.
* Returns The scale on the x axis.
```
engine.block.getCropScaleX(image);
```
```
getCropScaleY(id: DesignBlockId): number
```
Get the crop scale on the y axis of the given design block.
* `id`: The block whose scale should be queried.
* Returns The scale on the y axis.
```
engine.block.getCropScaleY(image);
```
```
flipCropHorizontal(id: DesignBlockId): void
```
Adjusts the crop in order to flip the content along its own horizontal axis.
* `block`: The block whose crop should be updated.
```
engine.block.flipCropHorizontal(image);
```
```
flipCropVertical(id: DesignBlockId): void
```
Adjusts the crop in order to flip the content along its own vertical axis.
* `block`: The block whose crop should be updated.
```
engine.block.flipCropVertical(image);
```
```
getCropScaleRatio(id: DesignBlockId): number
```
Get the crop scale ratio of the given design block.
* `id`: The block whose crop scale ratio should be queried.
* Returns The crop scale ratio.
```
engine.block.getCropScaleRatio(image);
```
```
getCropRotation(id: DesignBlockId): number
```
Get the crop rotation of the given design block.
* `id`: The block whose crop rotation should be queried.
* Returns The crop rotation.
```
engine.block.getCropRotation(image);
```
```
getCropTranslationX(id: DesignBlockId): number
```
Get the crop translation on the x axis of the given design block.
* `id`: The block whose translation should be queried.
* Returns The translation on the x axis.
```
engine.block.getCropTranslationX(image);
```
```
getCropTranslationY(id: DesignBlockId): number
```
Get the crop translation on the y axis of the given design block.
* `id`: The block whose translation should be queried.
* Returns The translation on the y axis.
```
engine.block.getCropTranslationY(image);
```
```
supportsContentFillMode(id: DesignBlockId): boolean
```
Query if the given block has a content fill mode.
* `id`: The block to query.
* Returns true, if the block has a content fill mode.
```
engine.block.supportsContentFillMode(image);
```
```
getContentFillMode(id: DesignBlockId): ContentFillMode
```
Query a block's content fill mode.
* `id`: The block to query.
* Returns The current mode: crop, cover or contain.
```
engine.block.getContentFillMode(image);
```
Manage Assets - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/api/assets/?platform=web&language=javascript
# Manage Assets
In this example, we will show you how to use the [CreativeEditor SDK](https://img.ly/products/creative-sdk)'s CreativeEngine to manage assets through the `asset` API.
To begin working with assets first you need at least one asset source. As the name might imply asset sources provide the engine with assets. These assets then show up in the editor's asset library. But they can also be independently searched and used to create design blocks. Asset sources can be added dynamically using the `asset` API as we will show in this guide.
##
Setup
This example uses the headless CreativeEngine. See the [Setup](/docs/cesdk/engine/quickstart/) article for a detailed guide. To get started right away, you can also access the `block` API within a running CE.SDK instance via `cesdk.engine.block`. Check out the [APIs Overview](../) to see that illustrated in more detail.
```
import CreativeEngine from 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.17.0/index.js';
const config = {
baseURL: 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.17.0/assets'
};
CreativeEngine.init(config).then(async (engine) => {
const scene = engine.scene.create();
const page = engine.block.create('page');
engine.block.appendChild(scene, page);
```
##
Defining a Custom Asset Source
Asset sources need at least an `id` and a `findAssets` function. You may notice asset source functions are all `async`. This way you can use web requests or other long-running operations inside them and return results asynchronously.
Let's go over these properties one by one:
```
const customSource = {
```
All functions of the `asset` API refer to an asset source by its unique `id`. That's why it has to be mandatory. Trying to add an asset source with an already registered `id` will fail.
```
id: 'foobar',
```
##
Finding and Applying Assets
The `findAssets` function should return paginated asset results for the given `queryData`. The asset results have a set of mandatory and optional properties. For a listing with an explanation for each property please refer to the [Integrate a Custom Asset Source](/docs/cesdk/engine/guides/integrate-a-custom-asset-source/) guide. The properties of the `queryData` and the pagination mechanism are also explained in this guide.
```
findAssets(sourceId: string, query: AssetQueryData): Promise>
```
Finds assets of a given type in a specific asset source.
* `sourceId`: The ID of the asset source.
* `query`: All the options to filter the search results by.
* Returns The search results.
```
const result = await engine.asset.findAssets(customSource.id, {
page: 0,
perPage: 100
});
const asset = result.assets[0];
const sortByNewest = await engine.asset.findAssets('ly.img.image.upload', {
page: 0,
perPage: 10,
sortingOrder: 'Descending'
});
const sortById = await engine.asset.findAssets('ly.img.image.upload', {
page: 0,
perPage: 10,
sortingOrder: 'Ascending',
sortKey: 'id'
});
const sortByMetaKeyValue = await engine.asset.findAssets(
'ly.img.image.upload',
{
page: 0,
perPage: 10,
sortingOrder: 'Ascending',
sortKey: 'someMetaKey'
}
);
const search = await engine.asset.findAssets('ly.img.asset.source.unsplash', {
query: 'banana',
page: 0,
perPage: 100
});
```
The optional function 'applyAsset' is to define the behavior of what to do when an asset gets applied to the scene. You can use the engine's APIs to do whatever you want with the given asset result. In this case, we always create an image block and add it to the first page we find.
If you don't provide this function the engine's default behavior is to create a block based on the asset result's `meta.blockType` property, add the block to the active page, and sensibly position and size it.
```
apply(sourceId: string, assetResult: AssetResult): Promise
```
Apply an asset result to the active scene. The default behavior will instantiate a block and configure it according to the asset's properties. Note that this can be overridden by providing an `applyAsset` function when adding the asset source.
* `sourceId`: The ID of the asset source.
* `assetResult`: A single assetResult of a `findAssets` query.
```
await engine.asset.apply(customSource.id, asset);
```
```
defaultApplyAsset(assetResult: AssetResult): Promise
```
The default implementation for applying an asset to the scene. This implementation is used when no `applyAsset` function is provided to `addSource`.
* `assetResult`: A single assetResult of a `findAssets` query.
```
return engine.asset.defaultApplyAsset(assetResult);
```
```
applyToBlock(sourceId: string, assetResult: AssetResult, block: DesignBlockId): Promise
```
Apply an asset result to the given block.
* `sourceId`: The ID of the asset source.
* `assetResult`: A single assetResult of a `findAssets` query.
* `block`: The block the asset should be applied to.
```
await engine.asset.applyToBlock(customSource.id, asset);
```
```
defaultApplyAssetToBlock(assetResult: AssetResult, block: DesignBlockId): Promise
```
The default implementation for applying an asset to an existing block.
* `assetResult`: A single assetResult of a `findAssets` query.
* `block`: The block to apply the asset result to.
```
engine.asset.defaultApplyAssetToBlock(assetResult, block);
```
```
getSupportedMimeTypes(sourceId: string): string[]
```
Queries the list of supported mime types of the specified asset source. An empty result means that all mime types are supported.
* `sourceId`: The ID of the asset source.
```
const mimeTypes = engine.asset.getSupportedMimeTypes(
```
##
Registering a New Asset Source
```
addSource(source: AssetSource): void
```
Adds a custom asset source. Its ID has to be unique.
* `source`: The asset source.
```
engine.asset.addSource(customSource);
```
```
addLocalSource(id: string, supportedMimeTypes?: string[], applyAsset?: (asset: CompleteAssetResult) => Promise, applyAssetToBlock?: (asset: CompleteAssetResult, block: DesignBlockId) => Promise): void
```
Adds a local asset source. Its ID has to be unique.
* `source`: The asset source.
* `supportedMimeTypes`: The mime types of assets that are allowed to be added to this local source.
* `applyAsset`: An optional callback that can be used to override the default behavior of applying a given asset result to the active scene.
* `applyAssetToBlock`: An optional callback that can be used to override the default behavior of applying an asset result to a given block.
```
engine.asset.addLocalSource('local-source');
```
```
findAllSources(): string[]
```
Finds all registered asset sources.
* Returns A list with the IDs of all registered asset sources.
```
engine.asset.findAllSources();
```
```
removeSource(id: string): void
```
Removes an asset source with the given ID.
* `id`: The ID to refer to the asset source.
```
engine.asset.removeSource('local-source');
```
```
onAssetSourceAdded: (callback: (sourceID: string) => void) => (() => void)
```
Register a callback to be called every time an asset source is added.
* `callback`: The function that is called whenever an asset source is added.
* Returns A method to unsubscribe.
```
engine.asset.onAssetSourceAdded((sourceID) => {
```
```
onAssetSourceRemoved: (callback: (sourceID: string) => void) => (() => void)
```
Register a callback to be called every time an asset source is removed.
* `callback`: The function that is called whenever an asset source is added.
* Returns A method to unsubscribe.
```
engine.asset.onAssetSourceRemoved((sourceID) => {
```
```
onAssetSourceUpdated: (callback: (sourceID: string) => void) => (() => void)
```
Register a callback to be called every time an asset source's contents are changed.
* `callback`: The function that is called whenever an asset source is updated.
* Returns A method to unsubscribe.
```
engine.asset.onAssetSourceUpdated((sourceID) => {
```
##
Scene Asset Sources
A scene colors asset source is automatically available that allows listing all colors in the scene. This asset source is read-only and is updated when `findAssets` is called.
```
const sceneColorsResult = await engine.asset.findAssets(
'ly.img.scene.colors',
{
page: 0,
perPage: 99999
}
);
const colorAsset = sceneColorsResult.assets[0];
```
##
Add an Asset
```
addAssetToSource(sourceId: string, asset: AssetDefinition): void
```
Adds the given asset to a local asset source.
* `sourceId`: The local asset source ID that the asset should be added to.
* `asset`: The asset to be added to the asset source.
```
engine.asset.addAssetToSource('local-source', {
id: 'ocean-waves-1',
label: {
en: 'relaxing ocean waves'
},
tags: {
en: ['ocean', 'waves', 'soothing', 'slow']
},
meta: {
uri: `https://example.com/ocean-waves-1.mp4`,
thumbUri: `https://example.com/thumbnails/ocean-waves-1.jpg`,
mimeType: 'video/mp4',
width: 1920,
height: 1080
}
});
```
##
Remove an Asset
```
removeAssetFromSource(sourceId: string, assetId: string): void
```
Removes the specified asset from its local asset source.
* `sourceId`: The id of the local asset source that currently contains the asset.
* `assetId`: The id of the asset to be removed.
```
engine.asset.removeAssetFromSource('local-source', 'ocean-waves-1');
```
##
Asset Source Content Updates
If the contents of your custom asset source change, you can call the `assetSourceUpdated` API to later notify all subscribers of the `onAssetSourceUpdated` API.
```
assetSourceContentsChanged(sourceID: string): void
```
Notifies the engine that the contents of an asset source changed.
* `sourceID`: The asset source whose contents changed.
```
engine.asset.assetSourceContentsChanged(customSource.id);
```
##
Groups in Assets
```
getGroups(id: string): Promise
```
Queries the asset source's groups for a certain asset type.
* `id`: The ID of the asset source.
* Returns The asset groups.
```
const groups = engine.asset.getGroups(customSource.id);
```
##
Credits and License
```
getCredits(sourceId: string): {
name: string;
url: string | undefined;
} | undefined
```
Queries the asset source's credits info.
* `sourceId`: The ID of the asset source.
* Returns The asset source's credits info consisting of a name and an optional URL.
```
const credits = engine.asset.getCredits(customSource.id);
```
```
getLicense(sourceId: string): {
name: string;
url: string | undefined;
} | undefined
```
Queries the asset source's license info.
* `sourceId`: The ID of the asset source.
* Returns The asset source's license info consisting of a name and an optional URL.
```
const license = engine.asset.getLicense(customSource.id);
```
Use of Emojis in Text - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/guides/text-with-emojis/?platform=web&language=javascript
# Use of Emojis in Text
Text blocks in CE.SDK support the use of emojis. A default emoji font is used to render these independently from the target platform. This guide shows how to change the default font and use emojis in text blocks.
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-text-with-emojis?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Text+With+Emojis&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-text-with-emojis).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-text-with-emojis?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Text+With+Emojis&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-text-with-emojis)
##
Setup
This example uses the headless CreativeEngine. See the [Setup](/docs/cesdk/engine/quickstart/) article for a detailed guide. To get started right away, you can also access the `block` API within a running CE.SDK instance via `cesdk.engine.block`. Check out the [APIs Overview](/docs/cesdk/engine/api/) to see that illustrated in more detail.
```
import CreativeEngine from 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.43.0/index.js';
```
##
Change the Default Emoji Font
The default front URI can be changed when another emoji font should be used or when the font should be served from another website, a content delivery network (CDN), or a file path. The preset is to use the [NotoColorEmoji](https://github.com/googlefonts/noto-emoji) font loaded from our [CDN](https://cdn.img.ly/assets/v3/emoji/NotoColorEmoji.ttf). This font file supports a wide variety of Emojis and is licensed under the [Open Font License](https://cdn.img.ly/assets/v3/emoji/LICENSE.txt).
In order to change the URI, call the `setSettingString(keypath: string, value: string)` [Editor API](/docs/cesdk/engine/api/editor-change-settings/) with 'defaultEmojiFontFileUri' as keypath and the new URI as value.
```
let uri = engine.editor.getSettingString('ubq://defaultEmojiFontFileUri');
// From a bundle
engine.editor.setSettingString(
'ubq://defaultEmojiFontFileUri',
'bundle://ly.img.cesdk/fonts/NotoColorEmoji.ttf'
);
// From a URL
engine.editor.setSettingString(
'ubq://defaultEmojiFontFileUri',
'https://cdn.img.ly/assets/v2/emoji/NotoColorEmoji.ttf'
);
```
##
Add a Text Block with an Emoji
To add a text block with an emoji, add a text block and set the emoji as text content.
```
const text = engine.block.create('text');
engine.block.setString(text, 'text/text', 'Text with an emoji 🧐');
engine.block.setWidthMode(text, 'Auto');
engine.block.setHeightMode(text, 'Auto');
engine.block.appendChild(page, text);
```
Strokes - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/api/block-strokes/?platform=web&language=javascript
# Strokes
In this example, we will show you how to use the [CreativeEditor SDK](https://img.ly/products/creative-sdk)'s CreativeEngine to modify strokes through the `block` API. Strokes can be added to any shape or text and stroke styles are varying from plain solid lines to dashes and gaps of varying lengths and can have different end caps.
##
Setup
This example uses the headless CreativeEngine. See the [Setup](/docs/cesdk/engine/quickstart/) article for a detailed guide. To get started right away, you can also access the `block` API within a running CE.SDK instance via `cesdk.engine.block`. Check out the [APIs Overview](../) to see that illustrated in more detail.
##
Strokes
```
supportsStroke(id: DesignBlockId): boolean
```
Query if the given block has a stroke property.
* `id`: The block to query.
* Returns True if the block has a stroke property.
```
if (engine.block.supportsStroke(block)) {
```
```
setStrokeEnabled(id: DesignBlockId, enabled: boolean): void
```
Enable or disable the stroke of the given design block. Required scope: 'stroke/change'
* `id`: The block whose stroke should be enabled or disabled.
* `enabled`: If true, the stroke will be enabled.
```
engine.block.setStrokeEnabled(block, true);
```
```
isStrokeEnabled(id: DesignBlockId): boolean
```
Query if the stroke of the given design block is enabled.
* `id`: The block whose stroke state should be queried.
* Returns True if the block's stroke is enabled.
```
const strokeIsEnabled = engine.block.isStrokeEnabled(block);
```
```
setStrokeColor(id: DesignBlockId, color: Color): void
```
Set the stroke color of the given design block. Required scope: 'stroke/change'
* `id`: The block whose stroke color should be set.
* `color`: The color to set.
```
engine.block.setStrokeColor(block, { r: 0, g: 1, b: 0, a: 1 });
```
```
getStrokeColor(id: DesignBlockId): Color
```
Get the stroke color of the given design block.
* `id`: The block whose stroke color should be queried.
* Returns The stroke color.
```
const strokeColor = engine.block.getStrokeColor(block);
```
```
setStrokeWidth(id: DesignBlockId, width: number): void
```
Set the stroke width of the given design block. Required scope: 'stroke/change'
* `id`: The block whose stroke width should be set.
* `width`: The stroke width to be set.
```
engine.block.setStrokeWidth(block, 5);
```
```
getStrokeWidth(id: DesignBlockId): number
```
Get the stroke width of the given design block.
* `id`: The block whose stroke width should be queried.
* Returns The stroke's width.
```
const strokeWidth = engine.block.getStrokeWidth(block);
```
```
setStrokeStyle(id: DesignBlockId, style: StrokeStyle): void
```
Set the stroke style of the given design block. Required scope: 'stroke/change'
* `id`: The block whose stroke style should be set.
* `style`: The stroke style to be set.
```
engine.block.setStrokeStyle(block, 'Dashed');
```
```
type StrokeStyle = 'Dashed' | 'DashedRound' | 'Dotted' | 'LongDashed' | 'LongDashedRound' | 'Solid'
```
```
engine.block.setStrokeStyle(block, 'Dashed');
```
```
getStrokeStyle(id: DesignBlockId): StrokeStyle
```
Get the stroke style of the given design block.
* `id`: The block whose stroke style should be queried.
* Returns The stroke's style.
```
const strokeStyle = engine.block.getStrokeStyle(block);
```
```
setStrokePosition(id: DesignBlockId, position: StrokePosition): void
```
Set the stroke position of the given design block. Required scope: 'stroke/change'
* `id`: The block whose stroke position should be set.
* `position`: The stroke position to be set.
```
engine.block.setStrokePosition(block, 'Outer');
```
```
type StrokePosition = 'Center' | 'Inner' | 'Outer'
```
```
engine.block.setStrokePosition(block, 'Outer');
```
```
getStrokePosition(id: DesignBlockId): StrokePosition
```
Get the stroke position of the given design block.
* `id`: The block whose stroke position should be queried.
* Returns The stroke position.
```
const strokePosition = engine.block.getStrokePosition(block);
```
```
setStrokeCornerGeometry(id: DesignBlockId, cornerGeometry: StrokeCornerGeometry): void
```
Set the stroke corner geometry of the given design block. Required scope: 'stroke/change'
* `id`: The block whose stroke join geometry should be set.
* `cornerGeometry`: The stroke join geometry to be set.
```
engine.block.setStrokeCornerGeometry(block, 'Round');
```
```
type StrokeCornerGeometry = 'Bevel' | 'Miter' | 'Round'
```
```
engine.block.setStrokeCornerGeometry(block, 'Round');
```
```
getStrokeCornerGeometry(id: DesignBlockId): StrokeCornerGeometry
```
Get the stroke corner geometry of the given design block.
* `id`: The block whose stroke join geometry should be queried.
* Returns The stroke join geometry.
```
const strokeCornerGeometry = engine.block.getStrokeCornerGeometry(block);
```
Using a custom URI resolver - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/guides/resolve-custom-uri/?platform=web&language=javascript
# Using a custom URI resolver
CE.SDK gives you full control over how URIs should be resolved. To register a custom resolver, use `setURIResolver` and pass in a function implementing your resolution logic. If a custom resolver is set, any URI requested by the engine is passed through the resolver. The URI your logic returns is then fetched by the engine. The resolved URI is just used for the current request and not stored. If, and only if, no custom resolver is set, the engine performs the default behaviour: absolute paths are unchanged and relative paths are prepended with the value of the `basePath` setting.
####
Warning
Your custom URI resolver must return an absolute path with a scheme.
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-uri-resolver?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Uri+Resolver&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-uri-resolver).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-uri-resolver?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Uri+Resolver&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-uri-resolver)
We can preview the effects of setting a custom URI resolver with the function `getAbsoluteURI`.
Before setting a custom URI resolver, the default behavior is as before and the given relative path will be prepended with the contents of `basePath`.
```
/** This will return 'https://cdn.img.ly/packages/imgly/cesdk-js/1.43.0/assets/banana.jpg'. */
instance.engine.editor.getAbsoluteURI('/banana.jpg');
```
To show that the resolver can be fairly free-form, in this example we register a custom URI resolver that replaces all `.jpg` images with our company logo. The resolved URI are expected to be absolute.
Note: you can still access the default URI resolver by calling `defaultURIResolver(relativePath)`.
```
/** Replace all .jpg files with the IMG.LY logo! **/
instance.engine.editor.setURIResolver((uri, defaultURIResolver) => {
if (uri.endsWith('.jpg')) {
return 'https://img.ly/static/ubq_samples/imgly_logo.jpg';
}
/** Make use of the default URI resolution behavior. */
return defaultURIResolver(uri);
});
```
Given the same path as earlier, the custom resolver transforms it as specified. Note that after a custom resolver is set, relative paths that the resolver does not transform remain unmodified.
```
/**
* The custom resolver will return a path to the IMG.LY logo because the given path ends with '.jpg'.
* This applies regardless if the given path is relative or absolute.
*/
instance.engine.editor.getAbsoluteURI('/banana.jpg');
/** The custom resolver will not modify this path because it ends with '.png'. */
instance.engine.editor.getAbsoluteURI('https://example.com/orange.png');
/** Because a custom resolver is set, relative paths that the resolver does not transform remain unmodified! */
instance.engine.editor.getAbsoluteURI('/orange.png');
```
To remove a previously set custom resolver, call the function with a `null` value. The URI resolution is now back to the default behavior.
```
/** Removes the previously set resolver. */
instance.engine.editor.setURIResolver(null);
/** Since we've removed the custom resolver, this will return 'https://cdn.img.ly/packages/imgly/cesdk-js/1.43.0/assets/banana.jpg' like before. */
instance.engine.editor.getAbsoluteURI('/banana.jpg');
```
Overview - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/guides/
CESDK/CE.SDK/Web Editor/Guides
# Overview
Delight your users with the powerful theming capabilities of the CreativeEditor SDK.

Adjusting the CE.SDK's style to match your corporate identity or just your taste is a breeze.
##
Detailed Guides about Theming
**[Controlling UI Elements](/docs/cesdk/ui/guides/elements/)**
Control which UI elements are available.
**[The Video Editor](/docs/cesdk/ui/guides/video/overview/)**
Enable your users to edit videos.
**[Predefined Themes](/docs/cesdk/ui/guides/theming/#using-the-built-in-themes-and-scale)**
Get to know our hand-crafted predefined themes and how to use them.
**[Theme Generator](/docs/cesdk/ui/guides/theming/#using-the-theme-generator)**
Learn how to quickly adapt the predefined themes to match your needs and quickly create custom themes..
**[Configuration](/docs/cesdk/ui/guides/theming/#configuration)**
Explore advanced configuration options to quickly realize your desired theme.
**[Theming API](/docs/cesdk/ui/guides/theming/#theming-api)**
Learn about advanced theming techniques via our dedicated API.
[
Previous
UI Configuration
](/docs/cesdk/ui/configuration/ui/)[
Next
I18n
](/docs/cesdk/ui/guides/i18n/)
How to Store Custom Metadata - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/guides/store-metadata/?platform=web&language=javascript
# How to Store Custom Metadata
CE.SDK allows you to store custom metadata in your scenes. You can attach metadata to your scene or directly to your individual design blocks within the scene. This metadata is persistent across saving and loading of scenes. It simply consists of key value pairs of strings. Using any string-based serialization format such as JSON will allow you to store even complex objects. Please note that when duplicating blocks their metadata will also be duplicated.
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-store-metadata?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Store+Metadata&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-store-metadata).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-store-metadata?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Store+Metadata&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-store-metadata)
##
Setup
This example uses the headless CreativeEngine. See the [Setup](/docs/cesdk/engine/quickstart/) article for a detailed guide. To get started right away, you can also access the `block` API within a running CE.SDK instance via `cesdk.engine.block`. Check out the [APIs Overview](/docs/cesdk/engine/api/) to see that illustrated in more detail.
```
import CreativeEngine from 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.43.0/index.js';
const config = {
license: 'mtLT-_GJwMhE7LDnO8KKEma7qSuzWuDxiKuQcxHKmz3fjaXWY2lT3o3Z2VdL5twm',
userId: 'guides-user',
baseURL: 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.43.0/assets'
};
CreativeEngine.init(config).then(async (engine) => {
let scene = await engine.scene.createFromImage(
'https://img.ly/static/ubq_samples/imgly_logo.jpg'
);
// get the graphic block with the image fill
// Note: In this example we know that the first block since there is only one block in the scene
// at this point. You might need to filter by fill type if you have multiple blocks.
const block = engine.block.findByType('graphic')[0];
```
##
Working with Metadata
We can add metadata to any design block using `setMetadata(block: number, key: string, value: string)`. This also includes the scene block.
```
engine.block.setMetadata(scene, 'author', 'img.ly');
engine.block.setMetadata(block, 'customer_id', '1234567890');
/* We can even store complex objects */
const payment = {
id: 5,
method: 'credit_card',
received: true
};
engine.block.setMetadata(block, 'payment', JSON.stringify(payment));
```
We can retrieve metadata from any design block or scene using `getMetadata(block: number, key: string): string`. Before accessing the metadata you check for its existence using `hasMetadata(block: number, key: string): boolean`.
```
/* This will return 'img.ly' */
engine.block.getMetadata(scene, 'author');
/* This will return '1000000' */
engine.block.getMetadata(block, 'customer_id');
```
We can query all metadata keys from any design block or scene using `findAllMetadata(block: number): string[]`. For blocks without any metadata, this will return an empty list.
```
/* This will return ['customer_id'] */
engine.block.findAllMetadata(block);
```
If you want to get rid of any metadata, you can use `removeMetadata(block: number, key: string)`.
```
engine.block.removeMetadata(block, 'payment');
/* This will return false */
engine.block.hasMetadata(block, 'payment');
```
Metadata will automatically be saved and loaded as part the scene. So you don't have to worry about it getting lost or having to save it separately.
```
/* We save our scene and reload it from scratch */
const sceneString = await engine.scene.saveToString();
scene = await engine.scene.loadFromString(sceneString);
/* This still returns 'img.ly' */
engine.block.getMetadata(scene, 'author');
/* And this still returns '1234567890' */
engine.block.getMetadata(block, 'customer_id');
```
Creating A Custom Panel - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/customization/guides/creatingCustomPanel/
CESDK/CE.SDK/Web Editor/Customization/Guides
# Creating A Custom Panel
Learn how to create and open a custom panel in the CE.SDK editor
For some complex workflows, simply adding or moving buttons may not be enough. You’ll need a way for users to interact with the panel’s content to input or process information.
The CE.SDK editor allows you to add fully custom panels, and in this guide, we will cover the basics. Please, also take a look at the [Custom Panel API reference](/docs/cesdk/ui/customization/api/customPanel/) for more information.
##
Registering a Custom Panel
The entry point for writing a custom panel is the method `registerPanel`. For a given panel identifier, you add a function that will be called repeatedly to render the content of the panel. Several arguments are passed to this function that can be used to access the current state of the `engine` and render an UI with the help of the `builder`.
```
cesdk.ui.registerPanel('myCustomPanel', ({ builder, engine }) => {
// Once `findAllSelected` changes, the panel will be re-rendered
// with the correct number of selected blocks
const selectedIds = engine.block.findAllSelected();
// Create a new section with a title
builder.Section('selected', {
title: `Selected Elements: ${selectedIds.length}`,
children: () => {
// For every selected block, ...
selectedIds.forEach((selectedId) => {
// ... create a button ...
builder.Button(`select.${selectedId}`, {
label: `Deselect ${selectedId}`,
onClick: () => {
// ... that deselects the block when clicked
engine.block.setSelected(selectedId, false);
}
});
});
}
});
});
```
Once a panel is registered, it can be controlled using the [Panel API](/docs/cesdk/ui/customization/api/panel/), just like any other panel. For instance, you can open a custom panel with `cesdk.ui.openPanel(registeredPanelId)`. Other settings, such as position and floating, can also be adjusted accordingly.
In most cases, you will want to open it using a custom button, .e.g in a button inside the [Dock](/docs/cesdk/ui/customization/api/dock/) or [Inspector Bar](/docs/cesdk/ui/customization/api/inspectorBar/).
```
cesdk.ui.registerComponent('myCustomPanel.dock', ({ builder }) => {
const isPanelOpen = cesdk.ui.isPanelOpen('myCustomPanel');
builder.Button('open-my-custom-panel', {
label: 'My Custom Panel',
onClick: () => {
if (isPanelOpen) {
cesdk.ui.closePanel('myCustomPanel');
} else {
cesdk.ui.openPanel('myCustomPanel');
}
}
});
});
cesdk.ui.setDockOrder([
...cesdk.ui.getDockOrder(),
// We add a spacer to push the new button to the bottom
'ly.img.spacer',
// The id of the component we registered earlier to open the panel
'myCustomPanel.dock'
]);
```
[
Previous
One-Click Quick Action Plugins
](/docs/cesdk/ui/customization/guides/oneClickQuickActionPlugins/)[
Next
Overview
](/docs/cesdk/ui/customization/api/)
Save Scenes to a Blob - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/guides/save-scene-to-blob/?platform=web&language=javascript
# Save Scenes to a Blob
In this example, we will show you how to save scenes as a `Blob` with the [CreativeEditor SDK](https://img.ly/products/creative-sdk).
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-save-scene-to-blob?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Save+Scene+To+Blob&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-save-scene-to-blob).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-save-scene-to-blob?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Save+Scene+To+Blob&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-save-scene-to-blob)
The CreativeEngine allows you to save scenes in a binary format to share them between editors or store them for later editing. This is done by converting the contents of a scene to a string, which can then be stored or transferred. For sending these to a remote location, we wrap them in a `Blob` and treat it as a file object.
####
Warning
A _scene file_ does not include any fonts or images. Only the source URIs of assets, the general layout, and element properties are stored. When loading scenes in a new environment, ensure previously used asset URIs are available.
To get hold of the scene contents as string, you need to use `engine.scene.saveToString()`. This is an asynchronous method returning a `Promise`. After waiting for the `Promise` to resolve, we receive a plain string holding the entire scene currently loaded in the editor. This includes all pages and any hidden elements but none of the actual asset data.
```
engine.scene
.saveToString()
.then((savedSceneString) => {
const blob = new Blob([savedSceneString], {
type: 'text/plain'
});
const formData = new FormData();
formData.append('file', blob);
fetch('/upload', {
method: 'POST',
body: formData
});
})
.catch((error) => {
console.error('Save failed', error);
});
```
The returned string consists solely of ASCII characters and can safely be used further or written to a database. In this case, we need a `Blob` object, so we proceed to wrap the received string into a `Blob`, a file-like object of immutable, raw data.
```
const blob = new Blob([savedSceneString], {
type: 'text/plain'
});
```
That object can then be treated as a form file parameter and sent to a remote location.
```
const formData = new FormData();
formData.append('file', blob);
fetch('/upload', {
method: 'POST',
body: formData
});
```
Exploration - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/api/block-exploration/?platform=web&language=javascript
# Exploration
Learn how to use the [CreativeEditor SDK](https://img.ly/products/creative-sdk)'s CreativeEngine to explore scenes through the `block` API.
##
Setup
This example uses the headless CreativeEngine. See the [Setup](/docs/cesdk/engine/quickstart/) article for a detailed guide. To get started right away, you can also access the `block` API within a running CE.SDK instance via `cesdk.engine.block`. Check out the [APIs Overview](../) to see that illustrated in more detail.
##
Functions
```
findAll(): DesignBlockId[]
```
Return all blocks currently known to the engine.
* Returns A list of block ids.
```
const allIds = engine.block.findAll();
```
```
findAllPlaceholders(): DesignBlockId[]
```
Return all placeholder blocks in the current scene.
* Returns A list of block ids.
```
const allPlaceholderIds = engine.block.findAllPlaceholders();
```
```
findByType(type: ObjectType): DesignBlockId[]
```
Finds all blocks with the given type.
* `type`: The type to search for.
* Returns A list of block ids.
```
const allPages = engine.block.findByType('page');
const allImageFills = engine.block.findByType('fill/image');
const allStarShapes = engine.block.findByType('shape/star');
const allHalfToneEffects = try engine.block.findByType('effect/half_tone')
const allUniformBlurs = try engine.block.findByType('blur/uniform')
```
```
findByKind(kind: string): DesignBlockId[]
```
Finds all blocks with the given kind.
* `kind`: The kind to search for.
* Returns A list of block ids.
```
const allStickers = engine.block.findByKind('sticker');
```
```
findByName(name: string): DesignBlockId[]
```
Finds all blocks with the given name.
* `name`: The name to search for.
* Returns A list of block ids.
```
const ids = engine.block.findByName('someName');
```
Building and Using Plugins - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/customization/plugins/
CESDK/CE.SDK/Web Editor/Customization/Plugins
# Building and Using Plugins
Learn about building and using plugins
All customization of the editor can be done during the initialization of the CE.SDK web editor by using the customization APIs described here. For most use cases, this will be sufficient. However, sometimes you might want to encapsulate functionality and make it reusable. This is where plugins come in.
**[Create a Plugin](/docs/cesdk/ui/customization/plugins/createPlugin/)**
Learn how to bundle your own code into a plugin.
**[Background Removal](/docs/cesdk/ui/customization/plugins/backgroundRemoval/)**
Install and use the official IMG.LY Background Removal plugin.
**[Vectorizer](/docs/cesdk/ui/customization/plugins/vectorizer/)**
Install and use the official IMG.LY Vectorizer plugin.
[
Previous
Basics & Principles
](/docs/cesdk/ui/customization/basics/)[
Next
Create Plugin
](/docs/cesdk/ui/customization/plugins/createPlugin/)
Integrate Creative Editor - CE.SDK | IMG.LY Docs [web/react/javascript] https://img.ly/docs/cesdk/ui/quickstart/?platform=web&language=javascript&framework=react
# Integrate Creative Editor
In this example, we will show you how to integrate [CreativeEditor SDK](https://img.ly/products/creative-sdk) with React.
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/integrate-with-react?title=IMG.LY%27s+CE.SDK%3A+Integrate+With+React&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/integrate-with-react).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/integrate-with-react?title=IMG.LY%27s+CE.SDK%3A+Integrate+With+React&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/integrate-with-react)
##
Prerequisites
* [Get the latest stable version of **Node.js & NPM**](https://www.npmjs.com/get-npm)
* [Setup Create React App](https://create-react-app.dev/docs/getting-started/)
##
Setup
Note that, for convenience we serve all SDK assets (e.g. images, stickers, fonts etc.) from our CDN by default. For use in a production environment we recommend [serving assets from your own servers](/docs/cesdk/ui/guides/assets-served-from-your-own-servers/).
###
1\. Add CE.SDK to your Project
Install the `@cesdk/cesdk-js` dependency via
`npm install --save @cesdk/cesdk-js`.
The SDK is served entirely via CDN, so we just need to import the CE.SDK module and the stylesheet containing the default theme settings.
```
import CreativeEditorSDK from '@cesdk/cesdk-js';
```
###
2\. Create an empty Container
We need to add an empty `
` as a container for the SDK. We configure the `
` element to fully fill the browser window.
###
3\. Create a component containing the SDK
We'll now create a `CreativeEditorSDKComponent`, that's responsible for initializing the SDK and attaching it to the previously created container.
Defining a constant configuration at the top level of your component module or import it from another module should be sufficient for most situations and is easy and safe to do if your configuration is static.
If you need configuration that is dynamically created inside your react app, make sure to create it in a `useMemo`. Be careful not to change it after it has been created. If you do so, the Creative Editor SDK will be disposed and recreated with the new configuration.
```
const config = {
license: 'mtLT-_GJwMhE7LDnO8KKEma7qSuzWuDxiKuQcxHKmz3fjaXWY2lT3o3Z2VdL5twm',
userId: 'guides-user',
// Enable local uploads in Asset Library
callbacks: { onUpload: 'local' }
};
export default function CreativeEditorSDKComponent() {
const cesdk_container = useRef(null);
const [cesdk, setCesdk] = useState(null);
useEffect(() => {
if (!cesdk_container.current) return;
let cleanedUp = false;
let instance;
CreativeEditorSDK.create(cesdk_container.current, config).then(
async (_instance) => {
instance = _instance;
if (cleanedUp) {
instance.dispose();
return;
}
// Do something with the instance of CreativeEditor SDK, for example:
// Populate the asset library with default / demo asset sources.
await Promise.all([
instance.addDefaultAssetSources(),
instance.addDemoAssetSources({ sceneMode: 'Design' })
]);
await instance.createDesignScene();
setCesdk(instance);
}
);
const cleanup = () => {
cleanedUp = true;
instance?.dispose();
setCesdk(null);
};
return cleanup;
}, [cesdk_container]);
return (
);
}
```
###
4\. Managing the container reference
To let CE.SDK use the container created by our component, we use `useRef` to acquire a reference to the element and pass it as the first parameter to `CreativeEditorSDK.create`.
At this point we might also want to store the instantiated CE.SDK in the react state. This instance can be passed around the app via `Context` or be used otherwise to interact with the CE.SDK. Note that this is optional and might not be necessary in every use case.
```
const cesdk_container = useRef(null);
const [cesdk, setCesdk] = useState(null);
```
###
4\. Use an effect to instantiate the SDK
Instantiating the CE.SDK is an asynchronous process. As such it needs to be managed in an effect. There are few things to keep in mind to do this successfully.
A common pitfall is a [feature of React 18, where during development, effects are always executed twice](https://react.dev/reference/react/useEffect#my-effect-runs-twice-when-the-component-mounts). This can make it tricky to cleanly dispose of a CE.SDK instance that hasn't finished initializing yet. The example code is written in a way to avoid that problem.
First, the effect needs to keep track of
* the information about whether the effect has been `cleanedUp` or not.
* the CE.SDK `instance` it created. This needs to be a variable _inside_ of the effect.
* **You can _not_ reliably use an outside variable, ref or state for this**.
Due to the asynchronous nature of the effect, using an outside variable creates a risk for two executions of the same effect to overwrite each other's instance.
* You also can't use the `_instance` parameter to the promise callback for this. This parameter is not accessible from the `cleanup` function. That's why we assign the instance to the `instance` variable as the first thing in the promise callback.
Then, the asynchronous `create` method is called, loading and instantiating the CE.SDK. During this asynchonous process, React 18 will remove the effect again, before the Promise returned from `create` is resolved. We recognize this situation by checking if `cleanedUp` has been set to true. If it has, we abort the rest of the initialization and immediately dispose the fresh instance.
During the second execution of the effect by React, `cleanedUp` will be false at this point, and we can proceed normally, configure the instance via the API, load/create a scene and finally update the react state with the instance.
The `cleanup` function returned from the effect performs all necessary steps to safely stop the initialization and clean up an existing CE.SDK instance from React.
* `cleanedUp` is set to `true`, to let us recognize this situation in the initialization process
* The `instance` our effect is managing is disposed.
* The react state is update to remove the reference to the CE.SDK instance
```
useEffect(() => {
if (!cesdk_container.current) return;
let cleanedUp = false;
let instance;
CreativeEditorSDK.create(cesdk_container.current, config).then(
async (_instance) => {
instance = _instance;
if (cleanedUp) {
instance.dispose();
return;
}
// Do something with the instance of CreativeEditor SDK, for example:
// Populate the asset library with default / demo asset sources.
await Promise.all([
instance.addDefaultAssetSources(),
instance.addDemoAssetSources({ sceneMode: 'Design' })
]);
await instance.createDesignScene();
setCesdk(instance);
}
);
const cleanup = () => {
cleanedUp = true;
instance?.dispose();
setCesdk(null);
};
return cleanup;
}, [cesdk_container]);
```
###
5\. Serving Webpage locally
In order to use the editor we need to run our project via `yarn`.
`yarn start` will spin up a development server at [http://localhost:3000](http://localhost:3000)
###
Congratulations!
You've got CE.SDK up and running. Get to know the SDK and dive into the next steps, when you're ready:
* [Perform Basic Configuration](/docs/cesdk/ui/configuration/basics/)
* [Serve assets from your own servers](/docs/cesdk/ui/guides/assets-served-from-your-own-servers/)
* [Create and use a license key](/docs/cesdk/engine/quickstart/#licensing)
* [Configure Callbacks](/docs/cesdk/ui/configuration/callbacks/)
* [Add Localization](/docs/cesdk/ui/guides/i18n/)
* [Adapt the User Interface](/docs/cesdk/ui/guides/theming/)
Observe Events - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/api/events/?platform=web&language=javascript
# Observe Events
In this example, we will show you how to use the [CreativeEditor SDK](https://img.ly/products/creative-sdk)'s CreativeEngine to subscribe to creation, update, and destruction events of design blocks.
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-event-api?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Event+Api&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-event-api).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-event-api?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Event+Api&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-event-api)
##
Setup
This example uses the headless CreativeEngine. See the [Setup](/docs/cesdk/engine/quickstart/) article for a detailed guide. To get started right away, you can also access the `block` API within a running CE.SDK instance via `cesdk.engine.block`. Check out the [APIs Overview](../) to see that illustrated in more detail.
```
import CreativeEngine from 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.43.0/index.js';
const config = {
license: 'mtLT-_GJwMhE7LDnO8KKEma7qSuzWuDxiKuQcxHKmz3fjaXWY2lT3o3Z2VdL5twm',
userId: 'guides-user',
baseURL: 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.43.0/assets'
};
CreativeEngine.init(config).then(async (engine) => {
document.getElementById('cesdk_container').append(engine.element);
const scene = engine.scene.create();
const page = engine.block.create('page');
engine.block.appendChild(scene, page);
```
##
Subscribing to Events
The event API provides a single function to subscribe to design block events. The types of events are:
* `'Created'`: The design block was just created.
* `'Updated'`: A property of the design block was updated.
* `'Destroyed'`: The design block was destroyed. Note that a destroyed block will have become invalid and trying to use Block API functions on it will result in an exception. You can always use the Block API's `isValid` function to verify whether a block is valid before use.
All events that occur during an engine update are batched, deduplicated, and always delivered at the very end of the engine update. Deduplication means you will receive at most one `'Updated'` event per block per subscription, even though there could potentially be multiple updates to a block during the engine update. To be clear, this also means the order of the event list provided to your event callback won't reflect the actual order of events within an engine update.
* `subscribe(blocks: number[], callback: (events: {type: string, block: number}[]) => void): () => void`
subscribe to events from a given list of blocks. Providing an empty list will subscribe to events from all of the engine's blocks. The provided callback will receive a list of events that occurred in the last engine update. Each event consists of the event `type` and the affected `block`. The returned function shall be used to unsubscribe from receiving further events.
```
let unsubscribe = engine.event.subscribe([block], (events) => {
for (var i = 0; i < events.length; i++) {
let event = events[i];
```
##
Unsubscribing from events
* `subscribe` returns a function that can be called to unsubscribe from receiving events.
Note that it is important to unsubscribe when done. At the end of each update the engine has to prepare a list of events for each individual subscriber. Unsubscribing will help to reduce unnecessary work and improve performance.
```
unsubscribe();
```
Javascript Image Editor SDK - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/solutions/photo-editor/javascript/
CESDK/CE.SDK/Web Editor/Solutions/Photo Editor
# Javascript Image Editor SDK
The CreativeEditor SDK provides a powerful and intuitive solution designed for seamless photo editing directly in the browser.
This CE.SDK configuration is fully customizable, offering a range of features that cater to various use cases, from simple photo adjustments, image compositions with background removal, to programmatic editing at scale. Whether you are building a photo editing application for social media, e-commerce, or any other platform, the CE.SDK Javascript Image Editor provides the tools you need to deliver a best-in-class user experience.
[Explore Demo](https://img.ly/showcases/cesdk/photo-editor-ui/web)
##
Key Capabilities

### Transform
Easily perform operations like cropping, rotating, and resizing your design elements to achieve the perfect composition.

### Asset Management
Import and manage stickers, images, shapes, and other assets to build intricate and visually appealing designs.

### Text Editing
Add and style text blocks with a variety of fonts, colors, and effects, giving users the creative freedom to express themselves.

### Client-Side Processing
All editing operations are performed directly in the browser, ensuring fast performance without the need for server dependencies.

### Headless & Automation
Programmatically edit designs using the engine API, allowing for automated workflows and advanced integrations within your application.

### Extendible
Enhance functionality with plugins and custom scripts, making it easy to tailor the editor to specific needs and use cases.

### Customizable UI
Design and integrate custom user interfaces that align with your application’s branding and user experience requirements.

### Background Removal
Utilize the powerful background removal plugin to allow users to effortlessly remove backgrounds from images, entirely on the Client-Side.

### Filters & Effects
Choose from a wide range of filters and effects to add professional-grade finishing touches to photos, enhancing their visual appeal.

### Size Presets
Access a variety of size presets tailored for different use cases, including social media formats and print-ready dimensions.
##
Browser Support
The CE.SDK Design Editor is optimized for use in modern web browsers, ensuring compatibility with the latest versions of Chrome, Firefox, Edge, and Safari. See the full list of [supported browsers here](https://img.ly/docs/cesdk/faq/browser-support/).
##
Supported File Types
[IMG.LY](http://img.ly/)'s Creative Editor SDK enables you to load, edit, and save **MP4 files** directly in the browser without server dependencies.
The following file types can also be imported for use as assets during video editing:
* MP3
* MP4 (with MP3 audio)
* M4A
* AAC
* JPG
* PNG
* WEBP
Individual scenes or assets from the video can be exported as JPG, PNG, Binary, or PDF files.
##
Getting Started
If you're ready to start integrating CE.SDK into your Javascript application, check out the CE.SDK [Getting Started guide](https://img.ly/docs/cesdk/engine/quickstart/). In order to configure the editor for an image editing use case consult our [photo editor UI showcase](https://img.ly/showcases/cesdk/photo-editor-ui/web#c) and its [reference implementation](https://github.com/imgly/cesdk-web-examples/tree/main/showcase-photo-editor-ui/src/components/case/CaseComponent.jsx).
##
Understanding CE.SDK Architecture & API
The following sections provide an overview of the key components of the CE.SDK photo editor UI and its API architecture.
If you're ready to start integrating CE.SDK into your application, check out our [Getting Started guide](https://img.ly/docs/cesdk/engine/quickstart/) or explore the Essential Guides.
###
CreativeEditor Photo UI
The CE.SDK photo editor UI is a specific configuration of the CE.SDK which focuses the Editor UI to essential photo editing features. It further includes our powerful background removal plugin that runs entirely on the users device, saving on computing costs.
This configuration can be further modified to suit your needs, see the section on customization.
Designed for intuitive interaction, enabling users to create and edit designs with ease. Key components include:

* _Canvas_: The primary workspace where users interact with their photo content.
* _Dock_: Provides access to tools and assets that are not directly related to the selected image or block, often used for adding or managing assets.
* _Inspector Bar_: Controls properties specific to the selected block, such as size, rotation, and other adjustments.
* _Canvas Menu_: Provides block-specific settings and actions such as deletion or duplication.
* _Canvas Bar_: For actions affecting the canvas or scene as a whole such as adding pages. This is an alternative place for actions such as zoom or redo/undo.
* _Navigation Bar_: Offers global actions such as undo/redo, zoom controls, and access to export options.
Learn more about interacting with and customizing the photo editor UI in our design editor UI guide.
###
CreativeEngine
At the heart of CE.SDK is the CreativeEngine, which powers all rendering and design manipulation tasks. It can be used in headless mode or in combination with the CreativeEditor UI. Key features and APIs provided by CreativeEngine include:
* **Scene Management:** Create, load, save, and manipulate design scenes programmatically.
* **Block Manipulation:** Create and manage elements such as images, text, and shapes within the scene.
* **Asset Management:** Load and manage assets like images and SVGs from URLs or local sources.
* **Variable Management:** Define and manipulate variables for dynamic content within scenes.
* **Event Handling:** Subscribe to events such as block creation or selection changes for dynamic interaction.
##
API Overview
CE.SDK’s APIs are organized into several categories, each addressing different aspects of scene and content management. The engine API is relevant if you want to programmatically manipulate images to create or modify them at scale.
[**Scene API:**](https://img.ly/docs/cesdk/engine/api/scene/)
* **Creating and Loading Scenes**[:](https://img.ly/docs/cesdk/engine/guides/create-scene/)
```
engine.scene.create();
engine.scene.loadFromURL(url);
```
* **Zoom Control**[:](https://img.ly/docs/cesdk/engine/api/scene-zoom/#sceneapisetzoomlevel)
```
engine.scene.setZoomLevel(1.0);
engine.scene.zoomToBlock(blockId);
```
[**Block API:**](https://img.ly/docs/cesdk/engine/api/block/)
* **Creating Blocks**:
```
const block = engine.block.create('shapes/rectangle');
```
* **Setting Properties**:
```
engine.block.setColor(blockId, 'fill/color', { r: 1, g: 0, b: 0, a: 1 });
engine.block.setString(blockId, 'text/content', 'Hello World');
```
* **Querying Properties**:
```
const color = engine.block.getColor(blockId, 'fill/color');
const text = engine.block.getString(blockId, 'text/content');
```
[**Variable API:**](https://img.ly/docs/cesdk/engine/api/variables/)
* **Managing Variables**:
```
engine.variable.setString('myVariable', 'value');
const value = engine.variable.getString('myVariable');
```
[**Asset API:**](https://img.ly/docs/cesdk/engine/api/assets/#defining-a-custom-asset-source)
* **Managing Assets**:
```
engine.asset.add('image', 'https://example.com/image.png');
```
[**Event API:**](https://img.ly/docs/cesdk/engine/api/events/)
* **Subscribing to Events**:
```
engine.scene.onActiveChanged(() => {
const newActiveScene = engine.scene.get();
});
```
###
Basic Automation Example
The following automation example shows how to turn an image block into a square format for a platform such as Instagram.
```
// Assuming you have an initialized engine and a selected block (which is an image block)
// Example dimensions
const newWidth = 1080; // Width in pixels
const newHeight = 1080; // Height in pixels
// Get the ID of the image block you want to resize
const imageBlockId = engine.block.findByType('image')[0];
// Resize the image block
engine.block.setWidth(imageBlockId, newWidth);
engine.block.setHeight(imageBlockId, newHeight);
// Optionally, you can ensure the content fills the new dimensions
engine.block.setContentFillMode(imageBlockId, 'Cover');
```
##
Customizing the CE.SDK Photo Editor
CE.SDK provides extensive customization options, allowing you to tailor the UI and functionality to meet your specific needs. This can range from basic configuration settings to more advanced customizations involving callbacks and custom elements.
###
Basic Customizations
* **Configuration Object:** Customize the editor’s appearance and functionality by passing a configuration object during initialization.
```
const config = {
baseURL: 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.18.0/assets',
license: 'your-license-key',
locale: 'en',
theme: 'light'
};
```
* **Localization:** Adjust the editor’s language and labels to support different locales.
```
const config = {
i18n: {
en: {
'libraries.ly.img.insert.text.label': 'Add Caption'
}
}
};
```
* **Custom Asset Sources:** Serve custom sticker or shape assets from a remote URL.
###
UI Customization Options
* **Theme:** Choose between 'dark' or 'light' themes.
```
const config = {
theme: 'dark'
};
```
* **UI Components:** Enable or disable specific UI components as per your application’s needs.
```
const config = {
ui: {
elements: {
toolbar: true,
inspector: false
}
}
};
```
##
Advanced Customizations
For deeper customization, [explore the range of APIs](https://img.ly/docs/cesdk/ui/customization/) available for extending the functionality of the photo editor. You can customize the order of components, add new UI elements, and even develop your own plugins to introduce new features.
##
Plugins
For cases where encapsulating functionality for reuse is necessary, plugins provide an effective solution. Use our [guide on building plugins](https://img.ly/docs/cesdk/ui/customization/plugins/) to get started, or explore existing plugins like **Background Removal** and **Vectorizer**.
##
Framework Support
CreativeEditor SDK’s photo editor is compatible with any Javascript including, React, Angular, Vue.js, Svelte, Blazor, Next.js, Typescript. It is also compatible with desktop and server-side technologies such as electron, PHP, Laravel and Rails.
[
Headless
](/docs/cesdk/engine/quickstart/)[
React
](/docs/cesdk/ui/quickstart?framework=react)[
Angular
](/docs/cesdk/ui/quickstart?framework=angular)[
Vue
](/docs/cesdk/ui/quickstart?framework=vue)[
Svelte
](/docs/cesdk/ui/quickstart?framework=svelte)[.electron\_svg\_\_cls-1{fill:#2b2e3a;fill-rule:evenodd}.electron\_svg\_\_cls-2{fill:#9feaf9}
Electron
](/docs/cesdk/ui/quickstart?framework=electron)[
Next.js
](/docs/cesdk/ui/quickstart?framework=nextjs)[
Node.js
](/docs/cesdk/ui/quickstart?platform=node)
Ready to get started?
With a free trial and pricing that fits your needs, it's easy to find the best solution for your product.
[Free Trial](https://img.ly/forms/free-trial)
### 500M+
video and photo creations are powered by IMG.LY every month

[
Previous
Vue.js
](/docs/cesdk/ui/solutions/video-editor/vuejs/)[
Next
React
](/docs/cesdk/ui/solutions/photo-editor/react/)
Placeholder - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/api/block-placeholder/?platform=web&language=javascript
# Placeholder
In this example, we will demonstrate how to use the [CreativeEditor SDK](https://img.ly/products/creative-sdk)'s CreativeEngine to manage placeholder behavior and controls through the block API.
##
Setup
This example uses the headless CreativeEngine. See the [Setup](/docs/cesdk/engine/quickstart/) article for a detailed guide. To get started right away, you can also access the `block` API within a running CE.SDK instance via `cesdk.engine.block`. Check out the [APIs Overview](../) to see that illustrated in more detail.
##
Placeholder Behavior and Controls
```
supportsPlaceholderBehavior(id: DesignBlockId): boolean
```
Checks whether the block supports placeholder behavior.
* `block`: The block to query.
* Returns True, if the block supports placeholder behavior.
```
if (engine.block.supportsPlaceholderBehavior(block)) {
```
```
setPlaceholderBehaviorEnabled(id: DesignBlockId, enabled: boolean): void
```
Enable or disable the placeholder behavior for a block.
* `id`: The block whose placeholder behavior should be enabled or disabled.
* `enabled`: Whether the placeholder behavior should be enabled or disabled.
```
engine.block.setPlaceholderBehaviorEnabled(block, true);
```
```
isPlaceholderBehaviorEnabled(id: DesignBlockId): boolean
```
Query whether the placeholder behavior for a block is enabled.
* `id`: The block whose placeholder behavior state should be queried.
* Returns the enabled state of the placeholder behavior.
```
const placeholderBehaviorIsEnabled =
```
```
setPlaceholderEnabled(id: DesignBlockId, enabled: boolean): void
```
Enable or disable the placeholder function for a block.
* `id`: The block whose placeholder function should be enabled or disabled.
* `enabled`: Whether the function should be enabled or disabled.
```
engine.block.setPlaceholderEnabled(block, true);
```
```
isPlaceholderEnabled(id: DesignBlockId): boolean
```
Query whether the placeholder function for a block is enabled.
* `id`: The block whose placeholder function state should be queried.
* Returns the enabled state of the placeholder function.
```
const placeholderIsEnabled = engine.block.isPlaceholderEnabled(block);
```
```
supportsPlaceholderControls(id: DesignBlockId): boolean
```
Checks whether the block supports placeholder controls.
* `block`: The block to query.
* Returns True, if the block supports placeholder controls.
```
if (engine.block.supportsPlaceholderControls(block)) {
```
```
setPlaceholderControlsOverlayEnabled(id: DesignBlockId, enabled: boolean): void
```
Enable or disable the visibility of the placeholder overlay pattern for a block.
* `block`: The block whose placeholder overlay should be enabled or disabled.
* `enabled`: Whether the placeholder overlay should be shown or not.
* Returns An empty result on success, an error otherwise.
```
engine.block.setPlaceholderControlsOverlayEnabled(block, true);
```
```
isPlaceholderControlsOverlayEnabled(id: DesignBlockId): boolean
```
Query whether the placeholder overlay pattern for a block is shown.
* `block`: The block whose placeholder overlay visibility state should be queried.
* Returns An error if the block was invalid, otherwise the visibility state of the block's placeholder overlay pattern.
```
const overlayEnabled =
```
```
setPlaceholderControlsButtonEnabled(id: DesignBlockId, enabled: boolean): void
```
Enable or disable the visibility of the placeholder button for a block.
* `block`: The block whose placeholder button should be shown or not.
* `enabled`: Whether the placeholder button should be shown or not.
* Returns An empty result on success, an error otherwise.
```
engine.block.setPlaceholderControlsButtonEnabled(block, true);
```
```
isPlaceholderControlsButtonEnabled(id: DesignBlockId): boolean
```
Query whether the placeholder button for a block is shown.
* `block`: The block whose placeholder button visibility state should be queried.
* Returns An error if the block was invalid, otherwise
```
const buttonEnabled = engine.block.isPlaceholderControlsButtonEnabled(block);
```
Adding Color Libraries - CE.SDK Docs - CE.SDK | IMG.LY Docs [web/undefined/js] https://img.ly/docs/cesdk/ui/guides/custom-color-libraries/?platform=web&language=js
# Adding Color Libraries to the CreativeEditor SDK
In this example, we will show you how to configure the [CreativeEditor SDK](https://img.ly/products/creative-sdk). CE.SDK has full support for custom color libraries. These appear in the color picker, and allow users to choose from pre-defined sets of colors to use in their design. They can include RGB colors, CMYK colors, and spot colors. They can be used to support your users with a variety of palettes, brand colors, or color books for printing. Note that many providers of color books (e.g. Pantone) require a license to use their data.
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/configure-colorlibraries?title=IMG.LY%27s+CE.SDK%3A+Configure+Colorlibraries&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/configure-colorlibraries).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/configure-colorlibraries?title=IMG.LY%27s+CE.SDK%3A+Configure+Colorlibraries&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/configure-colorlibraries)
##
General Concept
Color libraries are implemented as asset sources, containing individual colors as assets. Each color library is identified by a source ID, a unique string used when establishing and configuring the source.
##
Defining Colors
To integrate colors into a library, we need to supply them in the shape of an `AssetDefinition`. For more details on the `AssetDefinition` type, please consult our Guide on [integrating custom asset sources](/docs/cesdk/engine/guides/integrate-a-custom-asset-source/).
For colors, we are utilizing the `payload` key, providing an `AssetColor` to the `AssetPayload.color` property. In this example, we define one color for every type; see below for the applicable types:
###
`AssetRGBColor`
Member
Type
Description
Member
colorSpace
Type
`'sRGB'`
Description
Member
r, g, b, a
Type
`number`
Description
Red, green, blue, and alpha color channel components
###
`AssetCMYKColor`
Member
Type
Description
Member
colorSpace
Type
`'CMYK'`
Description
Member
c, m, y, k
Type
`number`
Description
Cyan, magenta, yellow, and black color channel components
###
`AssetSpotColor`
Member
Type
Description
Member
colorSpace
Type
`'SpotColor'`
Description
Member
name
Type
`string`
Description
Unique identifier of this spot color. Make sure this matches the standardized name of the spot color when using color books like those supplied by Pantone.
Member
externalReference
Type
`string`
Description
Reference to the source of this spot color (e.g. name of color book), if applicable.
Member
representation
Type
`AssetRGBColor` | `AssetCMYKColor`
Description
Note that spot colors also require a CMYK or RGB color representation, which is used to display an approximate color on screen during editing.
In this example, we are defining one of each color type, and add them to a single library, for demonstration purposes. Although there is no technical requirement to do so, it is recommended to separate different color types (RGB, CMYK, Spot) into separate libraries, to avoid confusing users.
```
const colors = [
{
id: 'RGB Murky Magenta',
label: { en: 'RGB Murky Magenta' },
tags: { en: ['RGB', 'Murky', 'Magenta'] },
payload: {
color: {
colorSpace: 'sRGB',
r: 0.65,
g: 0.3,
b: 0.65,
a: 1
}
}
},
{
id: 'Spot Goo Green',
label: { en: 'Spot Goo Green' },
tags: { en: ['Spot', 'Goo', 'Green'] },
payload: {
color: {
colorSpace: 'SpotColor',
name: 'Spot Goo Green',
externalReference: 'My Spot Color Book',
representation: {
colorSpace: 'sRGB',
r: 0.7,
g: 0.98,
b: 0.13,
a: 1
}
}
}
},
{
id: 'CMYK Baby Blue',
label: { en: 'CMYK Baby Blue' },
tags: { en: ['CMYK', 'Baby', 'Blue'] },
payload: {
color: {
colorSpace: 'CMYK',
c: 0.5,
m: 0,
y: 0,
k: 0
}
}
}
];
```
##
Configuration
###
Labels
To show the correct labels for your color library, provide a matching i18n key in your configuration. Color libraries use keys in the format `libraries..label` to look up the correct label.
```
i18n: {
en: {
'libraries.myCustomColors.label': 'Custom Color Library'
}
},
```
###
Order
Color libraries appear in the color picker in a specific order. To define this order, provide an array of source IDs to the `ui.colorLibraries` configuration key. The special source `'ly.img.colors.defaultPalette'` is used to place the default palette (See: [Configuring the Default Color Palette](/docs/cesdk/ui/configuration/ui/#configuring-the-default-color-palette)). If you want to hide this default palette, just remove the key from this array.
```
colorLibraries: ['ly.img.colors.defaultPalette', 'myCustomColors'],
```
##
Adding the library
After initializing the engine, use the Asset API to add a local asset source using `addLocalSource`. Afterwards, add colors to the new source using `addAssetToSource`. Make sure to use the same source ID as is referenced in the configuration. See also [Local Asset Sources](/docs/cesdk/engine/guides/integrate-a-custom-asset-source/#local-asset-sources) in our Guide on [Integrating custom asset sources](/docs/cesdk/engine/guides/integrate-a-custom-asset-source/)
```
cesdk.engine.asset.addLocalSource('myCustomColors', ['text/plain']);
for (const asset of colors) {
cesdk.engine.asset.addAssetToSource('myCustomColors', asset);
}
```
Javascript Creative Editor SDK - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/solutions/design-editor/javascript/
CESDK/CE.SDK/Web Editor/Solutions/Design Editor
# Javascript Creative Editor SDK
CreativeEditor SDK offers a fully-featured JavaScript library for creating and editing rich visual designs directly within the browser.
This CE.SDK configuration is highly customizable and extendable, providing a comprehensive set of design editing features such as templating, layout management, asset integration, and more. All operations are executed directly in the browser, without the need for server dependencies.
[Explore Demo](https://img.ly/showcases/cesdk/default-ui/web)
##
Key Capabilities of the JavaScript Creative Editor SDK

### Transform
Perform operations like cropping, rotating, and resizing design elements.

### Templating
Create and apply design templates with placeholders and text variables for dynamic content.

### Placeholders & Lockable Design
Constrain templates to guide your users’ design and ensure brand consistency.

### Asset Management
Import and manage images, shapes, and other assets to build your designs.

### Design Collage
Arrange multiple elements on a single canvas to create complex layouts.

### Text Editing
Add and style text blocks with various fonts, colors, and effects.

### Client-Side Processing
All design editing operations are executed directly in the browser, with no need for server dependencies.

### Headless & Automation
Programmatically edit designs within your React application using the engine API.

### Extendible
Hook into the engine API and editor events to implement custom features.

### Customizable UI
Build and integrate custom UIs tailored to your application’s design needs.

### Background Removal
This plugin makes it easy to remove the background from images running entirely in the browser.

### Optimized for Print
Perfect for web-to-print use cases, supporting spot colors and cut-outs.
##
Browser Support
The CE.SDK Design Editor is optimized for use in modern web browsers, ensuring compatibility with the latest versions of Chrome, Firefox, Edge, and Safari. See the full list of [supported browsers here](https://img.ly/docs/cesdk/faq/browser-support/).
##
Supported File Types
Creative Editor SDK supports loading, editing, and saving various image formats directly in the browser, without server dependencies. The supported file types include:
* JPG
* PNG
* SVG
* WEBP
Individual assets or entire designs can be exported as PDF, JPG, PNG, or SVG files.
##
Understanding CE.SDK Architecture & API
The following sections provide an overview of the key components of the CE.SDK design editor UI and its API architecture.
If you're ready to start integrating CE.SDK into your JavaScript application, check out our [Getting Started guide](https://img.ly/docs/cesdk/engine/quickstart/) or dive into the [guides](https://img.ly/docs/cesdk/ui/guides/).
###
CreativeEditor Design UI
The CE.SDK design UI is built for intuitive design creation and editing. Here are the main components and customizable elements within the UI:

* **Canvas:** The core interaction area for design content.
* **Dock:** Entry point for interactions not directly related to the selected design block, often used for accessing asset libraries.
* **Canvas Menu:** Access block-specific settings like duplication or deletion.
* **Inspector Bar:** Manage block-specific functionalities, such as adjusting properties of the selected block.
* **Navigation Bar:** Handles global scene actions like undo/redo and zoom.
* **Canvas Bar:** Provides tools for managing the overall canvas, such as adding pages or controlling zoom.
* **Layer Panel:** Manage the stacking order and visibility of design elements.
Learn more about interacting with and manipulating design controls in our design editor UI guide.
###
CreativeEngine
CreativeEngine is the core of CE.SDK, responsible for managing the rendering and manipulation of design scenes. It can be used in headless mode or integrated with the CreativeEditor UI. Below are key features and APIs provided by the CreativeEngine:
* **Scene Management:** Create, load, save, and modify design scenes programmatically.
* **Block Manipulation:** Create and manage design elements, such as shapes, text, and images.
* **Asset Management:** Load assets like images and SVGs from URLs or local sources.
* **Variable Management:** Define and manipulate variables within scenes for dynamic content.
* **Event Handling:** Subscribe to events like block creation or updates for dynamic interaction.
##
API Overview
The APIs of CE.SDK are grouped into several categories, reflecting different aspects of scene management and manipulation.
[**Scene API:**](https://img.ly/docs/cesdk/engine/api/scene/)
* **Creating and Loading Scenes:**
```
engine.scene.create();
engine.scene.loadFromURL(url);
```
* **Zoom Control:**
```
engine.scene.setZoomLevel(1.0);
engine.scene.zoomToBlock(blockId);
```
[**Block API:**](https://img.ly/docs/cesdk/engine/api/block/)
* **Creating Blocks**:
```
const block = engine.block.create('shapes/rectangle');
```
* **Setting Properties**:
```
engine.block.setColor(blockId, 'fill/color', { r: 1, g: 0, b: 0, a: 1 });
engine.block.setString(blockId, 'text/content', 'Hello World');
```
* **Querying Properties**:
```
const color = engine.block.getColor(blockId, 'fill/color');
const text = engine.block.getString(blockId, 'text/content');
```
[**Variable API:**](https://img.ly/docs/cesdk/engine/api/variables/)
Variables allow dynamic content within scenes to programmatically create variations of a design.
* **Managing Variables**:
```
engine.variable.setString('myVariable', 'value');
const value = engine.variable.getString('myVariable');
```
[**Asset API:**](https://img.ly/docs/cesdk/engine/api/assets/#defining-a-custom-asset-source)
* **Managing Assets**:
```
engine.asset.add('image', 'https://example.com/image.png');
```
[**Event API:**](https://img.ly/docs/cesdk/engine/api/events/)
* **Subscribing to Events**:
```
// Subscribe to scene changes
engine.scene.onActiveChanged(() => {
const newActiveScene = engine.scene.get();
});
```
##
Customizing the JavaScript Creative Editor
CE.SDK provides extensive customization options to adapt the UI to various use cases. These options range from simple configuration changes to more advanced customizations involving callbacks and custom elements.
###
Role-Based Customization
Switch between "Creator" and "Adopter" roles to control the editing experience. The "Creator" role allows setting constraints on template elements, while the "Adopter" role is focused on adapting these elements.
* **Creator:** Set constraints and manage template settings.
* **Adopter:** Edit elements within the bounds set by the Creator.
###
Basic Customizations
* **Configuration Object:** When initializing the CreativeEditor, you can pass a configuration object that defines basic settings such as the base URL for assets, the language, theme, and license key.
```
const config = {
baseURL: 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.18.0/assets',
license: 'your-license-key',
locale: 'en',
theme: 'light'
};
```
* **Localization:** Customize the language and labels used in the editor to support different locales.
```
const config = {
i18n: {
en: {
variables: {
my_custom_variable: {
label: 'Custom Label'
}
}
}
}
};
```
* [Custom Asset Sources](https://img.ly/docs/cesdk/engine/api/assets/#defining-a-custom-asset-source): Serve custom image or SVG assets from a remote URL.
###
UI Customization Options
* **Theme:** Choose between predefined themes such as 'dark' or 'light'.
```
const config = {
theme: 'dark'
};
```
* **UI Components:** Enable or disable specific UI components based on your requirements.
```
const config = {
ui: {
elements: {
toolbar: true,
inspector: false
}
}
};
```
##
Advanced Customizations
Learn more about extending editor functionality and customizing its UI to your use case by consulting our in-depth [customization guide](https://img.ly/docs/cesdk/ui/customization/guides/). Here is an overview of the APIs and components available to you.
###
Order APIs
Customization of the web editor's components and their order within these locations is managed through specific Order APIs, allowing the addition, removal, or reordering of elements. Each location has its own Order API, e.g., `setDockOrder`, `setCanvasMenuOrder`, `setInspectorBarOrder`, `setNavigationBarOrder`, and `setCanvasBarOrder`.
###
Layout Components
CE.SDK provides special components for layout control, such as `ly.img.separator` for separating groups of components and `ly.img.spacer` for adding space between components.
###
Registration of New Components
Custom components can be registered and integrated into the web editor using builder components like buttons, dropdowns, and inputs. These components can replace default ones or introduce new functionalities, deeply integrating custom logic into the editor.
###
Feature API
The Feature API enables conditional display and functionality of components based on the current context, allowing for dynamic customization. For example, you can hide certain buttons for specific block types.
##
Plugins
You can customize the CE.SDK web editor during its initialization using the APIs outlined above. For many use cases, this will be adequate. However, there are times when you might want to encapsulate functionality for reuse. This is where plugins become useful. Follow our [guide on building your own plugins](https://img.ly/docs/cesdk/ui/customization/plugins/) to learn more or check out one of the plugins we built using this API:
* [**Background Removal**](https://img.ly/docs/cesdk/ui/customization/plugins/backgroundRemoval/): Adds a button to the canvas menu to remove image backgrounds.
* [**Vectorizer**](https://img.ly/docs/cesdk/ui/customization/plugins/vectorizer/): Transform your pixel-based images images into scalable vector graphics.
##
Framework Support
CreativeEditor SDK’s video editing library is compatible with any Javascript including, React, Angular, Vue.js, Svelte, Blazor, Next.js, Typescript. It is also compatible with desktop and server-side technologies such as electron, PHP, Laravel and Rails.
[
Headless
](/docs/cesdk/engine/quickstart/)[
React
](/docs/cesdk/ui/solutions/design-editor/react/)[
Angular
](/docs/cesdk/ui/solutions/design-editor/angular/)[
Vue
](/docs/cesdk/ui/solutions/design-editor/vuejs/)[
Svelte
](/docs/cesdk/ui/quickstart?framework=svelte)[.electron\_svg\_\_cls-1{fill:#2b2e3a;fill-rule:evenodd}.electron\_svg\_\_cls-2{fill:#9feaf9}
Electron
](/docs/cesdk/ui/quickstart?framework=electron)[
Next.js
](/docs/cesdk/ui/quickstart?framework=nextjs)[
Node.js
](/docs/cesdk/ui/quickstart?platform=node)
Ready to get started?
With a free trial and pricing that fits your needs, it's easy to find the best solution for your product.
[Free Trial](https://img.ly/forms/free-trial)
### 500M+
video and photo creations are powered by IMG.LY every month

[
Previous
Overview
](/docs/cesdk/ui/solutions/)[
Next
React
](/docs/cesdk/ui/solutions/design-editor/react/)
Configure the Engine to use Assets served from your own Servers - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/guides/assets-served-from-your-own-servers/?platform=web&language=javascript
Platform
Web
iOS
Catalyst
macOS
Android
Language
JavaScript
Platform:
Web
Language:
JavaScript
# Configure the Engine to use Assets served from your own Servers
Learn how to serve assets from your own servers in the Engine.
In this example, we explain how to configure the Creative Engine to use assets hosted on your own servers. While we serve all assets from our own CDN by default, it is highly recommended to serve the assets from your own servers in a production environment.
##
Prerequisites
* [Get the latest stable version of **Node.js & NPM**](https://www.npmjs.com/get-npm)
* (Optional): [Get the latest stable version of **Yarn**](https://yarnpkg.com/getting-started)
##
1\. Add the CreativeEngine to Your Project
```
npm install --save @cesdk/engine@1.43.0
```
##
2\. Decide what Assets you need
We offer two sets of assets:
* _Core_ Assets - Files required for the engine to function.
* _Default_ Assets - Demo assets to quickstart your development.
###
⚠️ Warning
Prior to `v1.10.0`, the `CreativeEngine` and `CreativeEditorSDK` would load referenced default assets from the `assets/extensions/*` directories and hardcode them as `/extensions/…` references in serialized scenes.
To **maintain compatibility** for such scenes, make sure you're still serving version v1.9.2 the `/extensions` directory from your `baseURL`. You can [download them from our CDN](https://cdn.img.ly/packages/imgly/cesdk-engine/1.9.2/assets/extensions.zip).
##
3\. Register IMG.LY's default assets
If you want to use our default asset sources in your integration, call `CreativeEngine.addDefaultAssetSources({ baseURL?: string, excludeAssetSourceIds?: string[] }): void`. Right after initialization:
```
CreativeEngine.init(config).then((engine) => {
engine.addDefaultAssetSources();
});
```
This call adds IMG.LY's default asset sources for stickers, vectorpaths and filters to your engine instance. By default, these include the following source ids:
* `'ly.img.sticker'` - Various stickers.
* `'ly.img.vectorpath'` - Shapes and arrows.
* `'ly.img.filter.lut'` - LUT effects of various kinds.
* `'ly.img.filter.duotone'` - Color effects of various kinds.
* `'ly.img.colors.defaultPalette'` - Default color palette.
* `'ly.img.effect'` - Default effects.
* `'ly.img.blur'` - Default blurs.
* `'ly.img.typeface'` - Default typefaces.
If you don't specify a `baseURL` option, the assets are parsed and served from the IMG.LY CDN. It's it is highly recommended to serve the assets from your own servers in a production environment, if you decide to use them. To do so, follow the steps below and pass a `baseURL` option to `addDefaultAssetSources`. If you only need a subset of the IDs above, use the `excludeAssetSourceIds` option to pass a list of ignored Ids.
##
4\. Copy Assets
Copy the CreativeEngine `core`, `demo`, `i18n`, `ui`, etc. asset folders to your application's asset folder. The name of the folder depends on your setup and the used bundler, but it's typically a folder called `assets` or `public` in the project root.
```
cp -r ./node_modules/@cesdk/engine/assets public/
```
Furthermore, if you are using our IMG.LY default assets, download them from [our CDN](https://cdn.img.ly/assets/v3/IMGLY-Assets.zip) and extract them to your public directory as well.
If you deploy the site that embeds the CreativeEngine together with all its assets and static files, this might be all you need to do for this step.
In different setups, you might need to upload this folder to your CDN.
##
5\. Configure the CreativeEngine to use your self-hosted assets
Next, we need to configure the SDK to use our local assets instead of the ones served via our CDN. There are two configuration options that are relevant for this:
* `baseURL` should ideally point to the `assets` folder that was copied in the previous step.
This can be either an absolute URL, or a path. A path will be resolved using the `window.location.href` of the page where the CreativeEngine is embedded. By default `baseURL` is set to our CDN.
* `core.baseURL` must point to the folder containing the core sources and data file for the CreativeEngine. Defaults to `${baseURL}/core`
This can be either an absolute URL, or a relative path. A relative path will be resolved using the the previous `baseURL`. By default, `core.baseURL` is set to `core/`.
Normally you would simply serve the assets directory from the previous step. That directory already contains the `core` folder, and this setting does not need to be changed. For highly customized setups that separate hosting of the WASM files from the hosting of other assets that are used inside scenes, you can set this to a different URL.
* `CreativeEngine.addDefaultAssetSources` offers a `baseURL` option, that needs to be set to an absolute URL.
The given URL will be used to lookup the asset definitions from `{{baseURL}}//content.json` and for all file references, like `{{baseURL}}//images/example.png`. By default, default sources parse and reference assets from `https://cdn.img.ly/assets/v3`.
```
const config = {
...
// Specify baseURL for all relative URLs.
baseURL: '/assets' // or 'https://cdn.mydomain.com/assets'
core: {
// Specify location of core assets, required by the engine.
baseURL: 'core/'
},
...
};
// Setup engine and add default sources served from your own server.
CreativeEngine.init(config).then((engine) => {
engine.addDefaultAssetSources({ baseURL: 'https://cdn.mydomain.com/assets'})
})
```
##
Versioning of the WASM assets
The files that the CreativeEngine loads from `core.baseURL` (`.wasm` and`.data` files, and the `worker-host.js`) are changing between different versions of the CreativeEngine. You need to ensure that after a version update, you update your copy of the assets.
The filenames of these assets will also change between updates. This makes it safe to store different versions of these files in the same folder during migrations, as the CreativeEngine will always locate the correct files using the unique filenames.
It also means that if you forget to copy the new assets, the CreativeEngine will fail to load them during initialization and abort with an Error message on the console. Depending on your setup this might only happen in your production or staging environments, but not during development where the assets might be served from a local server. Thus we recommend to ensure that copying of the assets is taken care of by your automated deployments and not performed manually.
[
Previous
Using the Camera
](/docs/cesdk/engine/guides/using-camera/)[
Next
Adding Custom Asset Sources
](/docs/cesdk/engine/guides/integrate-a-custom-asset-source/)
Creating a Scene From an HTMLCanvas - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/guides/create-scene-from-canvas/?platform=web&language=javascript
# Creating a Scene From an HTMLCanvas
In this example, we will show you how to initialize the [CreativeEditor SDK](https://img.ly/products/creative-sdk) with an initial image provided from a canvas.
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-create-scene-from-image-canvas?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Create+Scene+From+Image+Canvas&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-create-scene-from-image-canvas).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-create-scene-from-image-canvas?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Create+Scene+From+Image+Canvas&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-create-scene-from-image-canvas)
Starting from an existing image allows you to use the editor for customizing individual assets. This is done by using `engine.scene.createFromImage(url: string, dpi = 300, pixelScaleFactor = 1): Promise` and passing a URL as argument. The `dpi` argument sets the dots per inch of the scene. The `pixelScaleFactor` sets the display's pixel scale factor.
To use the image drawn by a canvas as the initial image, acquire a `dataURL` containing the canvas contents via `canvas.toDataURL()`.
```
const dataURL = canvas.toDataURL();
```
Use the created URL as a source for the initial image.
```
let scene = await engine.scene.createFromImage(dataURL);
```
We can retrieve the graphic block id of this initial image using `cesdk.engine.block.findByType(type: ObjectType): number[]`. Note that that function returns an array. Since there's only a single graphic block in the scene, the block is at index `0`.
```
// Find the automatically added graphic block with an image fill in the scene.
const block = engine.block.findByType('graphic')[0];
```
We can then manipulate and modify this block. Here we modify its opacity with `cesdk.engine.block.setOpacity(id: number, opacity: number): void`. See [Modifying Scenes](/docs/cesdk/engine/guides/blocks/) for more details.
```
// Change its opacity.
engine.block.setOpacity(block, 0.5);
```
When starting with an initial image, the scenes page dimensions match the given image, and the scene is configured to be in pixel design units.
To later save your scene, see [Saving Scenes](/docs/cesdk/engine/guides/save-scene/).
Groups - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/api/block-groups/?platform=web&language=javascript
# Groups
In this example, we will show you how to use the [CreativeEditor SDK](https://img.ly/products/creative-sdk)'s CreativeEngine to group blocks through the `block` API. Groups form a cohesive unit.
##
Setup
This example uses the headless CreativeEngine. See the [Setup](/docs/cesdk/engine/quickstart/) article for a detailed guide. To get started right away, you can also access the `block` API within a running CE.SDK instance via `cesdk.engine.block`. Check out the [APIs Overview](../) to see that illustrated in more detail.
##
Grouping
Multiple blocks can be grouped together to form a cohesive unit. A group being a block, it can itself be part of a group.
####
What cannot be grouped
* A scene
* A block that already is part of a group
```
isGroupable(ids: DesignBlockId[]): boolean
```
Confirms that a given set of blocks can be grouped together.
* `ids`: An array of block ids.
* Returns Whether the blocks can be grouped together.
```
const groupable = engine.block.isGroupable([member1, member2])
```
```
group(ids: DesignBlockId[]): DesignBlockId
```
Group blocks together.
* `ids`: A non-empty array of block ids.
* Returns The block id of the created group.
```
const group = engine.block.group([member1, member2]);
```
```
ungroup(id: DesignBlockId): void
```
Ungroups a group.
* `id`: The group id from a previous call to `group`.
```
engine.block.ungroup(group);
```
```
enterGroup(id: DesignBlockId): void
```
Changes selection from selected group to a block within that group. Nothing happens if `group` is not a group. Required scope: 'editor/select'
* `id`: The group id from a previous call to `group`.
```
engine.block.enterGroup(group);
```
```
enterGroup(id: DesignBlockId): void
```
Changes selection from selected group to a block within that group. Nothing happens if `group` is not a group. Required scope: 'editor/select'
* `id`: The group id from a previous call to `group`.
```
engine.block.enterGroup(group);
```
```
exitGroup(id: DesignBlockId): void
```
Changes selection from a group's selected block to that group. Nothing happens if the `id` is not part of a group. Required scope: 'editor/select'
* `id`: A block id.
```
engine.block.exitGroup(member1);
```
Load Scenes from a Remote URL - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/guides/load-scene-from-url/?platform=web&language=javascript
# Load Scenes from a Remote URL
In this example, we will show you how to load scenes from a remote URL with the [CreativeEditor SDK](https://img.ly/products/creative-sdk).
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-load-scene-from-remote?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Load+Scene+From+Remote&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-load-scene-from-remote).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-load-scene-from-remote?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Load+Scene+From+Remote&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-load-scene-from-remote)
Loading an existing scene allows resuming work on a previous session or adapting an existing template to your needs. This can be done by fetching a scene file or an archive file from a URL.
####
Warning
Saving a scene can be done as a either _scene file_ or as an _archive file_ (c.f. [Saving scenes](/docs/cesdk/engine/guides/save-scene/)). A _scene file_ does not include any fonts or images. Only the source URIs of assets, the general layout, and element properties are stored. When loading scenes in a new environment, ensure previously used asset URIs are available. Conversely, an _archive file_ contains within it the scene's assets and references them as relative URIs.
Determine a URL that points to a scene binary string.
```
const sceneUrl =
'https://cdn.img.ly/assets/demo/v1/ly.img.template/templates/cesdk_postcard_1.scene';
```
We can then pass that string to the `engine.scene.loadFromURL(url: string): Promise` function. The editor will reset and present the given scene to the user. The function is asynchronous and the returned `Promise` resolves if the scene load succeeded.
```
let scene = await engine.scene
.loadFromURL(sceneUrl)
.then(() => {
console.log('Load succeeded');
let text = engine.block.findByType('text')[0];
engine.block.setDropShadowEnabled(text, true);
})
.catch((error) => {
console.error('Load failed', error);
});
```
From this point on we can continue to modify our scene. In this example, assuming the scene contains a text element, we add a drop shadow to it. See [Modifying Scenes](/docs/cesdk/engine/guides/blocks/) for more details.
```
let text = engine.block.findByType('text')[0];
engine.block.setDropShadowEnabled(text, true);
```
Scene loads may be reverted using `cesdk.engine.editor.undo()`.
To later save your scene, see [Saving Scenes](/docs/cesdk/engine/guides/save-scene/).
Scene Lifecycle - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/api/scene-lifecycle/?platform=web&language=javascript
# Scene Lifecycle
In this example, we will show you how to use the [CreativeEditor SDK](https://img.ly/products/creative-sdk)'s CreativeEngine to save scenes through the `scene` API and export them to PNG.
At any time, the engine holds only a single scene. Loading or creating a scene will replace the current one.
##
Setup
This example uses the headless CreativeEngine. See the [Setup](/docs/cesdk/engine/quickstart/) article for a detailed guide. To get started right away, you can also access the `block` API within a running CE.SDK instance via `cesdk.engine.block`. Check out the [APIs Overview](../) to see that illustrated in more detail.
##
Creating a Scene
```
create(sceneLayout?: SceneLayout): DesignBlockId
```
Create a new design scene, along with its own camera.
* Returns The scene's handle.
```
let scene = engine.scene.create(layout);
```
```
type SceneLayout = 'Free' | 'VerticalStack' | 'HorizontalStack' | 'DepthStack'
```
The scene layout determines how the layout stack should layout its pages.
```
const layout = 'Free';
```
```
get(): DesignBlockId | null
```
Return the currently active scene.
* Returns The scene or null, if none was created yet.
```
scene = engine.scene.get();
```
```
createVideo(): DesignBlockId
```
Create a new scene in video mode, along with its own camera.
* Returns The scene's handle.
```
scene = engine.scene.createVideo();
```
```
getMode(): SceneMode
```
Get the current scene mode.
* Returns The current mode of the scene.
```
const mode = scene.getMode();
```
```
type SceneMode = 'Design' | 'Video'
```
The mode of the scene defines how the editor and playback should behave.
```
if (mode == 'Design') {
// Working with a static design…
}
```
```
createFromImage(url: string, dpi?: number, pixelScaleFactor?: number, sceneLayout?: SceneLayout, spacing?: number, spacingInScreenSpace?: boolean): Promise
```
Loads the given image and creates a scene with a single page showing the image. Fetching the image may take an arbitrary amount of time, so the scene isn't immediately available.
* `url`: The image URL.
* `dpi`: The scene's DPI.
* `pixelScaleFactor`: The display's pixel scale factor.
* Returns A promise that resolves with the scene ID on success or rejected with an error otherwise.
```
scene = await engine.scene.createFromImage(
'https://img.ly/static/ubq_samples/sample_4.jpg'
);
```
```
createFromVideo(url: string): Promise
```
Loads the given video and creates a scene with a single page showing the video. Fetching the video may take an arbitrary amount of time, so the scene isn't immediately available.
* `url`: The video URL.
* Returns A promise that resolves with the scene ID on success or rejected with an error otherwise.
```
scene = await engine.scene.createFromVideo(
'https://img.ly/static/ubq_video_samples/bbb.mp4'
);
```
##
Loading a Scene
```
loadFromString(sceneContent: string): Promise
```
Load the contents of a scene file.
* `sceneContent`: The scene file contents, a base64 string.
* Returns A handle to the loaded scene.
```
scene = engine.scene.loadFromString(SCENE_CONTENT);
```
```
loadFromURL(url: string): Promise
```
Load a scene from the URL to the scene file. The scene file will be fetched asynchronously by the engine. This requires continuous `render` calls on this engines instance.
* `url`: The URL of the scene file.
* Returns scene A promise that resolves once the scene was loaded or rejects with an error otherwise.
```
scene = await engine.scene.loadFromURL(
```
```
loadFromArchiveURL(url: string): Promise
```
Load a previously archived scene from the URL to the scene file. The scene file will be fetched asynchronously by the engine. This requires continuous `render` calls on this engines instance.
* `url`: The URL of the scene file.
* Returns scene A promise that resolves once the scene was loaded or rejects with an error otherwise.
```
scene = await engine.scene.loadFromArchiveURL('https://cdn.img.ly/assets/demo/v1/ly.img.template/templates/cesdk_postcard_1_scene.zip');
```
##
Saving a Scene
```
saveToString(allowedResourceSchemes?: string[]): Promise
```
Serializes the current scene into a string. Selection is discarded.
* Returns A promise that resolves with a string on success or an error on failure.
```
scene = await engine.scene.saveToString();
```
```
saveToArchive(): Promise
```
Saves the current scene and all of its referenced assets into an archive. The archive contains all assets, that were accessible when this function was called. Blocks in the archived scene reference assets relative from to the location of the scene file. These references are resolved when loading such a scene via `loadSceneFromURL`.
* Returns A promise that resolves with a Blob on success or an error on failure.
```
const archive = await engine.scene.saveToArchive();
```
##
Events
```
onActiveChanged: (callback: () => void) => (() => void)
```
Subscribe to changes to the active scene rendered by the engine.
* `callback`: This function is called at the end of the engine update, if the active scene has changed.
* Returns A method to unsubscribe.
```
const unsubscribe = engine.scene.onActiveChanged(() => {
const newActiveScene = engine.scene.get();
});
```
The Background Removal Plugin - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/customization/plugins/backgroundRemoval/
CESDK/CE.SDK/Web Editor/Customization/Plugins
# The Background Removal Plugin
Learn about IMG.LY's Background Removal plugin
This plugin introduces background removal for the CE.SDK editor, leveraging the power of the [background-removal-js library](https://github.com/imgly/background-removal-js). It integrates seamlessly with CE.SDK, provides users with an efficient tool to remove backgrounds from images directly in the browser with ease and no additional costs or privacy concerns.
##
Installation
You can install the plugin via npm or yarn. Use the following commands to install the package:
```
yarn add @imgly/plugin-background-removal-web
npm install @imgly/plugin-background-removal-web
```
##
Usage
Adding the plugin to CE.SDK will automatically add a background removal canvas menu entry for every block with an image fill.
```
import CreativeEditorSDK from '@cesdk/cesdk-js';
import BackgroundRemovalPlugin from '@imgly/plugin-background-removal-web';
const config = {
license: '',
callbacks: {
// Please note that the background removal plugin depends on an correctly
// configured upload. 'local' will work for local testing, but in
// production you will need something stable. Please take a look at:
// https://img.ly/docs/cesdk/ui/guides/upload-images/
onUpload: 'local'
}
};
const cesdk = await CreativeEditorSDK.create(container, config);
await cesdk.addDefaultAssetSources(),
await cesdk.addDemoAssetSources({ sceneMode: 'Design' }),
await cesdk.unstable_addPlugin(BackgroundRemovalPlugin());
await cesdk.createDesignScene();
```
##
Configuration
Multiple configuration options are available for the background removal plugin.
###
Adding Canvas Menu Component
After adding the plugin to CE.SDK, it will register a component that can be used inside the canvas menu. It is not added by default but can be included using the following configuration:
```
// Either pass a location via the configuration object, ...
BackgroundRemovalPlugin({
ui: { locations: 'canvasMenu' }
})
```
###
Configuration of `@imgly/background-removal`
By default, this plugin uses the `@imgly/background-removal-js` library to remove a background from the image fill. All configuration options from this underlying library can be used in this plugin.
[See the documentation](https://github.com/imgly/background-removal-js/tree/main/packages/web#advanced-configuration) for further information.
```
import BackgroundRemovalPlugin from '@imgly/plugin-background-removal-web';
[...]
await cesdk.unstable_addPlugin(BackgroundRemovalPlugin({
provider: {
type: '@imgly/background-removal',
configuration: {
publicPath: '...',
// All other configuration options that are passed to the bg removal
// library. See https://github.com/imgly/background-removal-js/tree/main/packages/web#advanced-configuration
}
}
}))
```
##
Performance
For optimal performance using the correct CORS headers is important. See the library documentation [here](https://github.com/imgly/background-removal-js/tree/main/packages/web#performance) for more details.
```
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp'
```
##
Custom Background Removal Provider
It is possible to declare a different provider for the background removal process.
```
BackgroundRemovalPlugin({
provider: {
type: 'custom',
// Some images have a source set defined which provides multiple images
// in different sizes.
processSourceSet: async (
// Source set for the current block sorted by the resolution.
// URI with the highest URI is first
sourceSet: {
uri: string;
width: number;
height: number;
}[],
) => {
// You should call the remove background method on every URI in the
// source set. Depending on your service or your algorithm, you
// have the following options:
// - Return a source set with a single image (will contradict the use-case of source sets and degrades the user experience)
// - Create a segmented mask and apply it to every image (not always available)
// - Create a new source set by resizing the resulting blob.
// In this example we will do the last case.
// First image has the highest resolution and might be the best
// candidate to remove the background.
const highestResolution = sourceSet[0];
const highestResolutionBlob = await removeBackground(highestResolution.uri);
const highestResolutionURI = await uploadBlob(highestResolutionBlob);
const remainingSources = await Promise.all(
sourceSet.slice(1).map((source) => {
// ...
const upload = uploadBlob(/* ... */)
return { ...source, uri: upload };
})
);
return [{ ...highestResolution, uri: highestResolutionURI }, remainingSources];
}
}
});
```
Depending on your use case or service you might end up with a blob that you want to upload by the configured upload handler of the editor. This might look like the following function:
```
async function uploadBlob(
blob: Blob,
initialUri: string,
cesdk: CreativeEditorSDK
) {
const pathname = new URL(initialUri).pathname;
const parts = pathname.split('/');
const filename = parts[parts.length - 1];
const uploadedAssets = await cesdk.unstable_upload(
new File([blob], filename, { type: blob.type })
);
const url = uploadedAssets.meta?.uri;
if (url == null) {
throw new Error('Could not upload processed fill');
}
return url;
}
```
[
Previous
Create Plugin
](/docs/cesdk/ui/customization/plugins/createPlugin/)[
Next
Vectorizer
](/docs/cesdk/ui/customization/plugins/vectorizer/)
Migrating to v1.19 - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/introduction/migration_1_19/?platform=web&language=javascript
Platform
Web
iOS
Catalyst
macOS
Android
Language
JavaScript
Platform:
Web
Language:
JavaScript
Version [v1.19](/docs/cesdk/faq/changelog/#v1190) of CreativeEngineSDK and CreativeEditorSDK introduces structural changes to many of the current design blocks, making them more composable and more powerful. Along with this update, there are mandatory license changes that require attention. This comes with a number of breaking changes. This document will explain the changes and describe the steps you need to take to adapt them to your setup.
##
**License Changes**
The `license` parameter is now required for CreativeEngineSDK and CreativeEditorSDK. This means that you will need to update your license parameter in the `CreativeEngine.init` and `CreativeEditorSDK.create` configuration object properties. There is also a new `userId`, an optional unique ID tied to your application's user. This helps us accurately calculate monthly active users (MAU). Especially useful when one person uses the app on multiple devices with a sign-in feature, ensuring they're counted once. Providing this aids in better data accuracy.
##
**Graphic Design Block**
A new generic `Graphic` design block with the type id `//ly.img.ubq/graphic` has been introduced, which forms the basis of the new unified block structure.
##
**Shapes**
Similar to how the fill of a block is a separate object which can be attached to and replaced on a design block, we have now introduced a similar concept for the shape of a block.
You use the new `createShape`, `getShape` and `setShape` APIs in order to define the shape of a design block. Only the new `//ly.img.ubq/graphic` block allows for its shape to be changed with these APIs.
The new available shape types are:
* `//ly.img.ubq/shape/rect`
* `//ly.img.ubq/shape/line`
* `//ly.img.ubq/shape/ellipse`
* `//ly.img.ubq/shape/polygon`
* `//ly.img.ubq/shape/star`
* `//ly.img.ubq/shape/vector_path`
The following block types are now removed in favor of using a `Graphic` block with one of the above mentioned shape instances:
* `//ly.img.ubq/shapes/rect`
* `//ly.img.ubq/shapes/line`
* `//ly.img.ubq/shapes/ellipse`
* `//ly.img.ubq/shapes/polygon`
* `//ly.img.ubq/shapes/star`
* `//ly.img.ubq/vector_path`
(The removed type ids use the plural “shapes” and the new shape types use the singular “shape”)
This structural change means that the shape-specific properties (e.g. the number of sides of a polygon) are not available on the design block any more but on the shape instances instead. You will have to add calls to `getShape` to get the instance id of the shape instance and then pass that to the property getter and setter APIs.
Also remember to change property key strings in the getter and setter calls from the plural `shapes/…` to the singular `shape/…` to match the new type identifiers.
##
**Image and Sticker**
Previously, `//ly.img.ubq/image` and `//ly.img.ubq/sticker` were their own high-level design block types. They do not support the fill APIs nor the effects APIs.
Both of these blocks are now removed in favor of using a `Graphic` block with an image fill (`//ly.img.ubq/fill/image`) and using the effects APIs instead of the legacy image block’s numerous effects properties.
At its core, the sticker block has always just been an image block that is heavily limited in its capabilities. You can not crop it, nor apply any effects to it. In order to replicate this difference as closely as possible in the new unified structure, more fine-grained scopes have been added. You can now limit the adopter’s ability to crop a block and to edit its appearance.
Note that since these scopes only apply to a user of the editor with the “Adopter” role, a “Creator” user will now have all of the same editing options for both images and for blocks that used to be stickers.
##
**Scopes**
The following is the list of changes to the design block scopes:
* (Breaking) The permission to crop a block was split from `content/replace` and `design/style` into a separate scope: `layer/crop`.
* Deprecated the `design/arrange` scope and renamed `design/arrange/move` → `layer/move``design/arrange/resize` → `layer/resize``design/arrange/rotate` → `layer/rotate``design/arrange/flip` → `layer/flip`
* Deprecated the `content/replace` scope. For `//ly.img.ubq/text` blocks, it is replaced with the new `text/edit` scope. For other blocks it is replaced with `fill/change`.
* Deprecated the `design/style` scope and replaced it with the following fine-grained scopes: `text/character`, `stroke/change`, `layer/opacity`, `layer/blendMode`, `layer/visibility`, `layer/clipping`, `appearance/adjustments`, `appearance/filter`, `appearance/effect`, `appearance/blur`, `appearance/shadow`
* Introduced `fill/change`, `stroke/change`, and `shape/change` scopes that control whether the fill, stroke or shape of a block may be edited by a user with an "Adopter" role.
* The deprecated scopes are automatically mapped to their new corresponding scopes by the scope APIs for now until they will be removed completely in a future update.
##
**Kind**
While the new unified block structure both simplifies a lot of code and makes design blocks more powerful, it also means that many of the design blocks that used to have unique type ids now all have the same generic `//ly.img.ubq/graphic` type, which means that calls to the `findByType` cannot be used to filter blocks based on their legacy type ids any more.
Simultaneously, there are many instances in which different blocks in the scene which might have the same type and underlying technical structure have different semantic roles in the document and should therefore be treated differently by the user interface.
To solve both of these problems, we have introduced the concept of a block “kind”. This is a mutable string that can be used to tag different blocks with a semantic label.
You can get the kind of a block using the `getKind` API and you can query blocks with a specific kind using the `findByKind` API.
CreativeEngine provides the following default kind values:
* `image`
* `video`
* `sticker`
* `scene`
* `camera`
* `stack`
* `page`
* `audio`
* `text`
* `shape`
* `group`
Unlike the immutable design block type id, you can change the kind of a block with the new `setKind` API.
It is important to remember that the underlying structure and properties of a design block are not strictly defined by its kind, since the kind, shape, fill and effects of a block can be changed independent of each other. Therefore, a user-interface should not make assumptions about available properties of a block purely based on its kind.
**Note**
Due to legacy reasons, blocks with the kind "sticker" will continue to not allow their contents to be cropped. This special behavior will be addressed and replaced with a more general-purpose implementation in a future update.
##
**Asset Definitions**
The asset definitions have been updated to reflect the deprecation of legacy block type ids and the introduction of the “kind” property.
In addition to the “blockType” meta property, you can now also define the `“shapeType”` ,`“fillType”` and `“kind”` of the block that should be created by the default implementation of the applyAsset function.
* `“blockType”` defaults to `“//ly.img.ubq/graphic”` if left unspecified.
* `“shapeType”` defaults to `“//ly.img.ubq/shape/rect”` if left unspecified
* `“fillType”` defaults to `“//ly.img.ubq/fill/color”` if left unspecified
Video block asset definitions used to specify the `“blockType”` as `“//ly.img.ubq/fill/video“`. The `“fillType”` meta asset property should now be used instead for such fill type ids.
##
**Automatic Migration**
CreativeEngine will always continue to support scene files that contain the now removed legacy block types. Those design blocks will be automatically replaced by the equivalent new unified block structure when the scene is loaded, which means that the types of all legacy blocks will change to `“//ly.img.ubq/graphic”`.
Note that this can mean that a block gains new capabilities that it did not have before. For example, the line shape block did not have any stroke properties, so the `hasStroke` API used to return `false`. However, after the automatic migration its `Graphic` design block replacement supports both strokes and fills, so the `hasStroke` API now returns `true` . Similarly, the image block did not support fills or effects, but the `Graphic` block does.
##
List of all Removed Block Type IDs
* `//ly.img.ubq/image`
* `//ly.img.ubq/sticker`
* `//ly.img.ubq/shapes/rect`
* `//ly.img.ubq/shapes/line`
* `//ly.img.ubq/shapes/ellipse`
* `//ly.img.ubq/shapes/polygon`
* `//ly.img.ubq/shapes/star`
* `//ly.img.ubq/vector_path`
##
**UI Configuration**
The configuration options for the legacy blocks have also been removed under `config.ui.elements.blocks` and a new configuration option for the `ly.img.ubq/graphic` block type have been introduced which will then define which UI controls to enable for graphic blocks (crop, filters, adjustments, effects, blur). This new configuration option follows the same structure as before.
Here is a list of the deprecated block configuration options:
* `//ly.img.ubq/image`
* `//ly.img.ubq/fill/video`
* `//ly.img.ubq/shapes/rect`
* `//ly.img.ubq/shapes/line`
* `//ly.img.ubq/shapes/star`
* `//ly.img.ubq/shapes/polygon`
* `//ly.img.ubq/shapes/ellipse`
* `//ly.img.ubq/vector_path`
##
Translations
Some of the translation keys related to Scopes and Placeholder-Settings have been also updated:
* Removed the following keys:
* `scope.content.replace`
* `scope.design.arrange`
* `scope.design.style`
* Renamed the following keys:
* `scope.design.arrange.flip` is now `scope.layer.flip`
* `scope.design.arrange.move` is now `scope.layer.move`
* `scope.design.arrange.resize` is now `scope.layer.resize`
* `scope.design.arrange.rotate` is now `scope.layer.rotate`
* Added the following keys:
* `component.placeholder.appearance.description`
* `component.placeholder.appearance`
* `component.placeholder.arrange.description`
* `component.placeholder.arrange`
* `component.placeholder.disableAll`
* `component.placeholder.enableAll`
* `component.placeholder.fill.description`
* `component.placeholder.fill`
* `component.placeholder.general.description`
* `component.placeholder.general`
* `component.placeholder.shape.description`
* `component.placeholder.shape`
* `component.placeholder.stroke.description`
* `component.placeholder.stroke`
* `component.placeholder.text.description`
* `component.placeholder.text`
* `scope.appearance.adjustments`
* `scope.appearance.blur`
* `scope.appearance.effect`
* `scope.appearance.filter`
* `scope.appearance.shadow`
* `scope.fill.change`
* `scope.layer.blendMode`
* `scope.layer.opacity`
* `scope.shape.change`
* `scope.stroke.change`
* `scope.text.character`
* `scope.text.edit`
##
**Types and API Signatures**
To improve the type safety of our APIs, we have moved away from using the `DesignBlockType` enum and replaced with a set of types. Those changes have affected the following APIs:
* `CESDK.engine.block.create()`
* `CESDK.engine.block.createFill()`
* `CESDK.engine.block.createEffect()`
* `CESDK.engine.block.createBlur()`
* `CESDK.engine.block.findByType()`
* `CESDK.engine.block.getType()`
**Note**
The `create`, `findByType`, and `getType` APIs will no longer accept the IDs of the deprecated legacy blocks and will throw an error when those are passed
##
**Code Examples**
This section will show some code examples of the breaking changes and how it would look like after migrating.
```
/** Block Creation */
// Creating an Image before migration
const image = cesdk.engine.block.create('image');
cesdk.engine.block.setString(
image,
'image/imageFileURI',
'https://domain.com/link-to-image.jpg'
);
// Creating an Image after migration
const block = cesdk.engine.block.create('graphic');
const rectShape = cesdk.engine.block.createShape('rect');
const imageFill = cesdk.engine.block.createFill('image');
cesdk.engine.block.setString(
imageFill,
'fill/image/imageFileURI',
'https://domain.com/link-to-image.jpg'
);
cesdk.engine.block.setShape(block, rectShape);
cesdk.engine.block.setFill(block, imageFill);
cesdk.engine.block.setKind(block, 'image');
// Creating a star shape before migration
const star = cesdk.engine.block.create('shapes/star');
cesdk.engine.block.setInt(star, 'shapes/star/points', 8);
// Creating a star shape after migration
const block = cesdk.engine.block.create('graphic');
const starShape = cesdk.engine.block.createShape('star');
const colorFill = cesdk.engine.block.createFill('color');
cesdk.engine.block.setInt(starShape, 'shape/star/points', 8);
cesdk.engine.block.setShape(block, starShape);
cesdk.engine.block.setFill(block, colorFill);
cesdk.engine.block.setKind(block, 'shape');
// Creating a sticker before migration
const sticker = cesdk.engine.block.create('sticker');
cesdk.engine.setString(
sticker,
'sticker/imageFileURI',
'https://domain.com/link-to-sticker.png'
);
// Creating a sticker after migration
const block = cesdk.engine.block.create('graphic');
const rectShape = cesdk.engine.block.createShape('rect');
const imageFill = cesdk.engine.block.createFill('image');
cesdk.engine.block.setString(
imageFill,
'fill/image/imageFileURI',
'https://domain.com/link-to-sticker.png'
);
cesdk.engine.block.setShape(block, rectShape);
cesdk.engine.block.setFill(block, imageFill);
cesdk.engine.block.setKind(block, 'sticker');
/** Block Creation */
```
```
/** Block Exploration */
// Query all images in the scene before migration
const images = cesdk.engine.block.findByType('image');
// Query all images in the scene after migration
const images = cesdk.engine.block.findByType('graphic').filter((block) => {
const fill = cesdk.engine.block.getFill(block);
return (
cesdk.engine.block.isValid(fill) &&
cesdk.engine.block.getType(fill) === '//ly.img.ubq/fill/image'
);
});
// Query all stickers in the scene before migration
const stickers = cesdk.engine.block.findByType('sticker');
// Query all stickers in the scene after migration
const stickers = cesdk.engine.block.findByKind('sticker');
// Query all Polygon shapes in the scene before migration
const polygons = cesdk.engine.block.findByType('shapes/polygon');
// Query all Polygon shapes in the scene after migration
const polygons = cesdk.engine.block.findByType('graphic').filter((block) => {
const shape = cesdk.engine.block.getShape(block);
return (
cesdk.engine.block.isValid(shape) &&
cesdk.engine.block.getType(shape) === '//ly.img.ubq/shape/polygon'
);
});
/** Block Exploration */
```
[
Previous
Migrating to v1.13
](/docs/cesdk/introduction/migration_1_13/)[
Next
Migrating to v1.32
](/docs/cesdk/introduction/migration_1_32/)
How to Write Custom Components - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/customization/api/registerComponents/
CESDK/CE.SDK/Web Editor/Customization/API Reference
# How to Write Custom Components
Learn how to write or overwrite and register custom components
The CE.SDK web editor provides a set of built-in components that you can reference and render in a specific order. You can see a list of all available components in the respective documentation, including [Dock](/docs/cesdk/ui/customization/api/dock/), [Canvas Menu](/docs/cesdk/ui/customization/api/canvasMenu/), [Inspector Bar](/docs/cesdk/ui/customization/api/inspectorBar/), [Navigation Bar](/docs/cesdk/ui/customization/api/navigationBar/) and [Canvas Bar](/docs/cesdk/ui/customization/api/canvasBar/).
Additionally, you can write your own custom components, register them, and use them just like the built-in components. This allows you to extend the functionality of the CE.SDK web editor with custom logic and create a more personalized experience for your users.
##
Registering a Custom Component
The entry point for writing a custom component is the method `registerComponent`. For a given identifier, you add a function that will be called repeatedly to render this component. Several arguments are passed to this function that can be used to access the current state of the `engine` and render an UI with the help of the `builder`.
```
cesdk.ui.registerComponent('myCustomComponent', ({ builder: { Button }, engine }) => {
const selectedIds = engine.block.findAllSelected();
if (selectedIds.length !== 1) return;
Button('button-id', {
label: 'My Button',
onClick: () => {
console.log('Button clicked');
}
});
});
```
###
When is a Component Rendered?
It is important concept to understand when a registered component re-renders after its initial rendering. The component assumes that all its state is stored in the `engine` or the local state. Whenever we detect a change that is relevant for this component it will re-render.
###
Using the Engine
In the above example, we query for all selected blocks and based on the result we render a button or not. The engine detects the call to `findAllSelected` and now knows that if the selection changes, it needs to re-render this component. This works with all methods provided by the engine.
###
Using Local State
Besides the `engine`, the render function also receives a `state` argument to manage local state. This can be used to control input components or store state in general. When the state changes, the component will be re-rendered as well.
The `state` argument is a function that is called with a unique ID for the state. Any subsequent call to the state within this registered component will return the same state. The second optional argument is the default value for this state. If the state has not been set yet, it will return this value. Without this argument, you'll need to handle `undefined` values manually.
The return value of the state call is an object with `value` and `setValue` properties, which can be used to get and set the state. Since these property names match those used by input components, the object can be directly spread into the component options.
```
cesdk.ui.registerComponent('counter', ({ builder, state }) => {
const { value, setValue } = state('counter', 0);
builder.Button('counter-button', {
label: `${value} clicks`,
onClick: () => {
const pressed = value + 1;
setValue(pressed);
}
});
});
```
##
Passing Data to a Custom Component
If you add a component to an order, you can either pass a string representing the component or an object with the id and additional data. This data can be accessed in the component function with inside the `payload` property.
```
cesdk.ui.registerComponent(
'myDockEnry.dock',
({ builder: { Button }, engine, payload }) => {
const { label } = payload;
console.log("Label", label);
}
);
cesdk.ui.setDockOrder([
{
id: 'myDockEnry.dock',
label: "Custom Label"
}
]);
```
##
Using the Builder
The `builder` object passed to the render function provides a set of methods to create UI elements. Calling this method will add a builder component to the user interface. This includes buttons, dropdowns, text, etc.
###
Available Builder components
Not every location supports every builder component yet. It will be extended over time. If you are unsure, you can always check the documentation of the respective component.
Builder Component
Description
Properties
Available For
Builder Component
`builder.Button`
Description
A simple button to react on a user click.
Properties
**label**: The label inside the button. If it is a i18n key, it will be used for translation.
**onClick**: Executed when the button is clicked.
**variant**: The variant of the button. `regular` is the default variant, `plain` is a variant without any background or border.
**color**: The color of the button. `accent` is the accent color to stand out, `danger` is a red color.
**icon**: The icon of the button.
**isActive**: A boolean to indicate that the button is active.
**isSelected**: A boolean to indicate that the button is selected.
**isDisabled**: A boolean to indicate that the button is disabled.
**isLoading**: A boolean to indicate that the button is in a loading state.
**loadingProgress**: A number between 0 and 1 to indicate the progress of a loading button.
**tooltip**: A tooltip displayed upon hover. If it is a i18n key, it will be used for translation.
Available For
[Dock](/docs/cesdk/ui/customization/api/dock/), [Canvas Menu](/docs/cesdk/ui/customization/api/canvasMenu/), [Inspector Bar](/docs/cesdk/ui/customization/api/inspectorBar/), [Navigation Bar](/docs/cesdk/ui/customization/api/navigationBar/) and [Canvas Bar](/docs/cesdk/ui/customization/api/canvasBar/)
Builder Component
`builder.ButtonGroup`
Description
Grouping of multiple buttons in a single segmented control.
Properties
**children**: A function executed to render grouped buttons. Only the Button and Dropdown builder components are allowed to be rendered inside this function.
Available For
[Dock](/docs/cesdk/ui/customization/api/dock/), [Canvas Menu](/docs/cesdk/ui/customization/api/canvasMenu/), [Inspector Bar](/docs/cesdk/ui/customization/api/inspectorBar/), [Navigation Bar](/docs/cesdk/ui/customization/api/navigationBar/) and [Canvas Bar](/docs/cesdk/ui/customization/api/canvasBar/)
Builder Component
`builder.Dropdown`
Description
A button that opens a dropdown with additional content when the user clicks on it.
Properties
The same properties as for `builder.Button`, but instead of `onClick` it provides:
**children**: A function executed to render the content of the dropdown. Every builder component called in this children function, will be rendered in the dropdown
Available For
[Canvas Menu](/docs/cesdk/ui/customization/api/canvasMenu/), [Inspector Bar](/docs/cesdk/ui/customization/api/inspectorBar/) and [Navigation Bar](/docs/cesdk/ui/customization/api/navigationBar/)
Builder Component
`builder.Heading`
Description
Renders its content as heading to the navigation bar.
Properties
**content**: The content of the header as a string
Available For
[Navigation Bar](/docs/cesdk/ui/customization/api/navigationBar/)
Builder Component
`builder.Separator`
Description
Adds a small space (invisible `` element) in the canvas menu to help the visual separation of entries.
Separators follow some special layouting rules:
\- If 2 or more separators end up next to each other (e.g. due to other components not rendering), **only 1** separator will be rendered.
\- Separators that end up being the first or last element in the canvas menu will **not** be rendered.
\- Separators directly adjacent _to the top side_ of a spacer (see below) will **not** be rendered.
Properties
\-
Available For
[Dock](/docs/cesdk/ui/customization/api/dock/), [Canvas Menu](/docs/cesdk/ui/customization/api/canvasMenu/), [Inspector Bar](/docs/cesdk/ui/customization/api/inspectorBar/), [Navigation Bar](/docs/cesdk/ui/customization/api/navigationBar/) and [Canvas Bar](/docs/cesdk/ui/customization/api/canvasBar/)
[
Previous
Canvas Bar
](/docs/cesdk/ui/customization/api/canvasBar/)[
Next
Custom Panels
](/docs/cesdk/ui/customization/api/customPanel/)
One-Click Quick Action Plugins - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/customization/guides/oneClickQuickActionPlugins/
CESDK/CE.SDK/Web Editor/Customization/Guides
# One-Click Quick Action Plugins
Learn how to add one-click quick actions from plugins to the web editor
Adding new functionality to the web editor is easy with plugins provided by external packages. Some of these are simple to integrate and just require a single button to be added to the editor. We call them "quick actions."
You just need to install the NPM package and add the plugin to the editor. The business logic and button components are automatically registered, and all that’s left to do is to add the one-click quick actions to the editor.
##
Quick Action: Background Removal
The background removal plugin is a great example of a one-click quick action. It allows you to remove the background of an image with a single click. After adding the plugin, you won't see any immediate change to the editor. You will need to define where to place this feature.
```
import BackgroundRemovalPlugin from '@imgly/plugin-background-removal-web';
[...]
// Adding this plugin will automatically register user interface components
cesdk.addPlugin(BackgroundRemovalPlugin());
// Prepend it to the canvas menu ...
cesdk.ui.setCanvasMenuOrder([
'ly.img.background-removal.canvasMenu'
...cesdk.ui.getCanvasMenuOrder(),
]);
// ... or the inspector bar
cesdk.ui.setInspectorBar([
'ly.img.background-removal.inspectorBar'
...cesdk.ui.getInspectorBar(),
]);
```
##
Quick Action: Vectorizer
For the vectorizer plugin, the process is exactly the same. Simply install and add the plugin, then use the component Ids to extend the user interface.
```
import VectorizerPlugin from '@imgly/plugin-vectorizer-web';
[...]
// Adding this plugin will automatically register user interface components
cesdk.addPlugin(VectorizerPlugin());
// Prepend it to the canvas menu ...
cesdk.ui.setCanvasMenuOrder([
'ly.img.vectorizer.canvasMenu'
...cesdk.ui.getCanvasMenuOrder(),
]);
// ... or the inspector bar
cesdk.ui.setInspectorBar([
'ly.img.vectorizer.inspectorBar'
...cesdk.ui.getInspectorBar(),
]);
```
[
Previous
Adding New Buttons
](/docs/cesdk/ui/customization/guides/addingNewButtons/)[
Next
Creating A Custom Panel
](/docs/cesdk/ui/customization/guides/creatingCustomPanel/)
Shapes - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/api/block-shapes/?platform=web&language=javascript
# Shapes
In this example, we will show you how to use the [CreativeEditor SDK](https://img.ly/products/creative-sdk)'s CreativeEngine to modify a `graphic` block's shape through the `block` API.
##
Setup
This example uses the headless CreativeEngine. See the [Setup](/docs/cesdk/engine/quickstart/) article for a detailed guide. To get started right away, you can also access the `block` API within a running CE.SDK instance via `cesdk.engine.block`. Check out the [APIs Overview](../) to see that illustrated in more detail.
##
Creating a Shape
To create a shape simply use `createShape(type: string): number`.
```
const star = engine.block.createShape('star');
```
```
createShape(type: ShapeType): DesignBlockId
```
Create a new shape, fails if type is unknown.
* `type`: The type of the shape object that shall be created.
* Returns The created shape's handle.
```
const star = engine.block.createShape('star');
```
We currently support the following shape types:
* `'//ly.img.ubq/shape/rect'`
* `'//ly.img.ubq/shape/line'`
* `'//ly.img.ubq/shape/ellipse'`
* `'//ly.img.ubq/shape/polygon'`
* `'//ly.img.ubq/shape/star'`
* `'//ly.img.ubq/shape/vector_path'`
Note: short types are also accepted, e.g. `'rect'` instead of `'//ly.img.ubq/shape/rect'`.
```
const star = engine.block.createShape('star');
```
##
Functions
You can configure shapes just like you configure design blocks. See [Modify Properties](/docs/cesdk/engine/api/block-properties/) for more detail.
```
engine.block.setInt(star, 'shape/star/points', 6);
```
```
getShape(id: DesignBlockId): DesignBlockId
```
Returns the block containing the shape properties of the given block.
* `id`: The block whose shape block should be returned.
* Returns The block that currently defines the given block's shape.
```
const previousShape = engine.block.getShape(block);
```
##
Destroying and Replacing Shapes
Remember to first destroy the previous shape if you don't need it any more before changing the shape of a design block.
```
engine.block.destroy(previousShape);
```
```
setShape(id: DesignBlockId, shape: DesignBlockId): void
```
Sets the block containing the shape properties of the given block. Note that the previous shape block is not destroyed automatically. The new shape is disconnected from its previously attached block. Required scope: 'shape/change'
* `id`: The block whose shape should be changed.
* `fill`: The new shape.
```
engine.block.setShape(block, star);
```
```
supportsShape(id: DesignBlockId): boolean
```
Query if the given block has a shape property.
* `id`: The block to query.
* Returns true, if the block has a shape property, an error otherwise.
```
engine.block.supportsShape(block);
```
Hierarchies - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/engine/api/block-hierarchies/?platform=web&language=javascript
# Hierarchies
In this example, we will show you how to use the [CreativeEditor SDK](https://img.ly/products/creative-sdk)'s CreativeEngine to modify the hierarchy of blocks through the `block` API.
##
Setup
This example uses the headless CreativeEngine. See the [Setup](/docs/cesdk/engine/quickstart/) article for a detailed guide. To get started right away, you can also access the `block` API within a running CE.SDK instance via `cesdk.engine.block`. Check out the [APIs Overview](../) to see that illustrated in more detail.
##
Manipulate the hierarchy of blocks
Only blocks that are direct or indirect children of a `page` block are rendered. Scenes without any `page` child may not be properly displayed by the CE.SDK editor.
```
getParent(id: DesignBlockId): DesignBlockId | null
```
Query a block's parent.
* `id`: The block to query.
* Returns The parent's handle or null if the block has no parent.
```
const parent = engine.block.getParent(block);
```
```
getChildren(id: DesignBlockId): DesignBlockId[]
```
Get all children of the given block. Children are sorted in their rendering order: Last child is rendered in front of other children.
* `id`: The block to query.
* Returns A list of block ids.
```
const childIds = engine.block.getChildren(block);
```
```
insertChild(parent: DesignBlockId, child: DesignBlockId, index: number): void
```
Insert a new or existing child at a certain position in the parent's children. Required scope: 'editor/add'
* `parent`: The block whose children should be updated.
* `child`: The child to insert. Can be an existing child of `parent`.
* `index`: The index to insert or move to.
```
engine.block.insertChild(page, block, 0);
```
```
appendChild(parent: DesignBlockId, child: DesignBlockId): void
```
Appends a new or existing child to a block's children. Required scope: 'editor/add'
* `parent`: The block whose children should be updated.
* `child`: The child to insert. Can be an existing child of `parent`.
```
engine.block.appendChild(parent, block);
```
When adding a block to a new parent, it is automatically removed from its previous parent.
Web Editor Solutions - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/solutions/
CESDK/CE.SDK/Web Editor/Solutions
# Web Editor Solutions
Get to know all the available web editor solutions.
In this section, you will find all the available web editor solutions. Check out all the solutions to find what fits your use case best.
* [**Design Editor**](/docs/cesdk/ui/solutions/design-editor/javascript/)
Built to support versatile editing capabilities for a broad range of design applications.
* [**Video Editor**](/docs/cesdk/ui/solutions/video-editor/javascript/)
Built to edit videos.
* [**Photo Editor**](/docs/cesdk/ui/solutions/photo-editor/javascript/)
Built to edit photos.
[
Previous
Editing Video
](/docs/cesdk/ui/guides/edit/)[
Next
Javascript
](/docs/cesdk/ui/solutions/design-editor/javascript/)
Vue.js Creative Editor - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/solutions/design-editor/vuejs/
CESDK/CE.SDK/Web Editor/Solutions/Design Editor
# Vue.js Creative Editor
The CreativeEditor SDK delivers a powerful Vue.js library designed for crafting and editing rich visual designs directly within the browser.
This CE.SDK configuration is fully customizable and extendable, offering a comprehensive range of design editing capabilities, including templating, layout management, asset integration, and more, as well as advanced features like background removal.
[Explore Demo](https://img.ly/showcases/cesdk/default-ui/web)
##
Key Features of the Vue.js Creative Editor SDK

### Transformations
Execute operations like cropping, rotating, and resizing design components.

### Templating
Build and apply design templates with placeholders and text variables for dynamic content.

### Placeholders & Lockable Design
Constrain templates to guide your users’ design and ensure brand consistency.

### Asset Handling
Import and manage images, shapes, and other assets for your design projects.

### Design Collages
Arrange multiple elements on a single canvas to create intricate layouts.

### Text Editing
Incorporate and style text blocks using various fonts, colors, and effects.

### Client-Side Operations
All design editing tasks are performed directly in the browser, eliminating the need for server dependencies.

### Headless & Automation
Programmatically edit designs within your React application using the engine API.

### Extendible
Easily enhance functionality with plugins and custom scripts.

### Customizable UI
Develop and integrate custom UIs tailored to your application’s design requirements.

### Background Removal
This plugin simplifies the process of removing backgrounds from images entirely within the browser.

### Print Optimization
Ideal for web-to-print scenarios, supporting spot colors and cut-outs.
##
Browser Support
The CE.SDK Design Editor is optimized for use in modern web browsers, ensuring compatibility with the latest versions of Chrome, Firefox, Edge, and Safari. See the full list of [supported browsers here](https://img.ly/docs/cesdk/faq/browser-support/).
##
Prerequisites
[Install the latest stable version of **Node.js & NPM**](https://www.npmjs.com/get-npm)
##
Supported Formats
Creative Editor SDK supports loading, editing, and saving a variety of image formats directly in the browser, with no need for server-side dependencies. Supported formats include:
* JPG
* PNG
* SVG
* WEBP
You can export individual assets or entire designs as PDF, JPG, PNG, or SVG files.
##
Understanding CE.SDK Architecture & API
The following sections provide an overview of the key components of the CE.SDK design editor UI and its API architecture.
If you're ready to start integrating CE.SDK into your Vue.js application, refer to our [Getting Started guide](https://img.ly/docs/cesdk/engine/quickstart/) or explore the Essential Guides.
###
CreativeEditor Design UI
The CE.SDK design UI is designed for intuitive design creation and editing. Key components and customizable elements within the UI include:

* **Canvas:** The main interaction area for design content.
* **Dock:** An entry point for interactions not directly related to the selected design block, often used for accessing asset libraries.
* **Canvas Menu:** Access block-specific settings like duplication or deletion.
* **Inspector Bar:** Manage block-specific functionalities, such as adjusting properties of the selected block.
* **Navigation Bar:** Handles global scene actions like undo/redo and zoom.
* **Canvas Bar:** Provides tools for managing the overall canvas, such as adding pages or controlling zoom.
* **Layer Panel:** Manage the stacking order and visibility of design elements.
Learn more about interacting with and manipulating design controls in our design editor UI guide.
###
CreativeEngine
The CreativeEngine is the core of CE.SDK, responsible for rendering and manipulating design scenes. It can operate in headless mode or be integrated with the CreativeEditor UI. Key features and APIs provided by CreativeEngine include:
* **Scene Management:** Create, load, save, and modify design scenes programmatically.
* **Block Manipulation:** Create and manage design elements, such as shapes, text, and images.
* **Asset Management:** Load assets like images and SVGs from URLs or local sources.
* **Variable Management:** Define and manipulate variables within scenes for dynamic content.
* **Event Handling:** Subscribe to events like block creation or updates for dynamic interaction.
##
API Overview
CE.SDK’s APIs are categorized into several groups, reflecting different aspects of scene management and manipulation.
[**Scene API:**](https://img.ly/docs/cesdk/engine/api/scene/)
* **Creating and Loading Scenes**[:](https://img.ly/docs/cesdk/engine/guides/create-scene/)
```
engine.scene.create();
engine.scene.loadFromURL(url);
```
* **Zoom Control**[:](https://img.ly/docs/cesdk/engine/api/scene-zoom/#sceneapisetzoomlevel)
```
engine.scene.setZoomLevel(1.0);
engine.scene.zoomToBlock(blockId);
```
[**Block API:**](https://img.ly/docs/cesdk/engine/api/block/):
* **Creating Blocks**:
```
const block = engine.block.create('shapes/rectangle');
```
* **Setting Properties**:
```
engine.block.setColor(blockId, 'fill/color', { r: 1, g: 0, b: 0, a: 1 });
engine.block.setString(blockId, 'text/content', 'Hello World');
```
* **Querying Properties**:
```
const color = engine.block.getColor(blockId, 'fill/color');
const text = engine.block.getString(blockId, 'text/content');
```
[**Variable API:**](https://img.ly/docs/cesdk/engine/api/variables/)
Variables allow dynamic content within scenes, enabling programmatic creation of design variations.
* **Managing Variables**:
```
engine.variable.setString('myVariable', 'value');
const value = engine.variable.getString('myVariable');
```
[**Asset API:**](https://img.ly/docs/cesdk/engine/api/assets/#defining-a-custom-asset-source):
* **Managing Assets**:
```
engine.asset.add('image', 'https://example.com/image.png');
```
[**Event API:**](https://img.ly/docs/cesdk/engine/api/events/):
* **Subscribing to Events**:
```
// Subscribe to scene changes
engine.scene.onActiveChanged(() => {
const newActiveScene = engine.scene.get();
});
```
##
Customizing the Vue.js Creative Editor
CE.SDK provides extensive customization options to tailor the UI to various use cases. These options range from simple configuration changes to more advanced customizations involving callbacks and custom elements.
###
Basic Customizations
* **Configuration Object:** When initializing the CreativeEditor, pass a configuration object that defines basic settings such as the base URL for assets, language, theme, and license key.
```
const config = {
baseURL: 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.18.0/assets',
license: 'your-license-key',
locale: 'en',
theme: 'light'
};
```
* **Localization:** Customize the language and labels used in the editor to support different locales.
```
const config = {
i18n: {
en: {
variables: {
my_custom_variable: {
label: 'Custom Label'
}
}
}
}
};
```
* [Custom Asset Sources](https://img.ly/docs/cesdk/engine/api/assets/#defining-a-custom-asset-source): Serve custom image or SVG assets from a remote URL.
###
UI Customization Options
* **Theme:** Select from predefined themes like 'dark' or 'light'.
```
const config = {
theme: 'dark'
};
```
* **UI Components:** Enable or disable specific UI components as needed.
```
const config = {
ui: {
elements: {
toolbar: true,
inspector: false
}
}
};
```
##
Advanced Customizations
Explore more ways to extend editor functionality and customize its UI to your specific needs by consulting our detailed [customization guide](https://img.ly/docs/cesdk/ui/customization/guides/). Below is an overview of the available APIs and components.
###
Order APIs
The Order APIs manage the customization of the web editor's components and their order within these locations, allowing the addition, removal, or reordering of elements. Each location has its own Order API, such as `setDockOrder`, `setCanvasMenuOrder`, `setInspectorBarOrder`, `setNavigationBarOrder`, and `setCanvasBarOrder`.
###
Layout Components
CE.SDK offers special components for layout control, such as `ly.img.separator` for separating groups of components and `ly.img.spacer` for adding space between components.
###
Registration of New Components
Custom components can be registered and integrated into the web editor using builder components like buttons, dropdowns, and inputs. These components can replace default ones or introduce new functionalities, seamlessly integrating custom logic into the editor.
###
Feature API
The Feature API allows for the conditional display and functionality of components based on the current context, enabling dynamic customization. For instance, certain buttons can be hidden for specific block types.
##
Plugins
Customizing the CE.SDK web editor during its initialization is possible through the APIs outlined above. For many use cases, this will be sufficient. However, there are situations where encapsulating functionality for reuse is necessary. Plugins come in handy here. Follow our [guide on building your own plugins](https://img.ly/docs/cesdk/ui/customization/plugins/) to learn more or explore some of the plugins we've created using this API:
* **Background Removal**: Adds a button to the canvas menu to remove image backgrounds.
* **Vectorizer**: Adds a button to the canvas menu to quickly vectorize a graphic.
##
Framework Support
CreativeEditor SDK’s video editing library is compatible with any Javascript including, React, Angular, Vue.js, Svelte, Blazor, Next.js, Typescript. It is also compatible with desktop and server-side technologies such as electron, PHP, Laravel and Rails.
[
Headless
](/docs/cesdk/engine/quickstart/)[
Javascript
](/docs/cesdk/ui/solutions/design-editor/react/)[
React
](/docs/cesdk/ui/solutions/design-editor/vuejs/)[
Angular
](/docs/cesdk/ui/solutions/design-editor/angular/)[
Svelte
](/docs/cesdk/ui/quickstart?framework=svelte)[.electron\_svg\_\_cls-1{fill:#2b2e3a;fill-rule:evenodd}.electron\_svg\_\_cls-2{fill:#9feaf9}
Electron
](/docs/cesdk/ui/quickstart?framework=electron)[
Next.js
](/docs/cesdk/ui/quickstart?framework=nextjs)[
Node.js
](/docs/cesdk/ui/quickstart?platform=node)
Ready to get started?
With a free trial and pricing that fits your needs, it's easy to find the best solution for your product.
[Free Trial](https://img.ly/forms/free-trial)
### 500M+
video and photo creations are powered by IMG.LY every month

[
Previous
Angular
](/docs/cesdk/ui/solutions/design-editor/angular/)[
Next
Javascript
](/docs/cesdk/ui/solutions/video-editor/javascript/)
Adding Translations to the CreativeEditor SDK - CE.SDK | IMG.LY Docs [web/undefined/js] https://img.ly/docs/cesdk/ui/guides/i18n/?platform=web&language=js
# Adding Translations to the CreativeEditor SDK
In this example, we will show you how to configure the [CreativeEditor SDK](https://img.ly/products/creative-sdk). CE.SDK has full i18n support and allows overwriting and extending all strings to any valid language.
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/configure-i18n?title=IMG.LY%27s+CE.SDK%3A+Configure+I18n&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/configure-i18n).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/configure-i18n?title=IMG.LY%27s+CE.SDK%3A+Configure+I18n&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/configure-i18n)
##
I18N Configuration
The CE.SDK comes with a set of configuration parameters which let you translate any label in the user interface.
```
const config = {
license: 'mtLT-_GJwMhE7LDnO8KKEma7qSuzWuDxiKuQcxHKmz3fjaXWY2lT3o3Z2VdL5twm',
userId: 'guides-user',
locale: 'fr',
i18n: {
fr: {
'common.back': 'Retour',
'meta.currentLanguage': 'Français'
},
it: {
'common.back': 'Indietro',
'meta.currentLanguage': 'Italiano'
}
},
ui: {
elements: {
navigation: {
action: {
back: true // Enable 'Back' button to show translation label.
}
},
panels: {
settings: true // Enable Settings panel for switching languages.
}
}
},
callbacks: { onUpload: 'local' } // Enable local uploads in Asset Library.
};
```
* `locale: string` defines the default language of the user interface. This can later be changed in the editor customization panel. The CE.SDK currently ships with locales for English `en` and German `de`. Additional languages will be available in the future. Until then, or if you want to provide custom wording and translations, you can provide your own translations under the `i18n` configuration option, as described in the next paragraph.
```
locale: 'fr',
```
* `i18n: Object` is a map of strings that define the translations for multiple locales. Since the CE.SDK supports maintaining multiple locales at the same time, the first key in the map must always be the locale the translation is targeting. In this example, we change the back-button label for the locales `'fr'` and `'it'`.
Please note that the fallback locale is `'en'`. So, with this configuration, the complete user interface would be English except for the back-button. Also, if you want to change a single label for one of our shipped translations, you do not have to add all keys, but only the one you want to override.
A detailed overview of all available keys can be found in form of predefined language files inside `assets/i18n`. You can download the English version from our CDN here: [en.json](https://cdn.img.ly/packages/imgly/cesdk-js/1.43.0/assets/i18n/en.json)
```
i18n: {
fr: {
'common.back': 'Retour',
'meta.currentLanguage': 'Français'
},
it: {
'common.back': 'Indietro',
'meta.currentLanguage': 'Italiano'
}
```
* Under the special key `meta.currentLanguage`, you should provide a short label for your provided language. This will be used to display the language in the language select dropdown of the editor customization panel.
```
'meta.currentLanguage': 'Français'
```
Adding Templates - CE.SDK | IMG.LY Docs [web/undefined/js] https://img.ly/docs/cesdk/ui/guides/custom-template-source/?platform=web&language=js
# Adding Templates
You can use the asset source system to offer a series of templates, that act as a quick start for your users.
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-custom-template-source?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Custom+Template+Source&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-custom-template-source).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-custom-template-source?title=IMG.LY%27s+CE.SDK%3A+Engine+Guides+Custom+Template+Source&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/engine-guides-custom-template-source)
##
Demo templates
By default, the CE.SDK ships with a predefined set of default templates, that can be added to your installation using the `addDemoAssetSources()` method:

```
instance.addDemoAssetSources({ sceneMode: 'Design' });
```
##
Custom template asset source
Templates consist of predefined scenes created using CE.SDK. To create your own template, just design your desired file using CE.SDK and save the scene to disk using the 'Download' button. The scene file can then act as a template for your users.
To make the templates you created available to users, you need to create an asset source. This example shows the minimal amount of code you need to write to have your templates appear in the Asset Library. For a more complete description of the different ways you can configure the asset library, take a look at the [Asset API documentation](/docs/cesdk/engine/api/assets/) and the [customize asset library guide](/docs/cesdk/ui/guides/customize-asset-library/).
###
Add local asset source
Add a local asset source, using an arbitrary id that identifies the asset source. In this case the asset source id is `my-templates`.
```
instance.engine.asset.addLocalSource(
'my-templates',
undefined,
function applyAsset(asset) {
instance.engine.scene.applyTemplateFromURL(asset.meta.uri);
}
);
```
###
applyAsset()
Assets that the user has chosen from the asset library are passed to the `applyAsset` function.
This function determines what to do with the selected asset. In our case we want to apply it to the scene using the [Scene API](/docs/cesdk/engine/api/scene-apply-template/). Note that you can access the entire asset object here. This means you can use it to store and process arbitrary information in the `meta` property. In this example, we are passing a URI to a template file, but you could also pass an internal identifier, a serialized scene string, or additional data to further modify or process the template using the available API methods.
```
function applyAsset(asset) {
instance.engine.scene.applyTemplateFromURL(asset.meta.uri);
}
```
###
Source Id
Every asset source needs a source id. Which one you chose does not really matter, as long as it is unique.
```
'my-templates',
undefined,
```
###
Add template assets to the source
Every template asset should have four different properties:
* `id: string` needs to be a uniqe identifier. It is mainly used internally and can be chosen arbitrarily.
* `label: string` describes the template and is being rendered inside the template library via tooltip and as ARIA label.
* `meta.thumbUri: string` pointing to a thumbnail source. Thumbnails are used in the template library shown in the inspector and should ideally have a width of 400px for landscape images. Keep in mind, that a large number of large thumbnails may slow down the library.
* `meta.uri: string` provides the scene to load, when selecting the template. This can either be a raw scene string starting with `UBQ1`, an absolute or relative URL pointing at a scene file, or an async function that returns a scene string upon resolve.
```
instance.engine.asset.addAssetToSource('my-templates', {
id: 'template1',
label: 'Template 1',
meta: {
uri: `${window.location.protocol}//${window.location.host}/template.scene`,
thumbUri: `${window.location.protocol}//${window.location.host}/template_thumb.png`
}
});
```
###
UI Config
It is not enough to add the asset source to the Creative Engine. You also need to configure how the asset source will appear in the asset library. For more information, see the [asset library guide](/docs/cesdk/ui/guides/customize-asset-library/). In this example we provide the minimal configuration to have the template library we just created appear.
```
instance.ui.addAssetLibraryEntry({
id: 'my-templates-entry',
sourceIds: ['my-templates'],
sceneMode: 'Design',
previewLength: 5,
previewBackgroundType: 'cover',
gridBackgroundType: 'cover',
gridColumns: 3
});
instance.ui.setDockOrder([
{
id: 'ly.img.assetLibrary.dock',
key: 'my-templates-dock-entry',
label: 'My Templates',
icon: '@imgly/Template',
entries: ['my-templates-entry']
}
]);
```
Javascript Video Editor SDK - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/solutions/video-editor/javascript/
CESDK/CE.SDK/Web Editor/Solutions/Video Editor
# Javascript Video Editor SDK
CreativeEditor SDK is a Javascript library for creating and editing videos directly in a browser.
This CE.SDK configuration is highly customizable and extendible and offers a well-rounded suite of video editing features such as splitting, cropping and composing clips on a timeline.
[Explore Demo](https://img.ly/showcases/cesdk/video-ui/web)
##
Key Capabilities

### Transform
Crop, flip, and rotate video operations.

### Trim & Split
Set start and end time and split videos.

### Merge Videos
Pick, edit and merge several video clips into a single sequence.

### Video Collage
Arrange multiple clips on a single page.

### Client-Side Processing
All video editing operations are performed by our engine in the browser.

### Headless & Automation
Programmatically edit videos inside the browser.

### Extendible
Easily add functionality using the plugins & engine API.

### Customizable UI
Build Custom UIs.

### Asset Libraries
Add custom assets for filters, stickers, images and videos.

### Green Screen
Utilize chroma keying for background removal.

### Templating
Create role based design templates with placeholders and text variables.
##
Browser Support
Video editing mode relies on modern web codecs, which are currently only available in the latest versions of Google Chrome, Microsoft Edge, or other Chromium-based browsers.
##
Supported File Types
[IMG.LY](http://img.ly/)'s Creative Editor SDK enables you to load, edit, and save **MP4 files** directly in the browser without server dependencies.
The following file types can also be imported for use as assets during video editing:
* MP3
* MP4 (with MP3 audio)
* M4A
* AAC
* JPG
* PNG
* WEBP
Individual scenes or assets from the video can be exported as JPG, PNG, Binary, or PDF files.
##
Getting Started
If you're ready to start integrating CE.SDK into your Vue.js application, check out the CE.SDK [Getting Started guide](https://img.ly/docs/cesdk/engine/quickstart/). In order to configure the editor for a video editing use case consult our [video editor UI showcase](https://img.ly/showcases/cesdk/video-ui/web) and its [reference implementation](https://github.com/imgly/cesdk-web-examples/blob/main/showcase-video-ui/src/components/case/CaseComponent.jsx).
##
Understanding CE.SDK Architecture & API
The following sections outline the fundamentals of CE.SDK’s video editor user interface and its technical architecture and APIs.
CE.SDK architecture is designed to facilitate the creation, manipulation, and rendering of complex designs. At a high level, it consists of two main components: the CreativeEngine and the CreativeEditor UI. The following is an overview of these components and how they are reflected at the API level.
If you are already familiar with CE.SDK and want to get started integrating CE.SDK video editor check out our “Getting Started” guide or jump ahead to the “Essential Guides” section.
###
CreativeEditor Video UI
CE.SDK’s video UI is designed to facilitate intuitive manipulation and creation of a range of video-based designs. The following are the key locations in the editor UI and extension points for your Ui customizations:

* _Canvas_: The core interaction area for design content, controlled by the Creative Engine.
* _Dock_: The primary entry point for user interactions not directly related to the selected block. It is primarily, though not exclusively, used to open panels with asset libraries or add elements to the canvas. [Learn how to add demo videos in the dock.](https://img.ly/docs/cesdk/ui/guides/video/#add-demo-asset-sources)
* _Canvas Menu_: Provides block-specific settings and actions such as deletion or duplication.
* _Inspector Bar_: Main location for block-specific functionality. Any action or setting available for the currently selected block that does not appear in the canvas menu will be shown here.
* _Navigation Bar_: For actions affecting browser navigation and global scene effects such as zoom or undo/redo.
* _Canvas Bar_: For actions affecting the canvas or scene as a whole such as adding pages. This is an alternative place for actions such as zoom or redo/undo.
* _Timeline_: The timeline is the main control for video editing. It is here that clips and audio strips can be positioned in time.
Learn more about interacting with and manioukating video controls in our [video editor UI guide.](https://img.ly/docs/cesdk/ui/guides/video)
###
CreativeEngine
The CreativeEngine is the core of CE.SDK, responsible for handling the rendering and manipulation of designs. It can be used independently (headless mode) or integrated with the CreativeEditor UI. The CreativeEngine provides several APIs to interact with and manipulate scenes. A scene is the visual context or environment within the CreativeEditor SDK where blocks (elements) are created, manipulated, and rendered.
###
Key Features:
1. **Scene Management**:
* Create, load, save, and [m](https://img.ly/docs/cesdk/engine/guides/blocks/)odify scenes.
* Control the zoom and camera position within scenes.
2. **Block Manipulation**:
* Blocks are the basic building units of a scene, representing elements like shapes, images, and text.
* APIs to create, modify, and manage blocks.
* Properties of blocks (e.g., color, position, size) can be queried and set using specific methods.
3. **Asset Management**:
* Manage assets like images, videos, and fonts.
* Load assets from URLs or local sources.
4. **Variable Management**:
* Define and manipulate variables within scenes.
* Useful for template-based designs where dynamic content is required.
5. **Event Handling**:
* Subscribe to events related to block creation, updates, and destruction.
* Manage user interactions and state changes.
##
API Overview
The APIs of CE.SDK are grouped into several categories, reflecting different aspects of scene management and manipulation.
[**Scene API :**](https://img.ly/docs/cesdk/engine/api/scene/)
* **Creating and Loading Scenes**[:](https://img.ly/docs/cesdk/engine/guides/create-scene/)
```
engine.scene.create();
engine.scene.loadFromURL(url);
```
* **Zoom Control**[:](https://img.ly/docs/cesdk/engine/api/scene-zoom/#sceneapisetzoomlevel)
```
engine.scene.setZoomLevel(1.0);
engine.scene.zoomToBlock(blockId);
```
[**Block API :**](https://img.ly/docs/cesdk/engine/api/block/)
* **Creating Blocks**:
```
const block = engine.block.create('shapes/star');
```
* **Setting Properties**:
```
engine.block.setColor(blockId, 'fill/color', { r: 1, g: 0, b: 0, a: 1 });
engine.block.setString(blockId, 'text/content', 'Hello World');
```
* **Querying Properties**:
```
const color = engine.block.getColor(blockId, 'fill/color');
const text = engine.block.getString(blockId, 'text/content');
```
[**Variable API :**](https://img.ly/docs/cesdk/engine/api/variables/)
Variables allow dynamic content within scenes to programmatically create variations of a design.
* **Managing Variables**:
```
engine.variable.setString('myVariable', 'value');
const value = engine.variable.getString('myVariable');
```
[**Asset API :**](https://img.ly/docs/cesdk/engine/api/assets/#defining-a-custom-asset-source)
* **Managing Assets**:
```
engine.asset.add('image', 'https://example.com/image.png');
```
[**Event API :**](https://img.ly/docs/cesdk/engine/api/events/)
* **Subscribing to Events**:
```
// Subscribe to scene changes
engine.scene.onActiveChanged(() => {
const newActiveScene = engine.scene.get();
});
```
###
Example Usage
Here is a simple example of initializing the CreativeEngine and creating a video scene with a text block:
```
import CreativeEngine from 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.18.0/index.js';
const config = {
baseURL: 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.18.0/assets'
};
CreativeEngine.init(config).then(async (engine) => {
// Create a new scene
await engine.scene.createVideo();
// Add a text block
const textBlock = engine.block.create('text');
engine.block.setString(textBlock, 'text/content', 'Hello, CE.SDK!');
// Set the color of the text
engine.block.setColor(textBlock, 'fill/color', { r: 0, g: 0, b: 0, a: 1 });
// Attach the engine canvas to the DOM
document.getElementById('cesdk_container').append(engine.element);
});
```
This example demonstrates how to initialize the CreativeEngine, create a scene, add a text block, and set its properties. The flexibility of the APIs allows for extensive customization and automation of design workflows.
To learn more about how to power your own UI or creative workflows with the CreativeEngine have a look at the [engine guides](https://img.ly/docs/cesdk/engine/).
###
Customization Options
CE.SDK provides extensive customization options to adapt the UI to various use cases. These options range from simple configuration changes to more advanced customizations involving callbacks and custom elements.
###
Basic Customizations
* **Configuration Object**: When initializing the CreativeEditor, you can pass a configuration object that defines basic settings such as the base URL for assets, the language, theme, and license key.
```
const config = {
baseURL: 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.18.0/assets',
license: 'your-license-key',
locale: 'en',
theme: 'light'
};
```
* **Localization**: Customize the language and labels used in the editor to support different locales.
```
const config = {
i18n: {
en: {
variables: {
my_custom_variable: {
label: 'Custom Label'
}
}
}
}
};
```
* [Custom Asset Sources](https://img.ly/docs/cesdk/engine/api/assets/#defining-a-custom-asset-source): Serve custom video or image assets from a remote URL.
###
UI Customization Options
* **Theme**: Choose between predefined themes such as 'dark' or 'light'.
```
const config = {
theme: 'dark'
};
```
* **UI Components**: Enable or disable specific UI components based on your requirements.
```
const config = {
ui: {
elements: {
toolbar: true,
inspector: false
}
}
};
```
###
Advanced Customizations
Learn more about extending editor functionality and customizing its UI to your use case by consulting our in-depth [customization guide](https://img.ly/docs/cesdk/ui/customization/guides/). Here is an overview of the APIs and components available to you.
###
Order APIs
Customization of the web editor's components and their order within these locations is managed through specific Order APIs, allowing the addition, removal, or reordering of elements. Each location has its own Order API, e.g., `setDockOrder`, `setCanvasMenuOrder`, `setInspectorBarOrder`, `setNavigationBarOrder`, and `setCanvasBarOrder`.
###
Layout Components
CE.SDK provides special components for layout control, such as `ly.img.separator` for separating groups of components and `ly.img.spacer` for adding space between components.
###
Registration of New Components
Custom components can be registered and integrated into the web editor using builder components like buttons, dropdowns, and inputs. These components can replace default ones or introduce new functionalities, deeply integrating custom logic into the editor.
###
Feature API
The Feature API enables conditional display and functionality of components based on the current context, allowing for dynamic customization. For example, you can hide certain buttons for specific block types.
##
Plugins
You can customize the CE.SDK web editor during its initialization using the APIs outlined above. For many use cases, this will be adequate. However, there are times when you might want to encapsulate functionality for reuse. This is where plugins become useful. Follow our [guide on building your own plugins](https://img.ly/docs/cesdk/ui/customization/plugins/) to learn more or check out one of the plugins we built using this api:
[**Background Removal**](https://img.ly/docs/cesdk/ui/customization/plugins/backgroundRemoval/): Adds a button to the canvas menu to remove image backgrounds.
[**Vectorizer**](https://img.ly/docs/cesdk/ui/customization/plugins/vectorizer/): Adds a button to the canvas menu to quickly vectorize a graphic.
##
Framework Support
CreativeEditor SDK’s video editing library is compatible with any Javascript including, React, Angular, Vue.js, Svelte, Blazor, Next.js, Typescript. It is also compatible with desktop and server-side technologies such as electron, PHP, Laravel and Rails.
[
Headless
](/docs/cesdk/engine/quickstart/)[
React
](/docs/cesdk/ui/solutions/video-editor/react/)[
Angular
](/docs/cesdk/ui/solutions/video-editor/angular/)[
Vue
](/docs/cesdk/ui/solutions/video-editor/vuejs/)[
Svelte
](/docs/cesdk/ui/quickstart?framework=svelte)[.electron\_svg\_\_cls-1{fill:#2b2e3a;fill-rule:evenodd}.electron\_svg\_\_cls-2{fill:#9feaf9}
Electron
](/docs/cesdk/ui/quickstart?framework=electron)[
Next.js
](/docs/cesdk/ui/quickstart?framework=nextjs)[
Node.js
](/docs/cesdk/ui/quickstart?platform=node)
Ready to get started?
With a free trial and pricing that fits your needs, it's easy to find the best solution for your product.
[Free Trial](https://img.ly/forms/free-trial)
### 500M+
video and photo creations are powered by IMG.LY every month

[
Previous
Vue.js
](/docs/cesdk/ui/solutions/design-editor/vuejs/)[
Next
React
](/docs/cesdk/ui/solutions/video-editor/react/)
Create and Edit Video using the CreativeEditor SDK - CE.SDK | IMG.LY Docs [web/undefined/js] https://img.ly/docs/cesdk/ui/guides/edit/?platform=web&language=js
# Create and Edit Video using the CreativeEditor SDK
CE.SDK Video Mode allows your users to edit videos in a manner familiar from popular platforms such as TikTok or Instagram. The CE.SDK editor contains a full-featured video editor, complete with Video and Audio trimming, and composition capabilities. Get to know the core concepts in this guide.
To learn about the **available API calls** related to video editing, see the [engine guide on video editing](/docs/cesdk/engine/guides/video/).
To learn about the **Video Editor UI**, skip to the [UI overview](#ui-overview).
Explore a full code sample on [Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/guides-video-mode?title=IMG.LY%27s+CE.SDK%3A+Guides+Video+Mode&file=index.js) or view the code on [Github](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/guides-video-mode).
* [Edit on Stackblitz](https://stackblitz.com/fork/github/imgly/cesdk-web-examples/tree/v1.43.0/guides-video-mode?title=IMG.LY%27s+CE.SDK%3A+Guides+Video+Mode&file=index.js)
* [View on GitHub](https://github.com/imgly/cesdk-web-examples/tree/v1.43.0/guides-video-mode)
##
A Note on Browser Support
Video mode heavily relies on modern features like web codecs. A detailed list of supported browser versions can be found in our ["Supported Browsers" documentation](/docs/cesdk/faq/browser-support/). Please also take note of [possible restrictions based on the host platform](/docs/cesdk/faq/editor-limitations/) browsers are running on.
Video mode is currently not supported on any mobile web platform due to technical limitations by all mobile browsers.
[Our native mobile SDKs are a great solution for implementing video features on mobile devices today.](/docs/cesdk/mobile-editor/solutions/video-editor/)
##
Editor Setup
###
Configuring which library entries to use for background clips
You can use the `cesdk.ui.setBackgroundTrackAssetLibraryEntries` API to specify which library entries should be shown in insert panel for background clips.
```
cesdk.ui.setBackgroundTrackAssetLibraryEntries(['ly.img.image', 'ly.img.video']);
```
###
Add demo asset sources
When adding demo asset sources using `cesdk.addDemoAssetSources()`, make sure to specify the correct scene mode. The installed demo asset sources vary between Design and Video modes.
If you don't specify a scene mode, `addDemoAssetSources()` will try to add the correct sources based on the current scene, and default to `'Design'`. If you call `addDemoAssetSources()` _without_ a scene mode, and _before_ loading or creating a video scene, the audio and video asset sources will not be added.
```
cesdk.addDemoAssetSources({ sceneMode: 'Video' });
```
###
Create or load a video scene
To switch the editor to video mode, create an empty video scene using `cesdk.createVideoScene()`. If you already have a video scene, loading it with `loadFromUrl()` or `loadFromString()` will switch the editor to video mode as well.
```
const scene = await cesdk.createVideoScene();
```
And that's it!
##
UI Overview
###
Timeline

The timeline is the main control for video editing. It is here that clips and audio strips can be positioned in time. The timeline is divided into two main areas:
####
Foreground
Clips run along the top of the foreground timeline, while audio strips run along the bottom. Click anywhere inside the timeline to set the playback time, or drag the seeker directly. Use the **Split Clip** button to split the clips into two at the position of the seeker. The **zoom controls** allow you to zoom the timeline in and out for better control. Finally, Use the **Play** and **Loop** buttons to view the final result.
* Drag either of the strip handles to **adjust start and end time** of a clip.
* Drag the center of the strip to **position** the clip.
* Drag the center of the strip to **rearrange** the clips.
* Use the context menu on the strip to **perform specific actions** on the clip.
####
Background
Background clips go at the bottom of the timeline and define the length of the video. Background clips are typically videos and images, but can be configured to support other types of elements as well. They are packed against each other and can't have time gaps in between, and they define the length of the exported video.
* Drag either of the strip handles to **adjust start and end time** of a clip.
* Drag the center of the strip to **rearrange** the clips.
* Use the context menu on the strip to **perform specific actions** on the clip.
###
Video
Videos are handled in a similar fashion to regular elements: You can add them via the Asset Library and position them anywhere on the page. You can select a specific section of video to play by trimming the clip on the timeline and/or using the trim controls (pictured below), accessible by pressing the trim button.
####
Trimming videos

Trim controls will appear near the top of the editor window.
* While these controls are open, **only the selected video is played** during seeking or playback.
* You can **adjust the start and end time** by dragging the handles on either side of the strip.
* The **grayed-out area** indicates the parts of the video that won't be shown.
* The **blue overlay** indicates the end of the page duration - to show these parts of the video, extend the duration of the containing page.
###
Audio

Unlike regular design elements, audio is not visible on the canvas. It is only shown in the timeline, as audio strips. Use the timeline to edit audio:
* Drag either of the strip handles to **adjust start and end time** of the audio strip.
* Drag the center of the strip to **position** the strip.
* Drag the center of the strip to **rearrange** the audio stipes.
* Use the context menu on the strip to **perform specific actions** on the audio strip.
###
Trimming audio

Trimming audio works just like [trimming video](#trimming-videos).
Configuring the CreativeEditor SDK - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/configuration/
CESDK/CE.SDK/Web Editor/Configuration
# Configuring the CreativeEditor SDK
Get to know the various configuration options of the CreativeEditor SDK.
The CreativeEditor SDK (CE.SDK) works out of the box with almost zero configuration effort. However, almost every part of CE.SDK can be adapted and its behaviour and look & feel changed.
Here is a list of all available configuration options:
Key
Type
Description
Key
[baseURL](/docs/cesdk/ui/configuration/basics/)
Type
`string`
Description
Definition of the the base URL of all assets required by the SDK.
Key
[callbacks](/docs/cesdk/ui/configuration/callbacks/)
Type
`object`
Description
Definition of callbacks the SDK triggers.
Key
[i18n](/docs/cesdk/ui/guides/i18n/)
Type
`object`
Description
Options to add custom translations to the SDK.
Key
[license](/docs/cesdk/engine/quickstart/#licensing)
Type
`string`
Description
A license key that is unique to your product.
Key
[userID](/docs/cesdk/engine/quickstart/#licensing)
Type
`string`
Description
An unique ID tied to your application's user. This helps us accurately calculate monthly active users (MAU). Especially useful when one person uses the app on multiple devices with a sign-in feature, ensuring they're counted once. Providing this aids in better data accuracy.
Key
[locale](/docs/cesdk/ui/configuration/basics/)
Type
`string`
Description
Chosen language the editor is . Possible values are 'en', 'de', ...
Key
[role](/docs/cesdk/ui/configuration/basics/)
Type
`string`
Description
Chosen role. Possible values are 'Creator' or 'Adopter'.defines
Key
[theme](/docs/cesdk/ui/configuration/basics/)
Type
`string`
Description
The theme the SDK is launched in. Possible values are 'dark', 'light'
Key
[ui](/docs/cesdk/ui/guides/elements/)
Type
`object`
Description
Options to adapt the user interface elements.
[
Previous
Notification
](/docs/cesdk/ui/customization/api/notification/)[
Next
Basics
](/docs/cesdk/ui/configuration/basics/)
Adjusting the Content of the Canvas Menu - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/customization/api/canvasMenu/
CESDK/CE.SDK/Web Editor/Customization/API Reference
# Adjusting the Content of the Canvas Menu
Learn how to adjust the content of the canvas menu in the editor
There are 2 APIs for getting and setting the order of components in the Canvas Menu.
The content of the Canvas Menu changes based on the current [edit mode](/docs/cesdk/engine/api/editor-state/#state) (`'Transform'` (the default), `'Text'`, `'Crop'`, `'Trim'`, or a custom value), so both APIs accept an `orderContext` argument to specify the mode.
For example usage of these APIs, see also [Moving Existing Buttons](/docs/cesdk/ui/customization/guides/movingExistingButtons/#reducing-the-canvas-menu) or [Adding New Buttons](/docs/cesdk/ui/customization/guides/addingNewButtons/#add-a-button-to-the-canvas-menu-to-mark-blocks) in the Guides section.
###
Get the Current Order
```
cesdk.ui.getCanvasMenuOrder(
orderContext: OrderContext = { editMode: 'Transform' }
)
```
When omitting the `orderContext` parameter, the order for the `'Transform'` edit mode is returned, e.g.
```
cesdk.ui.getCanvasMenuOrder();
// => [
// {id: 'ly.img.group.enter.canvasMenu'},
// {id: 'ly.img.group.select.canvasMenu'},
// ...
// ]
```
###
Set a new Order
```
setCanvasMenuOrder(
canvasMenuOrder: (CanvasMenuComponentId | OrderComponent)[],
orderContext: OrderContext = { editMode: 'Transform' }
)
```
When omitting the `orderContext` parameter, the order is set for the default edit mode (`'Transform'`), e.g.:
```
// Sets the order for transform mode by default
cesdk.ui.setCanvasMenuOrder([ 'my.component.for.transform.mode']);
```
##
Canvas Menu Components
The following lists the default Canvas Menu components available within CE.SDK.
Take special note of the "Feature ID" column. Most components can be hidden/disabled by disabling the corresponding feature using the [Feature API](/docs/cesdk/ui/customization/api/features/).
Also note that many components are only rendered for the block types listed in the "Renders for" column, because their associated controls (e.g. font size) are only meaningful for specific kinds of blocks (e.g. text).
###
Layout Helpers
Component ID
Description
Component ID
`ly.img.separator`
Description
Adds a vertical separator (`` element) in the Canvas Menu.
Separators follow some special layouting rules:
\- If 2 or more separators end up next to each other (e.g. due to other components not rendering), **only 1** separator will be rendered.
\- Separators that end up being the first or last element in the Canvas Menu will **not** be rendered.
\- Separators directly adjacent _to the left side_ of a spacer (see below) will **not** be rendered.
###
Common Controls
These components are useful for editing various different block types.
Component ID
Description
Feature ID
Renders for
Component ID
`ly.img.replace.canvasMenu`
Description
Replace button:
Opens the "Replace" Panel offering to replace the current image or video fill.
Feature ID
`ly.img.replace`
Renders for
Images, Videos
Component ID
`ly.img.placeholder.canvasMenu`
Description
Placeholder button:
Opens the "Placeholder" panel, allowing the user to toggle specific [constraints](/docs/cesdk/ui/guides/placeholders/) on the selected block.
Feature ID
`ly.img.placeholder`
Renders for
Every block
Component ID
`ly.img.duplicate.canvasMenu`
Description
Duplicate button:
Duplicates the selected elements when pressed.
Feature ID
`ly.img.duplicate`
Renders for
Every block
Component ID
`ly.img.delete.canvasMenu`
Description
Delete button:
Deletes the selected elements when pressed.
Feature ID
`ly.img.delete`
Renders for
Every block
###
Text
These components are relevant for editing text blocks, and will only render when a text block is selected.
Component ID
Description
Feature ID
Component ID
`ly.img.text.edit.canvasMenu`
Description
Edit button:
Switches to text edit mode when pressed.
Feature ID
`ly.img.text.edit`
Component ID
`ly.img.text.color.canvasMenu`
Description
Color swatch button:
Opens the Color Panel, where the user can set the color for the currently selected text run.
Feature ID
`ly.img.fill`
Component ID
`ly.img.text.bold.canvasMenu`
Description
Bold toggle:
Toggles the bold cut (if available) for the currently selected text run.
Feature ID
`ly.img.text.edit`
Component ID
`ly.img.text.italic.canvasMenu`
Description
Italic toggle:
Toggles the italic cut (if available) for the currently selected text run.
Feature ID
`ly.img.text.edit`
Component ID
`ly.img.text.variables.canvasMenu`
Description
Insert Variable button:
Opens a dropdown containing the selection of available text variables.
Feature ID
###
Groups
These controls will only render when a group or an element of a group is selected.
Component ID
Description
Feature ID
Renders for
Component ID
`ly.img.group.enter.canvasMenu`
Description
Enter group button:
Moves selection to the first element of the group when pressed.
Feature ID
`ly.img.group`
Renders for
Groups
Component ID
`ly.img.group.select.canvasMenu`
Description
Select group button:
Moves selection to the parent group of the currently selected element when pressed.
Feature ID
`ly.img.group`
Renders for
Elements within groups
###
Page
These controls will only render when a page is selected.
Component ID
Description
Feature ID
Component ID
`ly.img.page.moveUp.canvasMenu`
Description
Move Up/Left button:
Moves the current page closer to the **start** of a multi-page document.
Feature ID
`ly.img.page.move`
Component ID
`ly.img.page.moveDown.canvasMenu`
Description
Move Down/Right button:
Moves the current page closer to the **end** of a multi-page document.
Feature ID
`ly.img.page.move`
##
Default Order
The default order of the Canvas Menu is the following:
###
Transform Mode
```
[
'ly.img.group.enter.canvasMenu',
'ly.img.group.select.canvasMenu',
'ly.img.page.moveUp.canvasMenu',
'ly.img.page.moveDown.canvasMenu',
'ly.img.separator',
'ly.img.text.edit.canvasMenu',
'ly.img.replace.canvasMenu',
'ly.img.separator',
'ly.img.placeholder.canvasMenu',
'ly.img.separator',
'ly.img.duplicate.canvasMenu',
'ly.img.delete.canvasMenu'
]
```
###
Text Mode
```
[
'ly.img.text.color.canvasMenu',
'ly.img.separator',
'ly.img.text.bold.canvasMenu',
'ly.img.text.italic.canvasMenu',
'ly.img.separator',
'ly.img.text.variables.canvasMenu'
]
```
[
Previous
Dock
](/docs/cesdk/ui/customization/api/dock/)[
Next
Inspector Bar
](/docs/cesdk/ui/customization/api/inspectorBar/)
Angular Image Editor SDK - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/solutions/photo-editor/angular/
CESDK/CE.SDK/Web Editor/Solutions/Photo Editor
# Angular Image Editor SDK
The CreativeEditor SDK provides a powerful and intuitive solution designed for seamless photo editing directly in the browser.
This CE.SDK configuration is fully customizable and offers a range of features that cater to various use cases, from simple photo adjustments and image compositions with background removal to programmatic editing at scale. Whether you are building a photo editing application for social media, e-commerce, or any other platform, the CE.SDK Angular Image Editor provides the tools you need to deliver a best-in-class user experience.
[Explore Demo](https://img.ly/showcases/cesdk/photo-editor-ui/web)
##
Key Capabilities of the CE.SDK Photo Editor

### Transform
Easily perform operations like cropping, rotating, and resizing your design elements to achieve the perfect composition.

### Asset Management
Import and manage stickers, images, shapes, and other assets to build intricate and visually appealing designs.

### Text Editing
Add and style text blocks with a variety of fonts, colors, and effects, giving users the creative freedom to express themselves.

### Client-Side Processing
All editing operations are performed directly in the browser, ensuring fast performance without the need for server dependencies.

### Headless & Automation
Programmatically edit designs using the engine API, allowing for automated workflows and advanced integrations within your application.

### Extendible
Enhance functionality with plugins and custom scripts, making it easy to tailor the editor to specific needs and use cases.

### Customizable UI
Design and integrate custom user interfaces that align with your application’s branding and user experience requirements.

### Background Removal
Utilize the powerful background removal plugin to allow users to effortlessly remove backgrounds from images, entirely on the Client-Side.

### Filters & Effects
Choose from a wide range of filters and effects to add professional-grade finishing touches to photos, enhancing their visual appeal.

### Size Presets
Access a variety of size presets tailored for different use cases, including social media formats and print-ready dimensions.
##
Browser Compatibility
The CE.SDK Design Editor is optimized for use in modern web browsers, ensuring compatibility with the latest versions of Chrome, Firefox, Edge, and Safari. See the full list of [supported browsers here](https://img.ly/docs/cesdk/faq/browser-support/).
##
Prerequisites
To get started with the CE.SDK Photo Editor, ensure you have the latest versions of **Node.js** and **NPM** installed.
##
Supported File Types
The CE.SDK Photo Editor supports loading, editing, and saving various image formats directly in the browser. Supported formats include:
* JPG
* PNG
* SVG
* WEBP
Exports can be made in formats such as JPG, PNG, and SVG, depending on your requirements.
##
Getting Started
If you're ready to start integrating CE.SDK into your Angular application, check out the CE.SDK [Getting Started guide](https://img.ly/docs/cesdk/engine/quickstart/). In order to configure the editor for an image editing use case consult our [photo editor UI showcase](https://img.ly/showcases/cesdk/photo-editor-ui/web#c) and its [reference implementation](https://github.com/imgly/cesdk-web-examples/tree/main/showcase-photo-editor-ui/src/components/case/CaseComponent.jsx).
##
Understanding CE.SDK Architecture & API
The following sections provide an overview of the key components of the CE.SDK photo editor UI and its API architecture.
###
CreativeEditor Photo UI
The CE.SDK photo editor UI is a specific configuration of the CE.SDK that focuses the Editor UI on essential photo editing features. It also includes our powerful background removal plugin that runs entirely on the user's device, saving on computing costs.
This configuration can be further modified to suit your needs. Key components include:

* **Canvas:** The primary workspace where users interact with their photo content.
* **Dock:** Provides access to tools and assets that are not directly related to the selected image or block, often used for adding or managing assets.
* **Inspector Bar:** Controls properties specific to the selected block, such as size, rotation, and other adjustments.
* **Canvas Menu:** Provides block-specific settings and actions such as deletion or duplication.
* **Navigation Bar:** Offers global actions such as undo/redo, zoom controls, and access to export options.
* **Canvas Bar:** For actions affecting the canvas or scene as a whole, such as adding pages or controlling zoom. This is an alternative place for actions like zoom or undo/redo.
Learn more about interacting with and customizing the photo editor UI in our design editor UI guide.
###
CreativeEngine
At the heart of CE.SDK is the CreativeEngine, which powers all rendering and design manipulation tasks. It can be used in headless mode or integrated with the CreativeEditor UI. Key features and APIs provided by CreativeEngine include:
* **Scene Management:** Create, load, save, and manipulate design scenes programmatically.
* **Block Manipulation:** Create and manage elements such as images, text, and shapes within the scene.
* **Asset Management:** Load and manage assets like images and SVGs from URLs or local sources.
* **Variable Management:** Define and manipulate variables for dynamic content within scenes.
* **Event Handling:** Subscribe to events such as block creation or selection changes for dynamic interaction.
##
API Overview
CE.SDK’s APIs are organized into several categories, each addressing different aspects of scene and content management. The engine API is relevant if you want to programmatically manipulate images to create or modify them at scale.
[**Scene API:**](https://img.ly/docs/cesdk/engine/api/scene/)
* **Creating and Loading Scenes**[:](https://img.ly/docs/cesdk/engine/guides/create-scene/)
```
engine.scene.create();
engine.scene.loadFromURL(url);
```
* **Zoom Control**[:](https://img.ly/docs/cesdk/engine/api/scene-zoom/#sceneapisetzoomlevel)
```
engine.scene.setZoomLevel(1.0);
engine.scene.zoomToBlock(blockId);
```
[**Block API:**](https://img.ly/docs/cesdk/engine/api/block/):
* **Creating Blocks**:
```
const block = engine.block.create('shapes/rectangle');
```
* **Setting Properties**:
```
engine.block.setColor(blockId, 'fill/color', { r: 1, g: 0, b: 0, a: 1 });
engine.block.setString(blockId, 'text/content', 'Hello World');
```
* **Querying Properties**:
```
const color = engine.block.getColor(blockId, 'fill/color');
const text = engine.block.getString(blockId, 'text/content');
```
[**Variable API:**](https://img.ly/docs/cesdk/engine/api/variables/)
* **Managing Variables**:
```
engine.variable.setString('myVariable', 'value');
const value = engine.variable.getString('myVariable');
```
[**Asset API:**](https://img.ly/docs/cesdk/engine/api/assets/#defining-a-custom-asset-source):
* **Managing Assets**:
```
engine.asset.add('image', 'https://example.com/image.png');
```
[**Event API:**](https://img.ly/docs/cesdk/engine/api/events/):
* **Subscribing to Events**:
```
// Subscribe to scene changes
engine.scene.onActiveChanged(() => {
const newActiveScene = engine.scene.get();
});
```
##
Basic Automation Example
The following automation example shows how to turn an image block into a square format for a platform such as Instagram:
```
// Assuming you have an initialized engine and a selected block (which is an image block)
const newWidth = 1080; // Width in pixels
const newHeight = 1080; // Height in pixels
const imageBlockId = engine.block.findByType('image')[0];
engine.block.setWidth(imageBlockId, newWidth);
engine.block.setHeight(imageBlockId, newHeight);
engine.block.setContentFillMode(imageBlockId, 'Cover');
```
##
Customizing the CE.SDK Photo Editor
CE.SDK provides extensive customization options, allowing you to tailor the UI and functionality to meet your specific needs. This can range from basic configuration settings to more advanced customizations involving callbacks and custom elements.
###
Basic Customizations
* **Configuration Object:** Customize the editor’s appearance and functionality by passing a configuration object during initialization.
```
const config = {
baseURL: 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.18.0/assets',
license: 'your-license-key',
locale: 'en',
theme: 'light'
};
```
* **Localization:** Adjust the editor’s language and labels to support different locales.
```
const config = {
i18n: {
en: {
'libraries.ly.img.insert.text.label': 'Add Caption'
}
}
};
```
* **Custom Asset Sources:** Serve custom sticker or shape assets from a remote URL.
###
UI Customization Options
* **Theme:** Choose between 'dark' or 'light' themes.
```
const config = {
theme: 'dark'
};
```
* **UI Components:** Enable or disable specific UI components as per your application’s needs.
```
const config = {
ui: {
elements: {
toolbar: true,
inspector: false
}
}
};
```
##
Advanced Customizations
For deeper customization, [explore the range of APIs](https://img.ly/docs/cesdk/ui/customization/) available for extending the functionality of the photo editor. You can customize the order of components, add new UI elements, and even develop your own plugins to introduce new features.
##
Plugins
For cases where encapsulating functionality for reuse is necessary, plugins provide an effective solution. Use our [guide on building plugins](https://img.ly/docs/cesdk/ui/customization/plugins/) to get started, or explore existing plugins like **Background Removal** and **Vectorizer**.
##
Framework Support
CreativeEditor SDK’s photo editor is compatible with Angular and other JavaScript frameworks like React, Vue.js, Svelte, Blazor, Next.js, and TypeScript. It also integrates well with desktop and server-side technologies such as Electron, PHP, Laravel, and Rails.
[
Vanilla JS
](/docs/cesdk/ui/quickstart/)[
Headless
](/docs/cesdk/engine/quickstart/)[
React
](/docs/cesdk/ui/quickstart?framework=react)[
Angular
](/docs/cesdk/ui/quickstart?framework=angular)[
Vue
](/docs/cesdk/ui/quickstart?framework=vue)[
Svelte
](/docs/cesdk/ui/quickstart?framework=svelte)[.electron\_svg\_\_cls-1{fill:#2b2e3a;fill-rule:evenodd}.electron\_svg\_\_cls-2{fill:#9feaf9}
Electron
](/docs/cesdk/ui/quickstart?framework=electron)[
Next.js
](/docs/cesdk/ui/quickstart?framework=nextjs)[
Node.js
](/docs/cesdk/ui/quickstart?platform=node)[
Apple
](/docs/cesdk/mobile-editor/quickstart/)[
Android
](/docs/cesdk/mobile-editor/quickstart?framework=composable&language=kotlin&platform=android)
Ready to get started?
With a free trial and pricing that fits your needs, it's easy to find the best solution for your product.
[Free Trial](https://img.ly/forms/free-trial)
### 500M+
video and photo creations are powered by IMG.LY every month

[
Previous
React
](/docs/cesdk/ui/solutions/photo-editor/react/)[
Next
Vue.js
](/docs/cesdk/ui/solutions/photo-editor/vuejs/)
Showing Notifications - CE.SDK | IMG.LY Docs [web/undefined/js] https://img.ly/docs/cesdk/ui/customization/api/notification/?platform=web&language=js
# Showing Notifications
The CE.SDK editor brings a notification API designed to deliver non-intrusive messages to the user, appearing in the lower right corner of the user interface. Use them to convey information without disrupting the user's current workflow. It provides a range of customization options to fit your specific needs.
* `cesdk.ui.showNotification(notification: string | Notification): string` displays a new notification to the user, accepting either a simple string message or a more complex notification object that allows for additional configuration options (detailed below). It returns an id of the notification.
* `cesdk.ui.updateNotification(notificationId: string, notification: Notification): updates a notification given by the id. All configuration options can be changed. If the` notificationId\` doesn't exist or the notification has already been dismissed, this action will have no effect.
* `cesdk.ui.dismissNotification(notificationId: string)` removes a notification identified by the provided notification `notificationId`. If the `notificationId` doesn't exist or the notification has already been dismissed, this action will have no effect.
###
Notification Options
All options apart from `message` are optional
Option
Description
Option
`message`
Description
The message displayed on the notification. This can either be a string or an internationalization (i18n) key from the CE.SDK translations, allowing for localized messages.
Option
`type`
Description
Notifications can be displayed in various styles, each differing in appearance to convey the appropriate context to the user. The available types include `info` (which is the default setting), `warning`, `error`, `success`, and `loading` (which displays a loading spinner).
Option
`duration`
Description
Notifications typically disappear after a set period, but the duration can vary based on the message's importance. Less critical updates may vanish swiftly, whereas warnings or significant alerts stay open for a longer time. You can specify this duration using either a numerical value representing milliseconds or predefined strings from CE.SDK, such as `short`, `medium` (which is the default setting), or `long`, each corresponding to different default durations. For notifications that should remain visible indefinitely, the `infinite` value can be used to prevent automatic dismissal.
Option
`onDismiss`
Description
A callback function that is triggered upon the dismissal of the notification, whether it's done automatically, programmatically, or manually by the user.
Option
`action: { label: "Retry", onClick: () => void }`
Description
Adds a single action button within the notification for user interaction.
Asset Library Entry - CE.SDK | IMG.LY Docs [web/undefined/javascript] https://img.ly/docs/cesdk/ui/customization/api/assetLibraryEntry/
CESDK/CE.SDK/Web Editor/Customization/API Reference
# Asset Library Entry
Learn how to configure what is shown in the asset library
An [Asset Source](/docs/cesdk/engine/api/assets/) is defined within the engine and can be seen as some sort of database of assets, it does not define how these assets are presented to the user. The web editor provides a versatile asset library that will display the assets in a user-friendly way inside a panel. However since an asset source does not provide any presentational information, the web editor needs to be told how to display the assets. This connection is made with an `Asset Library Entry`.
When you open the asset library, either by calling `openPanel` or adding a `ly.img.assetLibrary.dock` component to the dock, you must provide asset library entries. Only with these entries, the asset library will know what and how to display assets.
##
Managing Asset Library Entries
The CE.SDK web editor has an internal store of asset library entries that are referenced by asset libraries. You can find, add, remove, and update entries in this store.
```
CreativeEditorSDK.create('#cesdk', config).then(async (cesdk) => {
await cesdk.addDefaultAssetSources();
await cesdk.addDemoAssetSources();
await cesdk.createDesignScene();
// Find all asset library entries
const entryIds = cesdk.ui.findAllAssetLibraryEntries();
if (entryIds.includes('ly.img.image')) {
// Get the default image entry of the web editor
const entry = cesdk.ui.getAssetLibraryEntry('ly.img.image');
// ... to add a new source id.
cesdk.ui.updateAssetLibraryEntry('ly.img.image', {
sourceIds: [...entry.sourceIds, 'my.own.image.source'],
});
}
// Add a new custom asset library entry
cesdk.ui.addAssetLibraryEntry({
id: 'my.own.image.entry',
sourceIds: ['my.own.image.source'],
sceneMode: 'Design',
previewLength: 5,
previewBackgroundType: 'cover',
gridBackgroundType: 'cover',
gridColumns: 2
});
// Remove a default entry for stickers.
cesdk.ui.removeAssetLibraryEntry('ly.img.sticker');
```
Method
Description
Method
`findAllAssetLibraryEntries()`
Description
Returns all available asset library entries by their id.
Method
`addAssetLibraryEntry(entry)`
Description
Adds a new asset library entry to the store.
Method
`getAssetLibraryEntry(id)`
Description
Returns the asset library entry for the given id if present and `undefined` otherwise.
Method
`updateAssetLibraryEntry(id, entry)`
Description
Updates the asset library entry for the given id with the provided entry object. It does not replace the entry but is merged with a present entry.
Method
`removeAssetLibraryEntry(id)`
Description
Removes the asset library entry for the given id.
##
Using Asset Library Entries
Asset library entries are used by an asset library. How the library gets the entries depends on the context. The main use case for a library is the dock. This is described in the [Dock API](/docs/cesdk/ui/customization/api/dock/) documentation. We will describe further use cases here.
###
Replace Asset Library
The fill of a block can be replaced with another asset. What assets are applicable is different for each block. The web editor provides a function `setReplaceAssetLibraryEntries`. It gets a function that is used to define what block should be replaced with what asset. It will get the current context (most importantly the selected block) and will return ids to asset library entries that shall be used by the replace asset library.
```
cesdk.ui.setReplaceAssetLibraryEntries((context) => {
const { selectedBlocks, defaultEntryIds } = context;
// Most of the time replace makes only sense if one block is selected.
if (selectedBlocks.length !== 1) {
// If no entry ids are returned, a replace button will not be shown.
return [];
}
// id, block and fill type are provided for the selected block.
const { id, blockType, fillType } = selectedBlocks[0];
if (fillType === '//ly.img.ubq/fill/image') {
return ['my.own.image.entry'];
}
return [];
});
```
###
Background Tracks Asset Library
In the video timeline, the background track allows only certain type of assets. With `setBackgroundTrackAssetLibraryEntries` you can define what asset library entries are allowed for the background track when the user clicks on the "Add to Background Track" button.
```
// Only the image and video entries are allowed for the background track.
cesdk.ui.setBackgroundTrackAssetLibraryEntries(['ly.img.video', 'ly.img.video']);
```
##
Asset Library Entry Definition
###
Define What to Display
The following properties tell the asset library what data should be queried and displayed.
Property
Type
Description
Property
`id`
Type
`string`
Description
The unique id of this entry that is referenced by other APIs and passed to the asset library.
Property
`sourceIds`
Type
`string[]`
Description
Defines what asset sources should be queried by the asset library.
Property
`excludeGroups`
Type
`string[]`
Description
If the asset sources support groups, these will be excluded and not displayed.
Property
`includeGroups`
Type
`string[]`
Description
If the asset sources support groups, only these will be displayed and all other groups will be ignored.
Property
`sceneMode`
Type
`'Design'` or `'Video'`
Description
If set, the asset library will use this entry exclusively in the respective scene mode.
###
Define How to Display
Besides properties that define what data should be displayed, there are also properties that specify how the data should be displayed to meet specific use case requirements.
####
Preview and Grid
Some settings are for the preview and some for the grid view. If multiple asset sources or groups within a source are used, the asset library will show short sections with only a few assets shown. This is what we call the preview. The grid view is the main view where all assets are shown.
Property
Type
Description
Property
`title`
Type
`string` or `((options: { group?: string; sourceId?: string }) => string`
Description
Use for custom translation in the overviews for a group or a source. If undefined is returned by the function it will be handled like there wasn't a title function set at all.
Property
`canAdd`
Type
`boolean'` or `'(sourceId: string) => boolean'`
Description
If `true` an upload button will be shown and the uploaded file will be added to the source. Please note that the asset source needs to support `addAsset` as well.
Property
`canRemove`
Type
`boolean'` or `'(sourceId: string) => boolean'`
Description
If `true` a remove button will be shown which will remove the asset from the source. Please note that the asset source needs to support `removeAsset` as well.
Property
`previewLength`
Type
`number`
Description
Defines how many assets will be shown in a preview section of a source or group.
Property
`previewBackgroundType`
Type
`cover` or `contain`
Description
If the thumbUri is set as a background that will be contained or covered by the card in the preview view.
Property
`gridBackgroundType`
Type
`cover` or `contain`
Description
If the thumbUri is set as a background that will be contained or covered by the card in the grid view.
Property
`gridColumns`
Type
`number`
Description
Number of columns in the grid view.
Property
`gridItemHeight`
Type
`auto` or `square`
Description
The height of an item in the grid view:
\- `auto` automatically determines height yielding a masonry-like grid view.
\- `square` every card will have the same square size.
Property
`cardBorder`
Type
`boolean`
Description
Draws a border around the card if set to true.
Property
`cardLabel`
Type
`(assetResult: AssetResult) => string`
Description
Overwrites the label of a card for a specific asset result
Property
`cardLabelPosition`
Type
`(assetResult: AssetResult) => 'inside' or 'below'`
Description
Position of the label `inside` or `below` the card.
Property
`cardLabelTruncateLines`
Type
`(assetResult: AssetResult) => 'single' or 'multi'`
Description
Controls label truncation to occur at end of first line (`single`), or at end of second line (`multi`).
Property
`cardBackground`
Type
`CardBackground[]`
Description
Determines what will be used as the card background from the asset and in which priorities. The first preference for which the `path` returns a value will be used to decide what and how the background will be rendered. E.g. a path of `meta.thumbUri` will look inside the asset for a value `asset.meta.thumbUri`. This non-null value will be used.
The type of preference decides how the card will render the background.
`svgVectorPath` creates a `