Skip to main content

Canvas

WdCanvas

Basic Capabilities Description

  1. The basic properties of the canvas provide two types for selection: 2d and webgl.
  2. Under different canvas types, each provides a set of sample templates for user reference.

Extended Scenarios Description

Example: How to Set Page Watermark

The expected effect is as follows:

Configuration Method 1

Add a canvas component, which by default renders a 2D watermark effect. Uncomment the relevant code in the initialization code to implement it.

Configuration Method 2

Add a canvas component and implement the js method by binding events via canvas rendering. The js method can be referred to.

export default function({event, data}) {
//Get the canvas instance
const canvas = $w.wdCanvas2.canvasInstance;
//Get the canvas context
const ctx = $w.wdCanvas2.canvasCtx;
if (ctx && canvas && $w.wdCanvas2?.type === '2d') {
// Using fixed on the web end does not occupy space, achieving overlapping with other elements.
canvas.style.position = 'fixed';
canvas.style.top = '0';
canvas.style.left = '0';
canvas.style.zIndex = 1;
canvas.style.pointerEvents = 'none';

/** On the web end, using window.innerWidth and window.innerHeight allows the watermark to cover the entire screen. */
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
/** To achieve the above effect in mini programs, 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 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 and canvas context through $w.componentId.canvasInstance and w.componentId.canvasCtx respectively.

Note: Due to platform differences between the Web end and mini programs, adaptations may be required for certain APIs. When using these APIs, ensure to follow the best practices of each respective platform.

Application Scenarios Description

Handwritten Signature

Note: In canvas applications, handwritten signature is a relatively common use case. To implement a cross-platform compatible handwritten signature feature using the canvas component, the following operations are required:

Define variables and functions for the canvas page
NameTypeDefault ValueMeaning
canvasRectObject{}Stores the element information of the canvas during touch/click events (top, left, clientX, clientY, etc.)
isMouseDownBooleanfalseWhether the touch has started or the mouse button is pressed down
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 belowHandles touch start or mouse down events
mousemoveFunctionSee description belowHandles touch move or mouse move events
mouseupFunctionSee description belowHandles touch end or mouse up events
  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 needed, 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();
}
Binding canvas events

Property Description

External properties received by the component

Property Name
Property Identifier
Type
Description
禁止屏幕滚动及下拉刷新disableScrollboolean

当在 Canvas 中移动时且有绑定手势事件时,禁止屏幕滚动以及下拉刷新

Example: false

Canvas类型typestring

指定Canvas类型

Example: "2d"

模板templatestring

指定Canvas模板

Example: "2d"

函数codeobject

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渲染完成canvasReadyobject
  • canvasInstance: object Canvas实例

    获取 canvas 元素的引用

    • canvasCtx: object Canvas上下文

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

      Mobile,PC,Mini Program

      用户选中的数据发生改变时触发,出参所选节点数据

      点击clickobject
      • e: Event 对象
      PC

      -

      双击dblclickobject
      • e: Event 对象
      PC

      -

      手指/鼠标长按longtapMobile,PC,Mini Program

      手指/鼠标长按 500ms 之后触发,触发了长按事件后进行移动不会触发屏幕的滚动

      手指触摸开始touchstartMobile,Mini Program

      手指触摸动作开始

      手指触摸结束touchendMobile,Mini Program

      手指触摸动作结束

      手指触摸移动touchmoveMobile,Mini Program

      手指触摸后移动

      手指触摸被打断touchcancelMini Program

      手指触摸动作被打断,如来电提醒,弹窗

      鼠标按下mousedownobject
      • e: Event 对象
      PC

      -

      鼠标抬起mouseupobject
      • e: Event 对象
      PC

      -

      鼠标移动mousemoveobject
      • e: Event 对象
      PC

      -

      错误errorMobile,PC,Mini Program

      当发生错误时触发 error 事件

      Property 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类型typestring

      指定Canvas类型

      函数codeobject
      禁止屏幕滚动及下拉刷新disableScrollboolean

      当在 Canvas 中移动时且有绑定手势事件时,禁止屏幕滚动以及下拉刷新

      Canvas实例canvasInstanceobject

      获取 canvas 元素的引用

      Canvas上下文canvasCtxobject

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

      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
      根元素.wd-canvascanvas组件根元素
      /* :scope refers to the current component element */
      /* For details, refer to the Style API documentation */
      :scope.wd-canvas {
        /* Write CSS styles here */
      }
      PC 端canvas组件根元素.wd-pc-canvas可以为 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组件根元素.wd-h5-canvas可以为 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 */
      }
      小程序canvas端组件根元素.wd-mp-canvas可以为小程序端的canvas编写样式
      /* :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