const { imageHelpers } = window.canva;
const canva = window.canva.init();
canva.onReady(async (opts) => {
const image = await imageHelpers.fromElement(opts.element);
state.canvas = await imageHelpers.toCanvas(image);
document.body.appendChild(state.canvas);
canva.onControlsEvent(async (opts) => {
if (!opts.message.commit) {
if (opts.message.controlId === "touchModeButton") {
if (state.touchModeEnabled) {
await disableTouchMode(true);
canva.onTouchModeExit((opts) => {
disableTouchMode(opts.commit);
canva.onSaveRequest(async () => {
return await imageHelpers.fromCanvas("image/jpeg", state.canvas);
function renderControls() {
label: state.touchModeEnabled
canva.updateControlPanel(controls);
async function enableTouchMode() {
// Keep track of the previous image
canva.toggleSpinner("preview", true);
state.previousBlob = await imageHelpers.fromCanvas(
canva.toggleSpinner("preview", false);
state.touchModeEnabled = true;
canva.toggleTouchMode(true);
// Set the height of the "html" and "body" elements
document.querySelector("html").style.height = "100%";
document.body.style.height = "100%";
// Center everything in the "body" element
document.body.style.display = "grid";
document.body.style.alignItems = "center";
document.body.style.justifyContent = "center";
// Don't stretch the canvas to the edges of the iframe
state.canvas.style.width = null;
state.canvas.style.height = null;
// Don't let the canvas extend beyond the dimensions of the iframe
state.canvas.style.maxWidth = "100%";
state.canvas.style.maxHeight = "100%";
// Register event handlers
state.canvas.onpointerdown = handlePointerDown;
state.canvas.onpointermove = handlePointerMove;
state.canvas.onpointerup = handlePointerUp;
// Re-render the controls
async function disableTouchMode(commit) {
state.touchModeEnabled = false;
canva.toggleTouchMode(false);
// Reset the image if the user clicks the "Cancel" button
document.body.removeChild(state.canvas);
state.canvas = await imageHelpers.toCanvas(state.previousBlob);
document.body.appendChild(state.canvas);
// Reset the width of the canvas
state.canvas.style.width = "100%";
state.canvas.style.height = "100%";
state.canvas.onpointerdown = null;
state.canvas.onpointermove = null;
state.canvas.onpointerup = null;
// Re-render the controls
function handlePointerDown(event) {
const context = state.canvas.getContext("2d");
const { x, y } = getMousePosition(state.canvas, event);
function handlePointerMove(event) {
const context = state.canvas.getContext("2d");
const { x, y } = getMousePosition(state.canvas, event);
function handlePointerUp() {
function getMousePosition(canvas, event) {
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
x: (event.clientX - rect.left) * scaleX,
y: (event.clientY - rect.top) * scaleY,