Skip to content

Create From HTMLCanvas

In this example, we will show you how to initialize the CreativeEditor SDK with an initial image provided from a 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<number> 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 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.

Full Code

Here’s the full code:

import CreativeEngine from 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.51.0/index.js';
// Draw the text 'img.ly' to the demo canvas
const canvas = document.getElementById('my-canvas');
const ctx = canvas.getContext('2d');
ctx.font = '100px Arial';
ctx.fillText('img.ly', 120, 270);
const dataURL = canvas.toDataURL();
const config = {
license: 'mtLT-_GJwMhE7LDnO8KKEma7qSuzWuDxiKuQcxHKmz3fjaXWY2lT3o3Z2VdL5twm',
userId: 'guides-user',
baseURL: 'https://cdn.img.ly/packages/imgly/cesdk-engine/1.51.0/assets',
};
CreativeEngine.init(config).then(async engine => {
let scene = await engine.scene.createFromImage(dataURL);
// Find the automatically added graphic block with an image fill in the scene.
const block = engine.block.findByType('graphic')[0];
// Change its opacity.
engine.block.setOpacity(block, 0.5);
// Attach engine canvas to DOM
document.getElementById('cesdk_container').append(engine.element);
});