### WebGL Initialization and Basic Setup
Source: https://developers.weixin.qq.com/miniprogram/dev/component/canvas.html
Initializes a WebGL rendering context for the canvas. Requires specifying `type="webgl"`. This example sets a clear color and clears the buffer.
```html
```
```javascript
// canvas.js
Page({
onReady() {
const query = wx.createSelectorQuery()
query.select('#myCanvas').node().exec((res) => {
const canvas = res[0].node
const gl = canvas.getContext('webgl')
gl.clearColor(1, 0, 1, 1)
gl.clear(gl.COLOR_BUFFER_BIT)
})
}
})
```
--------------------------------
### Video Component Example
Source: https://developers.weixin.qq.com/miniprogram/dev/component/video.html
This example demonstrates how to use the video component, including playing videos, sending danmaku (bullet comments), choosing videos from the album or camera, and handling picture-in-picture mode. It requires the `wx.createVideoContext` API to control the video playback.
```javascript
function getRandomColor() {
const rgb = []
for (let i = 0; i < 3; ++i) {
let color = Math.floor(Math.random() * 256).toString(16)
color = color.length === 1 ? '0' + color : color
rgb.push(color)
}
return '#' + rgb.join('')
}
Page({
onShareAppMessage() {
return {
title: 'video',
path: 'page/component/pages/video/video'
}
},
onReady() {
this.videoContext = wx.createVideoContext('myVideo')
},
onHide() {
},
inputValue: '',
data: {
src: '',
danmuList:
[{ text: '第 1s 出现的弹幕',
color: '#ff0000',
time: 1
}, {
text: '第 3s 出现的弹幕',
color: '#ff00ff',
time: 3
}],
},
bindInputBlur(e) {
this.inputValue = e.detail.value
},
bindButtonTap() {
const that = this
wx.chooseVideo({
sourceType: ['album', 'camera'],
maxDuration: 60,
camera: ['front', 'back'],
success(res) {
that.setData({
src: res.tempFilePath
})
}
})
},
bindVideoEnterPictureInPicture() {
console.log('进入小窗模式')
},
bindVideoLeavePictureInPicture() {
console.log('退出小窗模式')
},
bindPlayVideo() {
console.log('1')
this.videoContext.play()
},
bindSendDanmu() {
this.videoContext.sendDanmu({
text: this.inputValue,
color: getRandomColor()
})
},
videoErrorCallback(e) {
console.log('视频错误信息:')
console.log(e.detail.errMsg)
}
})
```
--------------------------------
### Cover-View Example
Source: https://developers.weixin.qq.com/miniprogram/dev/component/cover-view.html
Basic example demonstrating the usage of the cover-view component, including data binding and share functionality.
```javascript
Page({
onShareAppMessage() {
return {
title: 'cover-view',
path: 'page/component/pages/cover-view/cover-view'
}
},
data: {
latitude: 23.099994,
longitude: 113.324520,
}
})
```
--------------------------------
### Starting a Particle System
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/particles/emiter.html
Call the `start()` function on a particle component instance to play the particle effect. An optional delay in seconds can be provided as an argument.
```javascript
particleComponent.start() // 可以设置参数,如: particleComponent.start(2), 延时二秒启动
```
--------------------------------
### wx-selection Component Example
Source: https://developers.weixin.qq.com/miniprogram/dev/component/selection.html
This example demonstrates the basic usage of the wx-selection component. Ensure that the text or rich-text components within wx-selection have user-select set to true and an id if firstNodeId and lastNodeId are needed.
```xml
This is selectable text.
```
--------------------------------
### Get Scene Instance via Event
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/core/scene.html
In user小程序 scripts, the scene instance can be obtained through the `ready` event.
```html
......
```
```javascript
// 小程序脚本中绑定的事件
handleReady({detail}) {
const scene = detail.value;
}
```
--------------------------------
### Editor Context API Example
Source: https://developers.weixin.qq.com/miniprogram/dev/component/editor.html
This example shows how to get the editor's context and use its methods, such as setContents, to programmatically set the editor's content. It's recommended to use delta format for insertion to avoid parsing errors with HTML.
```javascript
const editor = requirePlugin('editor');
const context = editor.createEditorContext('editorId');
// Set content using delta format
context.setContents({
delta: [
{ insert: 'Hello ' },
{ insert: 'World', attributes: { bold: true } },
{ insert: '\n' }
]
});
// Or set content using HTML (use with caution)
// context.setContents({
// html: '
Hello World
'
// });
// Get content
context.getContents({
success: function(res) {
console.log(res.html);
console.log(res.text);
console.log(res.delta);
}
});
```
--------------------------------
### Creating a PointEmitter via Code
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/particles/emiter.html
This example demonstrates how to dynamically create a PointEmitter using code. It requires obtaining an element instance and its corresponding component first.
```javascript
particleComponent.createPointEmitter(direction1, direction2)
```
--------------------------------
### Swiper Component Example
Source: https://developers.weixin.qq.com/miniprogram/dev/component/swiper.html
This code demonstrates the basic setup and event handling for the Swiper component in a WeChat Mini Program. It includes data properties for configuration and functions to handle changes in indicator dots, autoplay, interval, and duration.
```javascript
Page({
onShareAppMessage() {
return {
title: 'swiper',
path: 'page/component/pages/swiper/swiper'
}
},
data: {
background: ['demo-text-1', 'demo-text-2', 'demo-text-3'],
indicatorDots: true,
vertical: false,
autoplay: false,
interval: 2000,
duration: 500
},
changeIndicatorDots() {
this.setData({
indicatorDots: !this.data.indicatorDots
})
},
changeAutoplay() {
this.setData({
autoplay: !this.data.autoplay
})
},
intervalChange(e) {
this.setData({
interval: e.detail.value
})
},
durationChange(e) {
this.setData({
duration: e.detail.value
})
}
})
```
--------------------------------
### Mini Program Navigation from Web-view
Source: https://developers.weixin.qq.com/miniprogram/dev/component/web-view.html
Examples of using JSSDK to navigate within the mini program from a web-view. Ensure the JSSDK is included in your web page.
```javascript
//
// javascript
wx.miniProgram.navigateTo({url: '/path/to/page'})
wx.miniProgram.postMessage({ data: 'foo' })
wx.miniProgram.postMessage({ data: {foo: 'bar'} })
wx.miniProgram.getEnv(function(res) { console.log(res.miniprogram) })
```
--------------------------------
### Resource Asset Loading Example
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/core/data-values.html
Demonstrates how to use resource assets like textures and materials. It shows loading a texture with a specific asset-id and then referencing it in a material's uniform.
```html
```
--------------------------------
### Input Component Example
Source: https://developers.weixin.qq.com/miniprogram/dev/component/input.html
Demonstrates basic data binding, input filtering with cursor control, and hiding the keyboard based on input value.
```javascript
Page({
data: {
focus: false,
inputValue: ''
},
bindKeyInput: function (e) {
this.setData({
inputValue: e.detail.value
})
},
bindReplaceInput: function (e) {
var value = e.detail.value
var pos = e.detail.cursor
var left
if (pos !== -1) {
// 光标在中间
left = e.detail.value.slice(0, pos)
// 计算光标的位置
pos = left.replace(/11/g, '2').length
}
// 直接返回对象,可以对输入进行过滤处理,同时可以控制光标的位置
return {
value: value.replace(/11/g, '2'),
cursor: pos
}
// 或者直接返回字符串,光标在最后边
// return value.replace(/11/g,'2'),
},
bindHideKeyboard: function (e) {
if (e.detail.value === '123') {
// 收起键盘
wx.hideKeyboard()
}
}
})
```
--------------------------------
### Web-view Page Sharing
Source: https://developers.weixin.qq.com/miniprogram/dev/component/web-view.html
Example of how to get the current web-view URL when a user shares the page within the mini program.
```javascript
Page({
onShareAppMessage(options) {
console.log(options.webViewUrl)
}
})
```
--------------------------------
### Basic Page Container Usage
Source: https://developers.weixin.qq.com/miniprogram/dev/component/page-container.html
This example demonstrates the basic usage of the page-container component. It shows how to control its visibility using the 'show' property and how to handle events like clicking the overlay.
```xml
```
--------------------------------
### View Container Layout Example
Source: https://developers.weixin.qq.com/miniprogram/dev/component/view.html
Demonstrates how to use the view component for horizontal and vertical flexbox layouts. Ensure the necessary CSS classes are defined for styling.
```wxml
flex-direction: row
横向布局
flex-direction: column
纵向布局
```
--------------------------------
### Radio Component Example
Source: https://developers.weixin.qq.com/miniprogram/dev/component/radio.html
This example demonstrates how to use the Radio component within a WeChat Mini Program. It includes data initialization for radio options, handling the change event to update the checked state, and setting up the page for sharing.
```javascript
Page({
onShareAppMessage() {
return {
title: 'radio',
path: 'page/component/pages/radio/radio'
}
},
data: {
items: [
{value: 'USA', name: '美国'},
{value: 'CHN', name: '中国', checked: 'true'},
{value: 'BRA', name: '巴西'},
{value: 'JPN', name: '日本'},
{value: 'ENG', name: '英国'},
{value: 'FRA', name: '法国'},
]
},
radioChange(e) {
console.log('radio发生change事件,携带value值为:', e.detail.value)
const items = this.data.items
for (let i = 0, len = items.length; i < len; ++i) {
items[i].checked = items[i].value === e.detail.value
}
this.setData({
items
})
}
})
```
--------------------------------
### Checkbox Component Example
Source: https://developers.weixin.qq.com/miniprogram/dev/component/checkbox.html
This example demonstrates how to use the Checkbox component in a WeChat Mini Program. It includes data initialization, rendering checkboxes, and handling the 'checkboxChange' event to update the selection state.
```javascript
Page({
onShareAppMessage() {
return {
title: 'checkbox',
path: 'page/component/pages/checkbox/checkbox'
}
},
data: {
items: [
{value: 'USA', name: '美国'},
{value: 'CHN', name: '中国', checked: 'true'},
{value: 'BRA', name: '巴西'},
{value: 'JPN', name: '日本'},
{value: 'ENG', name: '英国'},
{value: 'FRA', name: '法国'}
]
},
checkboxChange(e) {
console.log('checkbox发生change事件,携带value值为:', e.detail.value)
const items = this.data.items
const values = e.detail.value
for (let i = 0, lenI = items.length; i < lenI; ++i) {
items[i].checked = false
for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
if (items[i].value === values[j]) {
items[i].checked = true
break
}
}
}
this.setData({
items
})
}
})
```
--------------------------------
### Getting Scene Instance
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/core/scene.html
Explains how to obtain the scene instance in different contexts, either directly using `this.scene` or via an event in user小程序 scripts.
```APIDOC
## Getting Scene Instance
### Description
This section describes how to access the `scene` instance. Within components or loaders, `this.scene` can be used directly. In user小程序 scripts, the `ready` event of the `xr-scene` component should be used.
### Usage
#### In Components/Loaders
```javascript
// Directly access the scene instance
const scene = this.scene;
```
#### In User小程序 Scripts
```html
```
```javascript
// In the小程序 script
Page({
handleReady({detail}) {
const scene = detail.value;
// Use the scene instance here
}
});
```
```
--------------------------------
### Redirect Page Content
Source: https://developers.weixin.qq.com/miniprogram/dev/component/navigator.html
Example WXML for a page used in a redirect scenario. Displays a title and a back instruction.
```wxml
{{title}}
点击左上角返回回到上级页面
```
--------------------------------
### Navigator Page Content
Source: https://developers.weixin.qq.com/miniprogram/dev/component/navigator.html
Example WXML for a page navigated to by the navigator component. Displays a title and a back instruction.
```wxml
{{title}}
点击左上角返回回到之前页面
```
--------------------------------
### Grid View Component Usage
Source: https://developers.weixin.qq.com/miniprogram/dev/component/grid-view.html
This example demonstrates the basic usage of the grid-view component. It can be used for grid or waterfall layouts and requires specific configurations for WebView compatibility.
```html
```
--------------------------------
### root-portal Component Usage
Source: https://developers.weixin.qq.com/miniprogram/dev/component/root-portal.html
This example demonstrates the basic usage of the root-portal component. The 'enable' attribute controls whether the subtree is detached from the page. Ensure compatibility for versions below 2.25.2.
```xml
This content is detached.
```
--------------------------------
### movable-view Example
Source: https://developers.weixin.qq.com/miniprogram/dev/component/movable-area.html
This JavaScript code demonstrates how to control the position and scale of a movable-view component within a movable-area. It includes event handlers for tap and scale actions, and logs details to the console.
```javascript
Page({
onShareAppMessage() {
return {
title: 'movable-view',
path: 'page/component/pages/movable-view/movable-view'
}
},
data: {
x: 0,
y: 0,
scale: 2,
},
tap() {
this.setData({
x: 30,
y: 30
})
},
tap2() {
this.setData({
scale: 3
})
},
onChange(e) {
console.log(e.detail)
},
onScale(e) {
console.log(e.detail)
}
})
```
--------------------------------
### Define a Component with Slot
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/core/slot.html
Define a component that can accept slot content. Ensure the component's renderer is set to 'xr-frame'. This example shows a basic xr-scene setup with a slot.
```xml
```
--------------------------------
### Modify GLTF Texture via Script
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/gltf/specification.html
Dynamically change GLTF model textures after the model is loaded. This example shows how to get a mesh by node name and update its base color map.
```json
// gltf
{
...
"nodes": [{
"mesh": 0,
"name": "Banana"
}],
...
}
```
```xml
// xml
```
```typescript
// ts
function handleGLTFLoaded({ detail }) {
const el = detail.value.target;
const gltf = el.getComponent("gltf");
const newMat = this.scene.assets.getAsset("texture", "...texture name...");
for (const mesh of gltf.getPrimitivesByNodeName("Banana")) {
mesh.material.setTexture("u_baseColorMap", newMat);
}
}
```
--------------------------------
### Old Canvas API Drawing Example
Source: https://developers.weixin.qq.com/miniprogram/dev/component/canvas.html
Demonstrates drawing shapes and lines using the older Canvas API. This API requires a `canvas-id` and uses `wx.createCanvasContext` to get the drawing context. Multiple canvases with the same `canvas-id` will result in hidden elements and error events.
```html
```
```javascript
Page({
canvasIdErrorCallback: function (e) {
console.error(e.detail.errMsg)
},
onReady: function (e) {
// 使用 wx.createContext 获取绘图上下文 context
var context = wx.createCanvasContext('firstCanvas')
context.setStrokeStyle("#00ff00")
context.setLineWidth(5)
context.rect(0, 0, 200, 200)
context.stroke()
context.setStrokeStyle("#ff0000")
context.setLineWidth(2)
context.moveTo(160, 100)
context.arc(100, 100, 60, 0, 2 * Math.PI, true)
context.moveTo(140, 100)
context.arc(100, 100, 40, 0, Math.PI, false)
context.moveTo(85, 80)
context.arc(80, 80, 5, 0, 2 * Math.PI, true)
context.moveTo(125, 80)
context.arc(120, 80, 5, 0, 2 * Math.PI, true)
context.stroke()
context.draw()
}
})
```
--------------------------------
### Scene Creation and Querying
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/core/scene.html
Demonstrates how to create texture resources and elements within a scene, and how to query scene information like width and assets.
```APIDOC
## Scene Creation and Querying
### Description
This section details how to create resources and elements associated with an `xr-scene`, and how to access scene properties and system instances.
### Methods
#### `createTexture(options)`
- **Description**: Creates a texture resource that belongs to the current scene, independent of the resource loading workflow.
- **Parameters**: `options` (object) - Configuration options for the texture.
- **Returns**: `texture` (object) - The created texture resource.
#### `createElement(xrFrameSystem.XRNode)`
- **Description**: Creates a new element. It is recommended to use this in conjunction with `ShadowElement`.
- **Parameters**: `xrFrameSystem.XRNode` (class) - The class constructor for the element to be created.
- **Returns**: `el` (object) - The created element.
#### `getElementById(id)`
- **Description**: Queries for an element by its ID.
- **Parameters**: `id` (string) - The ID of the element to find.
- **Returns**: `element` (object) - The found element, or null if not found.
#### `width`
- **Description**: Gets the width of the canvas.
- **Returns**: `number` - The width of the canvas.
#### `assets`
- **Description**: Gets a reference to the system instance for assets.
- **Returns**: `object` - The assets system instance.
```
--------------------------------
### Audio Component Basic Usage
Source: https://developers.weixin.qq.com/miniprogram/dev/component/audio.html
This snippet demonstrates how to use the audio component, including setting its source, name, author, and poster. It also shows how to control playback (play, pause, seek) using wx.createAudioContext.
```javascript
Page({
onReady: function (e) {
// 使用 wx.createAudioContext 获取 audio 上下文 context
this.audioCtx = wx.createAudioContext('myAudio')
},
data: {
poster: 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000',
name: '此时此刻',
author: '许巍',
src: 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E06DCBDC9AB7C49FD713D632D313AC4858BACB8DDD29067D3C601481D36E62053BF8DFEAF74C0A5CCFADD6471160CAF3E6A&fromtag=46',
},
audioPlay: function () {
this.audioCtx.play()
},
audioPause: function () {
this.audioCtx.pause()
},
audio14: function () {
this.audioCtx.seek(14)
},
audioStart: function () {
this.audioCtx.seek(0)
}
})
```
--------------------------------
### root-portal Component
Source: https://developers.weixin.qq.com/miniprogram/dev/component/root-portal.html
This section details the root-portal component, its functionality, properties, and provides an example of its usage.
```APIDOC
## root-portal
> Supported starting from basic library version 2.25.2, with compatibility handling for lower versions.
> **WeChat Windows Version**: Supported
> **WeChat Mac Version**: Supported
> **WeChat HarmonyOS Version**: Supported
Rendering framework support: Skyline (debug with the latest Nightly tool), WebView
## Function Description
Allows an entire subtree to detach from the page, similar to the effect of `fixed` positioning in CSS. Primarily used for creating pop-ups, floating layers, etc.
## Property Description
| Property | Type | Default Value | Required | Description | Minimum Version |
|---|---|---|---|---|---|
| enable | boolean | true | No | Whether to detach from the page | 2.26.1 |
| externalClass | string | | No | External style class | 3.9.2 |
## Example Code
Preview the effect in the developer tools
```
--------------------------------
### Setting up Global Physics
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/physics/rigidbody.html
Configure the current scene as a physics world by adding the `` tag within ``. This tag must be a direct child of ``.
```markup
...(场景中的其他标签)
```
--------------------------------
### Scroll View Reverse Scrolling
Source: https://developers.weixin.qq.com/miniprogram/dev/component/scroll-view.html
Enable reverse scrolling for the scroll-view, typically starting from the bottom.
```markup
```
--------------------------------
### Store Gift Component with Options and Callbacks
Source: https://developers.weixin.qq.com/miniprogram/dev/component/store-gift.html
This example shows how to use the store-gift component with additional options like show-gift-card and bind success/error events. Ensure your client version meets the requirements for these features.
```html
```
--------------------------------
### Specular Glossiness Workflow
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/builtin/effect-standard.html
Implements an alternative PBR workflow using specular and glossiness values. Allows control over F0 in the specular map and uses glossiness as (1 - roughness). Requires the `WX_USE_SPECULARGLOSSINESS` macro.
```glsl
// Specular glossiness workflow is enabled by WX_USE_SPECULARGLOSSINESS macro.
// Uniforms like u_specularFactor, u_glossinessFactor, and u_specularGlossinessMap are used.
// Diffuse part uses baseColor parameters.
// The 'specularGlossinessMap' contains specular in RGB and glossiness in Alpha.
```
--------------------------------
### Manually Create and Configure an Element
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/core/element.html
Shows how to programmatically create an element instance using `createElement` and set its attributes. It advises against using `setAttribute` for updates, recommending component `setData` instead.
```javascript
const node = scene.createElement(xrFrameSystem.XRNode, {
position: '1 1 1'
});
node.setAttribute(position, '2 2 2');
```
--------------------------------
### Get Atlas Texture
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/render/atlas.html
Access the underlying texture object from a loaded atlas. This texture contains the combined image data.
```javascript
// 获取纹理
const texture = atlas.texture;
```
--------------------------------
### Editor Component with Keyboard Configuration
Source: https://developers.weixin.qq.com/miniprogram/dev/component/editor.html
This example configures the virtual keyboard's enter key behavior. 'enterkeyhint' defines the label on the enter key, and 'confirm-hold' determines if the keyboard remains visible after pressing enter (default is true).
```xml
```
--------------------------------
### Typical Camera Element Usage
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/render/camera.html
A basic example of how to use the xr-camera element in XML, including setting its position, clear color, background, and target. It also shows how to enable the camera orbit control.
```xml
```
--------------------------------
### Configuring Rigidbody Mass
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/physics/rigidbody.html
Modify rigidbody properties by adding attribute values to the `rigidbody` attribute. This example sets the mass of the rigidbody.
```markup
```
--------------------------------
### Editor Component with Image Controls
Source: https://developers.weixin.qq.com/miniprogram/dev/component/editor.html
This example shows how to enable image size and toolbar controls within the editor. When a user clicks on an image, controls to display its size, a toolbar, and resize options will appear.
```xml
```
--------------------------------
### Monitoring Page State Changes in Web-view
Source: https://developers.weixin.qq.com/miniprogram/dev/component/web-view.html
Example of how to listen for page state changes (e.g., active/inactive) within a web-view using the WeixinJSBridge.
```javascript
WeixinJSBridge.on('onPageStateChange', function(res) {
console.log('res is active', res.active)
})
```
--------------------------------
### Registering a Custom Node-Derived Element
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/core/node.html
Provides an example of registering a custom element that derives from `xr-node`, by merging default components and data mappings.
```javascript
import XrFrame from 'XrFrame';
const xrFrameSystem = wx.getXrFrameSystem();
const CustomDefaultComponents: XrFrame.IEntityComponents = Object.assign({
'custom-component': {
customData: value
}
}, xrFrameSystem.NodeDefaultComponents);
const CustomStarDataMapping: {[key: string]: string[];} = Object.assign({
'custom-data': ['custom-component', 'customData']
}, xrFrameSystem.NodeDataMapping);
xrFrameSystem.registerElement('custom', class XRCustom extends xrFrameSystem.Element {
public readonly defaultComponents: XrFrame.IEntityComponents = CustomStarDefaultComponents;
public readonly dataMapping: {[key: string]: string[];} = CustomStarDataMapping;
});
```
--------------------------------
### Page Meta Configuration Example
Source: https://developers.weixin.qq.com/miniprogram/dev/component/page-meta.html
This snippet shows how to configure page meta properties like background styles, colors, and scroll position. It also includes the navigation-bar component for setting the title, loading state, and colors.
```xml
```
--------------------------------
### Textarea Component Logic
Source: https://developers.weixin.qq.com/miniprogram/dev/component/textarea.html
Provides the JavaScript logic for the textarea component examples, handling focus changes, blur events, and form submission.
```javascript
Page({
data: {
height: 20,
focus: false
},
bindButtonTap: function() {
this.setData({
focus: true
})
},
bindTextAreaBlur: function(e) {
console.log(e.detail.value)
},
bindFormSubmit: function(e) {
console.log(e.detail.value.textarea)
}
})
```
--------------------------------
### Loading Assets and Rendering a Mesh with Standard Material
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/builtin/effect-standard.html
Example of loading external assets like environment data and textures, defining a standard material, and then applying it to an xr-mesh component. It demonstrates setting uniform values for metallic, roughness, base color, and other maps, as well as customizing render states.
```html
```
--------------------------------
### Image Component Initialization
Source: https://developers.weixin.qq.com/miniprogram/dev/component/image.html
Initializes the Image component with various display modes and a sample image source. Includes an error handling function.
```javascript
Page({
data: {
array: [{
mode: 'scaleToFill',
text: 'scaleToFill:不保持纵横比缩放图片,使图片完全适应'
}, {
mode: 'aspectFit',
text: 'aspectFit:保持纵横比缩放图片,使图片的长边能完全显示出来'
}, {
mode: 'aspectFill',
text: 'aspectFill:保持纵横比缩放图片,只保证图片的短边能完全显示出来'
}, {
mode: 'top',
text: 'top:不缩放图片,只显示图片的顶部区域'
}, {
mode: 'bottom',
text: 'bottom:不缩放图片,只显示图片的底部区域'
}, {
mode: 'center',
text: 'center:不缩放图片,只显示图片的中间区域'
}, {
mode: 'left',
text: 'left:不缩放图片,只显示图片的左边区域'
}, {
mode: 'right',
text: 'right:不缩放图片,只显示图片的右边边区域'
}, {
mode: 'top left',
text: 'top left:不缩放图片,只显示图片的左上边区域'
}, {
mode: 'top right',
text: 'top right:不缩放图片,只显示图片的右上边区域'
}, {
mode: 'bottom left',
text: 'bottom left:不缩放图片,只显示图片的左下边区域'
}, {
mode: 'bottom right',
text: 'bottom right:不缩放图片,只显示图片的右下边区域'
}],
src: 'https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg'
},
imageError: function(e) {
console.log('image3发生error事件,携带值为', e.detail.errMsg)
}
})
```
--------------------------------
### Page Container with Slide Down Close
Source: https://developers.weixin.qq.com/miniprogram/dev/component/page-container.html
This example shows how to enable closing the page-container by sliding it down. It also includes custom styling for the overlay and the container itself.
```xml
```
--------------------------------
### Accessing and Modifying Transform Component
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/core/node.html
Illustrates how to get a reference to the Transform component using `getNodeById` and modify its position, rotation, and scale properties.
```javascript
const trs = scene.getNodeById(nodeId);
// 修改位置
trs.position.x = 10;
trs.position.setValue(10, 10, 10);
trs.position.setFromArray([1, 1, 1]);
trs.position.set(new xrFrameSystem.Vector3());
// 欧拉角、缩放、四元素也是类似的
trs.rotation.y = 10;
trs.scale.z = 2;
trs.quaternion.w = 1;
```
--------------------------------
### Basic voip-room Usage
Source: https://developers.weixin.qq.com/miniprogram/dev/component/voip-room.html
This snippet demonstrates how to render multiple voip-room instances, dynamically setting the mode to 'camera' for the current user and 'video' for other participants. Ensure the 'openIdList' and 'selfOpenId' are correctly managed in your component's data.
```wxml
```
--------------------------------
### Start Recording Scene
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/share
Initiates the recording of the XR scene. It's recommended to scale width and height proportionally to avoid frame drops. This feature requires a base library version of v3.1.1 or higher.
```javascript
// 录制配置,以下是默认值
// 这里建议根据实际情况,等比缩放`width`和`height`,防止丢帧
const options: XrFrame.IShareRecordOptions = {
fps: 30,
width: scene.width,
height: scene.height,
videoBitsPerSecond: 1000
};
// 启动录制
await scene.share.recordStart(options);
```
--------------------------------
### Web-view Component Tips and Notes
Source: https://developers.weixin.qq.com/miniprogram/dev/component/web-view.html
This section provides important tips and notes regarding the web-view component, including domain configuration, debugging, usage limitations, and potential issues.
```APIDOC
## Bug & Tip
1. **Tip**: The domain of iframes within a web page also needs to be configured in the domain whitelist.
2. **Tip**: In the developer tools, you can debug the web-view component by right-clicking on it and selecting 'Debug'.
3. **Tip**: Each page can only contain one web-view component. The web-view will automatically fill the entire page and cover other components.
4. **Tip**: Communication between the web-view page and the mini program is not supported beyond the interfaces provided by the JSSDK.
5. **Tip**: On iOS, if you encounter issues with JSSDK interface calls not responding, try appending `#wechat_redirect` to the `src` URL of the web-view.
6. **Tip**: Avoid using Chinese characters in URLs, as this can cause blank pages on iOS. It is recommended to use `encodeURIComponent` for URLs.
```
--------------------------------
### Get Atlas UV Matrix
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/render/atlas.html
Retrieve the UV matrix for a specific frame within the atlas. This matrix is used for rendering specific parts of the atlas.
```javascript
// 获取UV矩阵,matrix3
const uvMatrix = atlas.getUVMatrix(frameName);
```
--------------------------------
### Creating Different Light Types
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/render/light.html
Demonstrates how to create and configure ambient, directional, point, and spot lights in XR-Frame. Each light type has specific properties for color, intensity, and spatial configuration.
```xml
```
--------------------------------
### Basic Navigator Usage
Source: https://developers.weixin.qq.com/miniprogram/dev/component/navigator.html
Demonstrates basic navigation scenarios using the navigator component. Includes navigating to a new page, redirecting to the current page, and switching tabs.
```wxml
跳转到新页面
在当前页打开
切换 Tab
打开绑定的小程序
```
--------------------------------
### Create Sphere Shape on Generic Node
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/physics/shape.html
Demonstrates that any scene node can have a shape component added, not just xr-mesh. This example adds a sphere shape to a generic xr-node.
```xml
```
--------------------------------
### WXML Event Binding Example
Source: https://developers.weixin.qq.com/miniprogram/dev/component/xr-frame/core/event.html
Bind events to XR-Frame elements in WXML, similar to standard小程序 components. Event handlers are defined in the component's methods.
```xml
```