Canvas
WdCanvas
Basic Capabilities Description
- The basic properties of the canvas provide two types for selection: 2d and webgl.
- 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
Name | Type | Default Value | Meaning |
---|---|---|---|
canvasRect | Object | {} | Stores the element information of the canvas during touch/click events (top, left, clientX, clientY, etc.) |
isMouseDown | Boolean | false | Whether the touch has started or the mouse button is pressed down |
canvasClear | Function | See description below | Clears the canvas |
canvasReady | Function | See description below | Initializes the canvas when rendering is complete |
canvasSave | Function | See description below | Converts the canvas content to an image |
mousedown | Function | See description below | Handles touch start or mouse down events |
mousemove | Function | See description below | Handles touch move or mouse move events |
mouseup | Function | See description below | Handles touch end or mouse up events |
- 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();
}
- 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);
}
- 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}` });
}
}
}
- 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);
}
- 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();
}
}
- mouseup function
export default function ({ event, data }) {
$w.page.dataset.state.isMouseDown = false;
$w.canvas1.canvasCtx.closePath();
}
Binding canvas events
Property Description
组件接收的外部传入的属性
属性名 | 属性标识 | 类型 | 说明 |
---|
Canvas类型 | type | string | 指定Canvas类型 示例:"2d" |
模板 | template | string | 指定Canvas模板 示例:"2d" |
函数 | code | object | |
禁止屏幕滚动及下拉刷新 | disableScroll | boolean | 当在 Canvas 中移动时且有绑定手势事件时,禁止屏幕滚动以及下拉刷新 示例:false |
Event Description
组件暴露的事件,可以监听组件的事件来触发一些外部的动作
事件名 | 事件code | 事件出参 event.detail | 适用情况 | 说明 |
---|
canvas渲染完成 | canvasReady | object
| 移动端,PC端,小程序 | 用户选中的数据发生改变时触发,出参所选节点数据 |
点击 | click | object
| PC端 | - |
双击 | dblclick | object
| PC端 | - |
手指/鼠标长按 | longtap | 移动端,PC端,小程序 | 手指/鼠标长按 500ms 之后触发,触发了长按事件后进行移动不会触发屏幕的滚动 | |
手指触摸开始 | touchstart | 移动端,小程序 | 手指触摸动作开始 | |
手指触摸结束 | touchend | 移动端,小程序 | 手指触摸动作结束 | |
手指触摸移动 | touchmove | 移动端,小程序 | 手指触摸后移动 | |
手指触摸被打断 | touchcancel | 小程序 | 手指触摸动作被打断,如来电提醒,弹窗 | |
鼠标按下 | mousedown | object
| PC端 | - |
鼠标抬起 | mouseup | object
| PC端 | - |
鼠标移动 | mousemove | object
| PC端 | - |
错误 | error | 移动端,PC端,小程序 | 当发生错误时触发 error 事件 |
Property API
通过属性 API,可以获取组件内部的状态和属性值,可以通过$w.componentId.propertyName
来访问组件内部的值,如 $w.input1.value
,详请请参考 属性 API
只读属性名 | 属性标识 | 类型 | 说明 |
---|
Canvas类型 | type | string | 指定Canvas类型 |
函数 | code | object | |
禁止屏幕滚动及下拉刷新 | disableScroll | boolean | 当在 Canvas 中移动时且有绑定手势事件时,禁止屏幕滚动以及下拉刷新 |
Canvas实例 | canvasInstance | object | 获取 canvas 元素的引用 |
Canvas上下文 | canvasCtx | object | getContext() 方法返回的对象,该对象提供了用于在画布上绘图的方法和属性 |
Method API
无Style API
通过样式 API,可以覆盖组件中内部元素的样式来实现自定义,例如在低代码编辑器中中通过 #wd-page-root .wd-btn
即可为所有的按钮组件编写样式,通过 :scope
可以控制单个组件样式, 详细说明请参考样式 API
名称 | 类名 | 说明和示例 |
---|
根元素 | .wd-canvas | canvas组件根元素
|
PC 端canvas组件根元素 | .wd-pc-canvas | 可以为 PC 端的canvas编写样式
|
H5 端canvas组件根元素 | .wd-h5-canvas | 可以为 H5 端的canvas编写样式
|
小程序canvas端组件根元素 | .wd-mp-canvas | 可以为小程序端的canvas编写样式
|