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

组件接收的外部传入的属性

属性名
属性标识
类型
说明
Canvas类型typestring

指定Canvas类型

示例:"2d"

模板templatestring

指定Canvas模板

示例:"2d"

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

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

示例:false

Event Description

组件暴露的事件,可以监听组件的事件来触发一些外部的动作

事件名
事件code
事件出参 event.detail
适用情况
说明
canvas渲染完成canvasReadyobject
  • canvasInstance: object Canvas实例

    获取 canvas 元素的引用

    • canvasCtx: object Canvas上下文

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

      移动端,PC端,小程序

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

      点击clickobject
      • e: Event 对象
      PC端

      -

      双击dblclickobject
      • e: Event 对象
      PC端

      -

      手指/鼠标长按longtap移动端,PC端,小程序

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

      手指触摸开始touchstart移动端,小程序

      手指触摸动作开始

      手指触摸结束touchend移动端,小程序

      手指触摸动作结束

      手指触摸移动touchmove移动端,小程序

      手指触摸后移动

      手指触摸被打断touchcancel小程序

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

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

      -

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

      -

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

      -

      错误error移动端,PC端,小程序

      当发生错误时触发 error 事件

      Property API

      通过属性 API,可以获取组件内部的状态和属性值,可以通过$w.componentId.propertyName 来访问组件内部的值,如 $w.input1.value ,详请请参考 属性 API

      只读属性名
      属性标识
      类型
      说明
      Canvas类型typestring

      指定Canvas类型

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

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

      Canvas实例canvasInstanceobject

      获取 canvas 元素的引用

      Canvas上下文canvasCtxobject

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

      Method API

      Style API

      通过样式 API,可以覆盖组件中内部元素的样式来实现自定义,例如在低代码编辑器中中通过 #wd-page-root .wd-btn 即可为所有的按钮组件编写样式,通过 :scope 可以控制单个组件样式, 详细说明请参考样式 API

      名称
      类名
      说明和示例
      根元素.wd-canvascanvas组件根元素
      /* :scope 指的是当前组件元素 */
      /* 具体可参考样式 API 文档 */
      :scope.wd-canvas {
        /* 在这里编写CSS 样式 */
      }
      PC 端canvas组件根元素.wd-pc-canvas可以为 PC 端的canvas编写样式
      /* :scope 指的是当前组件元素 */
      /* 具体可参考样式 API 文档 */
      :scope.wd-pc-canvas {
        /* 在这里编写CSS 样式 */
      }
      H5 端canvas组件根元素.wd-h5-canvas可以为 H5 端的canvas编写样式
      /* :scope 指的是当前组件元素 */
      /* 具体可参考样式 API 文档 */
      :scope.wd-h5-canvas {
        /* 在这里编写CSS 样式 */
      }
      小程序canvas端组件根元素.wd-mp-canvas可以为小程序端的canvas编写样式
      /* :scope 指的是当前组件元素 */
      /* 具体可参考样式 API 文档 */
      :scope.wd-mp-canvas {
        /* 在这里编写CSS 样式 */
      }

      了解样式 API