Skip to main content

Canvas

WdCanvas

Basic Capabilities Description

  1. The basic properties of canvas provide two types, 2d and webgl, to choose from.
  2. Under different canvas types, each provides a set of example templates for user reference.

Extended Scenarios Description

Example: How to Set Up Page Watermark

The expected effect is as follows:

Image ba6118c9a8772d7828256e153db4be4b**Configuration Method 1**

Add a canvas component, which by default renders a 2D watermark effect. To achieve this, uncomment the relevant code in the initialization code.

Image 5c78e03c01478c0cff4ca7037cac48d8

Configuration Method 2

Add a canvas component and implement event binding via canvas rendering using a js method. For the js method, refer to the following:

export default function({event, data}) {
// Obtain the canvas instance
const canvas = $w.wdCanvas2.canvasInstance;
// obtain the canvas context
const ctx = $w.wdCanvas2.canvasCtx;
if (ctx && canvas && $w.wdCanvas2?.type === '2d') {
// On the web side, using fixed positioning avoids occupying space and enables overlapping with other elements.
canvas.style.position = 'fixed';
canvas.style.top = '0';
canvas.style.left = '0';
canvas.style.zIndex = 1;
canvas.style.pointerEvents = 'none';

/** Using window.innerWidth and window.innerHeight on the web side allows the watermark to cover the entire screen. */
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
/** On the Mini Program side, if you want to achieve the above effect, you can directly set the style of the canvas component. */
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = '24px Arial';
ctx.setFillStyle('rgba(0, 0, 0, 0.1)');
ctx.setTextAlign('center');
ctx.setTextBaseline('middle');
ctx.rotate(Math.PI / 180 * 45);

for (let x = 0; x < canvas.width * 2; x += 140) {
for (let y = -canvas.height; y < canvas.height; y += 100) {
ctx.fillText('I am a watermark', x, y);
}
}
ctx.draw(true);
}
}

Note: The canvas component is implemented based on the standard Web and Mini Program canvas APIs. Therefore, you can use standard APIs to manipulate the canvas component. The platform supports obtaining the canvas instance via $w.componentID.canvasInstance and the canvas context via w.componentID.canvasCtx.

Note: Due to platform differences between Web and Mini Program platforms, certain APIs may require adaptation. When using these APIs, ensure compliance with best practices for each respective platform.

Application Scenarios Description

Handwritten Signature

Note: In canvas applications, handwritten signatures are a common usage scenario. To implement this feature with cross-platform compatibility across three ends using the canvas component, the following operations are required:`

Define variables and functions for the page containing the canvas
NameTypeDefault ValueDescription
canvasRectObject{}Stores the canvas element information on touch/click (top, left, clientX, clientY, etc.)
isMouseDownBooleanfalseWhether touch or mouse down is active
canvasClearFunctionSee description belowClears the canvas
canvasReadyFunctionSee description belowInitializes the canvas when rendering is complete
canvasSaveFunctionSee description belowConverts the canvas content to an image
mousedownFunctionSee description belowFinger touch start or mouse down
mousemoveFunctionSee description belowFinger touch move or mouse move
mouseupFunctionSee description belowFinger touch end or mouse up
  1. canvasClear function
export default function ({ event, data }) {
$w.canvas1.canvasCtx.clearRect(
0,
0,
$w.canvas1.canvasInstance.width,
$w.canvas1.canvasInstance.height
);

$w.canvas1.canvasCtx.setFillStyle('white');
$w.canvas1.canvasCtx.fillRect(
0,
0,
$w.canvas1.canvasInstance.width,
$w.canvas1.canvasInstance.height
);
$w.canvas1.canvasCtx.draw();
}
  1. canvasReady function
export default function ({ event, data }) {
$w.canvas1.canvasCtx.setFillStyle('white');
$w.canvas1.canvasCtx.fillRect(
0,
0,
$w.canvas1.canvasInstance.width,
$w.canvas1.canvasInstance.height
);
$w.canvas1.canvasCtx.draw();

if (!$w.wedaContext.platforms.includes('MP')) return;
const { pixelRatio: dpr } = wx.getSystemInfoSync() || {};

if (!dpr) return;
$w.canvas1.canvasCtx.scale(dpr, dpr);
}
  1. canvasSave function
export default function ({ event, data }) {
if ($w.wedaContext.platforms.includes('MP')) {
$w.canvas1.canvasCtx.draw(
true,
wx.canvasToTempFilePath({
quality: 1,
canvas: $w.canvas1.canvasInstance,
async success(res) {
console.log('image: ', res.tempFilePath);
$w.utils.showToast({ title: 'Image generated successfully' });
// If cloud storage is required, execute the following code. For file storage details, see https://docs.cloudbase.net/api-reference/webv2/storage#uploadfile
// const cloud = await $w.cloud.getCloudInstance();
// const upload = await cloud.uploadFile({
// cloudPath: 'test.png',
// filePath: res.tempFilePath,
// })
},
fail: (e) => {
console.log('fail', e);
$w.utils.showToast({ title: `Image generation failed: ${e}` });
},
})
);
} else {
try {
const dataUrl = $w.canvas1.canvasInstance.toDataURL();
console.log('image: ', dataUrl);
$w.utils.showToast({ title: 'Image generated successfully' });
} catch (e) {
console.log('fail', e);
$w.utils.showToast({ title: `Image generation failed: ${e}` });
}
}
}
  1. mousedown function
export default async function ({ event, data }) {
event.detail?.e?.preventDefault?.();
const touches =
event.changedTouches?.[0] ||
event.detail?.e?.changedTouches?.[0] ||
event.detail?.e ||
{};
const { clientX, clientY } = touches;
const { left, top } = await $w.canvas1.canvasInstance.getCanvasRectInfo();
$page.dataset.state.canvasRect = { left, top };
const x = clientX - left;
const y = clientY - top;

$w.page.dataset.state.isMouseDown = true;
$w.canvas1.canvasCtx.beginPath();
$w.canvas1.canvasCtx.moveTo(x, y);
}
  1. mousemove function
export default function ({ event, data }) {
if ($w.page.dataset.state.isMouseDown) {
event.detail?.e?.preventDefault?.();
const touches =
event.changedTouches?.[0] ||
event.detail?.e?.changedTouches?.[0] ||
event.detail?.e ||
{};
const { clientX, clientY } = touches;
const { left, top } = $page.dataset.state.canvasRect;
const x = clientX - left;
const y = clientY - top;

$w.canvas1.canvasCtx.lineTo(x, y);
$w.canvas1.canvasCtx.stroke();
}
}
  1. mouseup function
export default function ({ event, data }) {
$w.page.dataset.state.isMouseDown = false;
$w.canvas1.canvasCtx.closePath();
}
Bind canvas Events
Image 9acfd489-d56f-423d-b8aa-d00e95e163e1

Property Description

External properties received by the component

Property Name
Property Identifier
Type
Description
Forbid screen scrolling and pull-down refreshdisableScrollboolean

When moving in Canvas with a gesture event bound, forbid screen scroll and pull-down refresh

Example: false

Canvas typetypestring

Canvas type

Example: "2d"

Templatetemplatestring

Designate a Canvas template

Example: "2d"

functioncodeobject

Event Description

Events exposed by the component. You can listen to component events to trigger external actions

Event Name
Event Code
Event Output Parameters event.detail
Applicable Scenarios
Description
canvas rendering donecanvasReadyobject
  • canvasInstance: object Canvas实例

    获取 canvas 元素的引用

    • canvasCtx: object Canvas上下文

      getContext() 方法返回的对象,该对象提供了用于在画布上绘图的方法和属性

      Mobile,PC,Mini Program

      Trigger when the selected data changes, output the selected node data

      clickclickobject
      • e: Event 对象
      PC

      -

      double-clickdblclickobject
      • e: Event 对象
      PC

      -

      finger/mouse long presslongtapMobile,PC,Mini Program

      Long press with finger/mouse for 500ms to trigger, then move after the long press event to avoid triggering screen scroll

      Finger touch starttouchstartMobile,Mini Program

      Finger touch action start

      Touch EndtouchendMobile,Mini Program

      Finger touch action complete

      Finger touch and movetouchmoveMobile,Mini Program

      Finger touch and move

      Finger touch interruptedtouchcancelMini Program

      Finger touch action interrupted, such as call reminder or pop-up

      mouse pressmousedownobject
      • e: Event 对象
      PC

      -

      Mouse upmouseupobject
      • e: Event 对象
      PC

      -

      mouse movementmousemoveobject
      • e: Event 对象
      PC

      -

      errorerrorMobile,PC,Mini Program

      When an error occurs, trigger an error event

      Properties API

      Through the Property API, you can access the internal state and property values of components. You can access internal values using$w.componentId.propertyName, such as $w.input1.value. For details, please refer to Property API

      Read-only Property Name
      Property Identifier
      Type
      Description
      Canvas typetypestring

      Canvas type

      functioncodeobject
      Forbid screen scrolling and pull-down refreshdisableScrollboolean

      When moving in Canvas with a gesture event bound, forbid screen scroll and pull-down refresh

      Canvas instancecanvasInstanceobject

      Get the canvas element reference

      Canvas contextcanvasCtxobject

      The object returned by the getContext() method provides methods and properties for plotting on canvas.

      Method API

      None

      Style API

      Through the Style API, you can override the styles of internal elements in components to achieve customization. For example, in the low-code editor, you can write styles for all button components using #wd-page-root .wd-btn, and control individual component styles with :scope. For detailed instructions, please refer toStyle API

      Name
      Class Name
      Description and Examples
      root element.wd-canvascanvas component root element
      /* :scope refers to the current component element */
      /* For details, refer to the Style API documentation */
      :scope.wd-canvas {
        /* Write CSS styles here */
      }
      PC-side canvas component root element.wd-pc-canvasWrite style for PC canvas
      /* :scope refers to the current component element */
      /* For details, refer to the Style API documentation */
      :scope.wd-pc-canvas {
        /* Write CSS styles here */
      }
      H5 canvas component root element.wd-h5-canvasWrite style for H5 canvas
      /* :scope refers to the current component element */
      /* For details, refer to the Style API documentation */
      :scope.wd-h5-canvas {
        /* Write CSS styles here */
      }
      Mini Program canvas Component Root Element.wd-mp-canvasCan write styles for canvas in the mini program
      /* :scope refers to the current component element */
      /* For details, refer to the Style API documentation */
      :scope.wd-mp-canvas {
        /* Write CSS styles here */
      }

      Learn about Style API