### Installing Minigame Canvas Engine (npm) - Shell Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/overview/guide.md Installs the minigame-canvas-engine library and its dependencies using npm, saving it as a project dependency in the package.json file. ```shell npm install minigame-canvas-engine --save ``` -------------------------------- ### Importing Layout Module - JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/overview/guide.md Imports the main `Layout` class or object from the installed minigame-canvas-engine library, making its functionalities accessible within the current JavaScript file. ```js import Layout from "minigame-canvas-engine"; ``` -------------------------------- ### Install and Use Rich Text Plugin (JavaScript) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/plugin/richtext.md This snippet demonstrates how to install the Rich Text plugin via tnpm, import it, register it with the Layout engine, retrieve a rich text element from the layout, and set its text content using HTML-like markup with inline styles. Requires the minigame-canvas-engine and the rich text plugin package. ```JavaScript // 安装 tnpm install --save minigame-canvas-engine-richtext // 引用 import RichText from 'minigame-canvas-engine-richtext' // 安装插件 Layout.use(RichText); // xml // 获取富文本的节点 const rich = Layout.getElementsById('rich')[0]; // 设置富文本的值 rich.text = `

这是一段富文本测试


这是一段加粗的标题

这里展示了嵌套的标签


前面是一个换行

文字可以自定义颜色


样式可以继承,也可以自定义,这段很长的文字会自动换行,富文本组件都会自动处理好

`; ``` -------------------------------- ### Initializing Layout Engine - JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/overview/guide.md Initializes the minigame canvas engine's internal layout and rendering structures by parsing the provided template string and applying the defined style object. This prepares the engine for rendering the UI onto a canvas. ```js Layout.init(template, style); ``` -------------------------------- ### Customizing Environment Module for Platform Adaptation (JavaScript) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/tutorial/platform.md This JavaScript example demonstrates how to customize the `env` module before initializing the Layout engine. It shows how to override `createImage` to use a platform-specific image class and `onTouchStart` to hook into the current platform's touch event handler, enabling Layout to function correctly in a new or custom environment. ```JavaScript import { env, Layout } from 'minigame-canvas-engine'; env.createImage = () => { return new ImageClassInCurrentPlatform(); } env.onTouchStart = currentPlatform.onTouchStart; // 下面正常执行 Layout的使用 ``` -------------------------------- ### Getting First Element by ID - Layout - JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/api/api.md Demonstrates how to get the first element matching a given `id` using `Layout.getElementById`. This method assumes the business logic ensures ID uniqueness. ```JavaScript // const container = Layout.getElementById('container'); ``` -------------------------------- ### Implementing doT.js Loop (Layout XML/JS) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/tutorial/templateengine.md Demonstrates the doT.js `{~ }}` syntax for iterating over arrays, typically `it.data`. The example loops through `it.data`, creating a `` for each `item`, accessing `item` properties like `avatarUrl`, `nickname`, `rankScore`, and the `index`. Requires an array property `data` on the input `it` object. ```Layout XML // Syntax {{~ }} // Example {{~it.data :item:index}} {{~}} ``` -------------------------------- ### Getting Elements by ID - Layout - JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/api/api.md Shows how to retrieve a list of elements by their `id` using `Layout.getElementsById`. Note that unlike standard Web behavior, `id` is not unique in this context, so it returns an array of matching elements. ```JavaScript // const container = Layout.getElementsById('container')[0]; ``` -------------------------------- ### Defining UI Template - JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/overview/guide.md Defines a multi-line JavaScript string containing the UI structure in an XML-like format. This template specifies the hierarchy and types of elements to be rendered; it must have exactly one root node. ```js let template = ` `; ``` -------------------------------- ### Cloning and Modifying Nodes - Layout - JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/api/api.md Provides an example of using `Layout.cloneNode` to deep copy an existing element. It then shows how to modify properties of the cloned node's children and append the new node to an existing parent, avoiding a full `Layout.init` re-execution. ```JavaScript // 获取 ScrollView const list = Layout.getElementsByClassName('list')[0]; // 对列表第一项进行深度拷贝 const listItem = Layout.getElementsByClassName('listItem'); const listItem1 = listItem[0]; const newListItem1 = Layout.cloneNode(listItem1); // 针对拷贝后的子节点做一些魔改 const listItemNum = newListItem1.getElementsByClassName('listItemNum')[0]; listItemNum.value = 2; const listItemName = newListItem1.getElementsByClassName('listItemName')[0]; listItemName.value = 'zim test'; const listItemScore = newListItem1.getElementsByClassName('listItemScore')[0]; listItemScore.value = '100'; // 将拷贝后的节点也添加到滚动列表 list.appendChild(newListItem1); ``` -------------------------------- ### Getting Elements by ID in JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/components/element.md This snippet demonstrates how to retrieve a list of elements by their ID using `Layout.getElementsById`. Since IDs are not guaranteed to be unique in this implementation, it returns an array, and the example accesses the first element. ```JavaScript // const container = Layout.getElementsById('container')[0]; ``` -------------------------------- ### Getting Elements by Class Name in JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/components/element.md This snippet demonstrates how to retrieve a collection of elements that have a specific class name using `Layout.getElementsByClassName`. It shows an example of an HTML structure and then logs the count of elements found with the class 'item'. ```JavaScript /** * */ const list = Layout.getElementsByClassName('item'); console.log(list.length); // 3 ``` -------------------------------- ### Implementing doT.js Conditional (Layout XML/JS) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/tutorial/templateengine.md Shows the doT.js `{{? }}` syntax for conditional rendering or logic within the template. The example uses conditions within a loop to apply a different class (`listItemOld`) based on whether the item's index is odd or even. Requires the `it.data` array and depends on the loop context (`item`, `index`). ```Layout XML // Syntax {{? }} // Example {{~it.data :item:index}} {{? index % 2 === 1 }} {{?}} {{? index % 2 === 0 }} {{?}} {{~}} ``` -------------------------------- ### Rendering UI on Canvas - JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/overview/guide.md Retrieves an HTML canvas element's 2D rendering context, configures the canvas dimensions to match the desired layout size, updates the engine's viewport settings, and triggers the engine to perform layout calculation and draw the UI elements onto the canvas context. ```js // 首先在HTML里面创建canvas // let canvas = document.getElementById("canvas"); let context = canvas.getContext("2d"); // 设置canvas的尺寸和样式的container比例一致 canvas.style.width = 400 + "px"; canvas.style.height = 200 + "px"; canvas.width = 400; canvas.height = 200; Layout.updateViewPort({ x: 0, y: 0, width: 400, height: 200, }); Layout.layout(context); ``` -------------------------------- ### Implementing doT.js Interpolation (Layout XML/JS) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/tutorial/templateengine.md Shows the doT.js `{{= }}` syntax for inserting data values from the `it` object into the template. The example inserts the `it.title` property into the `value` attribute of a `` tag within a Layout XML structure. Requires data passed to the compiled template function. ```Layout XML // Syntax {{= }} // Example ``` -------------------------------- ### Getting Elements by Class Name - Layout - JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/api/api.md Illustrates how to retrieve a list of elements that have a specific class name using `Layout.getElementsByClassName`. It returns an array of matching elements. ```JavaScript /** * */ const list = Layout.getElementsByClassName('item'); console.log(list.length); // 3 ``` -------------------------------- ### Adding Per-Frame Callback to Layout Ticker (JavaScript) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/api/api.md This example illustrates how to register a function (`selfTickerFunc`) to be executed on every frame of the `Layout` engine's animation loop using `Layout.ticker.add`. The callback modifies the `top` style property of a `ball` element, simulating movement. ```JavaScript const ball = Layout.getElementsByClassName('ball')[0]; const selfTickerFunc = () => { ball.style.top += 1; } Layout.ticker.add(selfTickerFunc); ``` -------------------------------- ### Binding Click Event - JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/overview/guide.md Retrieves a specific UI element from the initialized layout tree using its ID and attaches a click event listener to it. The provided anonymous function is executed whenever the retrieved element is clicked. ```js let text = Layout.getElementsById("testText")[0]; text.on("click", (e) => { alert("hello canvas"); }); ``` -------------------------------- ### Managing Element Classes with Layout.classList (JavaScript) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/tutorial/style.md This example illustrates how to dynamically manage an element's CSS classes using the "classList" property. It retrieves an element by its ID, logs its current class list (which includes its ID by default), then adds and removes a 'test' class. This approach is recommended for batch style modifications, offering a more efficient way to apply or remove multiple styles simultaneously compared to direct "style" manipulation. ```js // const container = Layout.getElementById('container'); console.log(container.classList.value); // `container info` container.classList.add('test'); container.classList.remove('test'); ``` -------------------------------- ### Calling ScrollView scrollTo Method JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/components/scrollview.md Illustrates calling the scrollTo method on a ScrollView instance to programmatically scroll the content. The example scrolls vertically by 100 units with animation enabled, demonstrating how to control the scroll position from JavaScript. ```javascript const list = Layout.getElementById("list"); // 列表往上滚动 100 list.scrollTo(0, 100, true); ``` -------------------------------- ### Executing Callback on Next Layout Ticker Frame (JavaScript) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/api/api.md This snippet shows how to schedule a one-time callback to be executed after the next frame of the `Layout` engine's animation loop using `Layout.ticker.next`. It's useful for operations that need to occur after a layout update, such as getting element dimensions. ```JavaScript const ball = Layout.getElementsByClassName('ball')[0]; Layout.ticker.next(() => { console.log(ball.getBoundingClientRect()); }); ``` -------------------------------- ### Getting a Single Element by ID in JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/components/element.md This snippet shows how to retrieve the first element matching a given ID using `Layout.getElementById`. This method is available from v1.0.1 and assumes the business logic ensures ID uniqueness. ```JavaScript // const container = Layout.getElementById('container'); ``` -------------------------------- ### Defining UI Styles - JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/overview/guide.md Defines a JavaScript object containing CSS-like styles for the UI elements identified by their IDs or classes in the template. Class styles override ID styles for conflicting properties. Note that width and height are recommended for all elements, and required for the root. ```js let style = { container: { width: 400, height: 200, backgroundColor: "#ffffff", justifyContent: "center", alignItems: "center", }, testText: { color: "#ffffff", width: "100%", height: "100%", lineHeight: 200, fontSize: 40, textAlign: "center", }, // 文字的最终颜色为#ff0000 redText: { color: "#ff0000", }, }; ``` -------------------------------- ### CodeMirror Tab and Ruler Styling (CSS) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/public/playground.html Styles the appearance of tab characters and vertical rulers within the CodeMirror editor. Tabs are set to display as inline blocks with inherited text decoration, while rulers are positioned absolutely to provide visual guides. ```CSS .cm-tab { display: inline-block; text-decoration: inherit; } .CodeMirror-rulers { position: absolute; left: 0; right: 0; top: -50px; bottom: 0; overflow: hidden; } .CodeMirror-ruler { border-left: 1px solid #ccc; top: 0; bottom: 0; position: absolute; } ``` -------------------------------- ### Preloading Image Resources - Layout - JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/api/api.md Illustrates how to use `Layout.loadImgs` to pre-load image resources before rendering, improving performance and user experience by preventing images from appearing one by one. Paths are relative to the mini-game's root directory. ```JavaScript // 注意图片路径不需要加./作为前缀,以小游戏根目录作为根目录 Layout.loadImgs([ 'sub/Buffet_icon_GiftPlate_0.png', 'sub/Buffet_icon_GiftPlate.png', 'sub/UI_Icon_Rating.png' ]).then(() => { console.log('所有资源加载完成'); }) ``` -------------------------------- ### Core Environment Module for Platform Adaptation (TypeScript) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/tutorial/platform.md This TypeScript module (`env`) encapsulates platform-specific functionalities required by the Layout engine, such as touch event handling, canvas/image creation, and device pixel ratio retrieval. It dynamically detects the current environment (e.g., WeChat, ByteDance, Baidu mini-games, or browser) and provides unified interfaces for these operations. Developers can override these methods to adapt Layout to new platforms. ```TypeScript import { Callback } from "./types"; if (typeof GameGlobal !== 'undefined') { GameGlobal.__env = GameGlobal.wx || GameGlobal.tt || GameGlobal.swan; } const domEventMap: Record = { touchstart: 'mousedown', touchmove: 'mousemove', touchend: 'mouseup', touchcancel: 'mouseleave', } enum eventType { on = 'on', off = 'off', } function genDomTouchEvent(event: string, type: eventType) { if (typeof document !== 'undefined') { return function (listener: Callback) { type === eventType.on ? document.addEventListener(event, listener, false) : document.removeEventListener(event, listener, false) } } } function getOnTouchHandler(event: string, type: eventType) { if (typeof GameGlobal !== 'undefined') { return GameGlobal.__env[`${type}${event}`] } else { return genDomTouchEvent(domEventMap[event.toLowerCase()], type); } } /** * Layout 可能用在不用的平台,而Layout会依赖平台下面的一些方法来实现具体的功能,比如创建图片 * 为了更好做平台适配,统一封装 env 模块,不同平台要做适配,替换 env 的具体方法即可 */ export default { // 监听触摸相关事件 onTouchStart: getOnTouchHandler('TouchStart', eventType.on), onTouchMove: getOnTouchHandler('TouchMove', eventType.on), onTouchEnd: getOnTouchHandler('TouchEnd', eventType.on), onTouchCancel: getOnTouchHandler('TouchCancel', eventType.on), // 取消监听触摸相关事件 offTouchStart: getOnTouchHandler('TouchStart', eventType.off), offTouchMove: getOnTouchHandler('TouchMove', eventType.off), offTouchEnd: getOnTouchHandler('TouchEnd', eventType.off), offTouchCancel: getOnTouchHandler('TouchCancel', eventType.off), // Layout 支持百分比样式,如果根节点样式设置为 100%,直接取 Canvas 的尺寸,不同平台的取法不一样,因此单独提供函数 getRootCanvasSize() { if (typeof __env !== 'undefined' && __env.getSharedCanvas) { const cvs = __env.getSharedCanvas(); return { width: cvs.width, height: cvs.height, } } else { return { width: 300, height: 150, } } }, // 取当前设备的 devicePixelRatio,不同平台的取法不一样 getDevicePixelRatio() { if (typeof __env !== 'undefined' && __env.getSystemInfoSync) { return __env.getSystemInfoSync().devicePixelRatio; } else if (window.devicePixelRatio) { return window.devicePixelRatio; } else { return 1; } }, // 创建Canvas createCanvas() { if (typeof __env !== 'undefined') { return __env.createCanvas(); } return document.createElement('canvas'); }, // 创建图片 createImage() { if (typeof __env !== 'undefined') { return __env.createImage(); } return document.createElement('img'); } } ``` -------------------------------- ### Creating and Inserting UI Elements with layout.insertElement (JavaScript) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/api/api.md This snippet demonstrates how to dynamically create UI elements using a template string and apply styles. It shows iterating over data to build the template and then inserting the generated elements into an existing `scrollView` element. It requires `layout` and `Layout` objects to be available. ```JavaScript let template = ""; const data = []; // data 数据需要自行填写 data.forEach((user) => { template += "\n \n \n \n \n "; }); const style = { item: { flexDirection: 'row', padding: 16, alignItems: 'center', }, avatar: { width: 48, height: 48, borderRadius: 8, }, name: { color: 'rgba(0,0,0,0.9)', fontSize: 16, marginLeft: 8, width: 120, textOverflow: 'ellipsis', }, }; const scrollView = layout.getElementsByClassName('scrollView')[0]; Layout.insertElement(template, style, scrollView); ``` -------------------------------- ### Encapsulating Loading Animation Function - JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/tutorial/loading.md This JavaScript function `showLoading` encapsulates the entire loading animation logic for use in a WeChat Mini Game's open data domain. It initializes the Layout with a predefined HTML template and styles, then sets up the per-frame rotation for the loading image. It requires the `Layout` plugin and uses `wx.getSharedCanvas` for rendering. ```JavaScript // 通过插件的方式引用 Layout const Layout = requirePlugin('Layout').default; let sharedCanvas = wx.getSharedCanvas(); let sharedContext = sharedCanvas.getContext("2d"); const style = { container: { width: '100%', height: '100%', justifyContent: "center", alignItems: "center", }, loading: { width: 150, height: 150, borderRadius: 75, }, }; const tpl = ` `; export function showLoading() { Layout.clear(); Layout.init(tpl, style); Layout.layout(sharedContext); const image = Layout.getElementById('loading'); let degrees = 0; Layout.ticker.add(() => { degrees = (degrees + 2) % 360; image.style.transform = `rotate(${degrees}deg)`; }); } ``` -------------------------------- ### Styling Active State with Pseudo-class (JS) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/components/overview.md This JavaScript object literal snippet defines a style object that includes the ':active' pseudo-class. It demonstrates how to apply styles that trigger when an element receives a 'touchstart' event, specifically scaling the element up. This is useful for creating interactive button effects without manual event handling. ```javascript { color: '#ffffff', backgroundColor: '#34a123', borderRadius: 10, width: 400, height: 120, lineHeight: 120, fontSize: 50, textAlign: 'center', marginTop: 20, ':active': { transform: 'scale(1.05, 1.05)', }, } ``` -------------------------------- ### Defining Basic Layout XML Template (JavaScript) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/tutorial/templateengine.md Demonstrates a simple static XML template string used by the Layout engine. It defines a container view with a text element. This serves as a basic structure before introducing templating with data. It is stored as a JavaScript string. ```JavaScript let template = ` `; ``` -------------------------------- ### Defining Pseudo-class Styles with :active (JSON) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/tutorial/style.md This JSON snippet demonstrates how to define styles, including a pseudo-class, for a Layout element. It specifies basic visual properties like color, background, dimensions, and text alignment. Crucially, it includes an ":active" pseudo-class, which applies a "transform: 'scale(1.05, 1.05)'" effect when the element triggers a 'touchstart' event. This allows for interactive effects, such as button scaling on press, without requiring manual JavaScript event handling. ```json { "color": "#ffffff", "backgroundColor": "#34a123", "borderRadius": 10, "width": 400, "height": 120, "lineHeight": 120, "fontSize": 50, "textAlign": "center", "marginTop": 20, ":active": { "transform": "scale(1.05, 1.05)" } } ``` -------------------------------- ### Defining HTML Layout for Loading Indicator - HTML Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/tutorial/loading.md This HTML snippet defines the basic structure for the loading indicator. It consists of a container `view` and an `image` element inside it, which will serve as the rotating loading icon. The image source is a placeholder URL. ```HTML ``` -------------------------------- ### Binding Touch Events to Elements in JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/components/element.md This snippet demonstrates how to bind event listeners to elements retrieved by their class name. It iterates through a list of 'listItem' elements and attaches a `touchstart` event handler to each, logging the event object and the element itself. ```JavaScript const list = Layout.getElementsByClassName('listItem'); list.forEach(item => { item.on('touchstart', (e) => { console.log(e, item); }); }); ``` -------------------------------- ### Using Custom Fonts in WeChat Mini Game Open Data Domain - JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/tutorial/font.md This snippet illustrates the process of loading a custom font in the main game context using 'wx.loadFont' and then transmitting its identifier to the open data domain. The open data domain subsequently receives this font name via 'wx.onMessage', enabling it to apply the custom font using the 'fontFamily' property for rendering. ```JavaScript // game.js const fontFamily = wx.loadFont('xxxxx'); // 替换成真实的字体地址 let openDataContext = wx.getOpenDataContext(); openDataContext.postMessage({ type: 'setFontFamily', fontFamily, }) // open-data/index.js wx.onMessage(data => { console.log(data) /* { type: 'setFontFamily', fontFaimly: 'customFamliy1' // 假设字体名称为 customFamliy1 } */ // Layout 可以使用 customFamliy1 作为 fontFamily 属性 }); ``` -------------------------------- ### Declaring a Button Component in XML Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/components/button.md This snippet demonstrates how to declare a Button component using XML. When declared, the Layout system automatically creates a View container and a Text label, handling the underlying structure and default styling. ```xml ``` -------------------------------- ### Implementing Per-Frame Rotation for Loading Image - JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/tutorial/loading.md This JavaScript snippet demonstrates how to make the loading image rotate continuously. It retrieves the image element by its ID, initializes a `degrees` variable, and then uses `Layout.ticker.add()` to register a callback that increments the rotation angle by 2 degrees every frame, applying it via the `transform` style property. ```JavaScript const image = Layout.getElementById('loading'); let degrees = 0; Layout.ticker.add(() => { degrees = (degrees + 2) % 360; image.style.transform = `rotate(${degrees}deg)`; }); ``` -------------------------------- ### CodeMirror Addon and Core Mechanics Styling (CSS) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/public/playground.html Provides styles for common CodeMirror addons, such as matching and non-matching brackets and tags, and for the active line background. It also defines critical, low-level styles for the editor's core mechanics, including overflow behavior, scrollbars, and sizing, which are essential for its functionality. ```CSS div.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;} div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;} .CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); } .CodeMirror-activeline-background {background: #e8f2ff;} /* STOP */ /* The rest of this file contains styles related to the mechanics of the editor. You probably shouldn't touch them. */ .CodeMirror { position: relative; overflow: hidden; background: white; } .CodeMirror-scroll { overflow: scroll !important; /* Things will break if this is overridden */ /* 30px is the magic margin used to hide the element's real scrollbars */ /* See overflow: hidden in .CodeMirror */ margin-bottom: -30px; margin-right: -30px; padding-bottom: 30px; height ``` -------------------------------- ### Styling bitmaptext with JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/api/tags.md This JavaScript object defines the CSS-like properties for a `bitmaptext` element, typically applied via a class. It includes dimensions (`width`, `height`), font size, line height, text alignment (`textAlign`, `verticalAlign`), font weight, and border styles, controlling the visual presentation of the bitmap font text. ```javascript title: { width: 144, fontSize: 48, height: 120, lineHeight: 50, textAlign: 'center', verticalAlign: 'top', fontWeight: 'bold', borderBottomWidth: 6, borderColor: '#000000', } ``` -------------------------------- ### CodeMirror Gutter and Line Number Styling (CSS) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/public/playground.html Configures the appearance of the editor's gutter, including its border, background, and whitespace handling. It also styles the line numbers, setting their padding, minimum width, alignment, and color. ```CSS .CodeMirror-gutters { border-right: 1px solid #ddd; background-color: #f7f7f7; white-space: nowrap; } .CodeMirror-linenumbers {} .CodeMirror-linenumber { padding: 0 3px 0 5px; min-width: 20px; text-align: right; color: #999; white-space: nowrap; } .CodeMirror-guttermarker { color: black; } .CodeMirror-guttermarker-subtle { color: #999; } ``` -------------------------------- ### Basic CodeMirror Editor Styling (CSS) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/public/playground.html Defines fundamental visual properties for the CodeMirror editor, including font family, height, text color, and text direction. It sets the global appearance for the editor container. ```CSS .CodeMirror { /* Set height, width, borders, and global font properties here */ font-family: monospace; height: 300px; color: black; direction: ltr; } ``` -------------------------------- ### CodeMirror Default Syntax Highlighting Theme (CSS) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/public/playground.html Applies a default theme for syntax highlighting in CodeMirror, assigning specific colors and font styles to various code elements like keywords, numbers, strings, comments, and tags. This enhances readability by visually distinguishing different parts of the code. ```CSS .cm-s-default .cm-header {color: blue;} .cm-s-default .cm-quote {color: #090;} .cm-negative {color: #d44;} .cm-positive {color: #292;} .cm-header, .cm-strong {font-weight: bold;} .cm-em {font-style: italic;} .cm-link {text-decoration: underline;} .cm-strikethrough {text-decoration: line-through;} .cm-s-default .cm-keyword {color: #708;} .cm-s-default .cm-atom {color: #219;} .cm-s-default .cm-number {color: #164;} .cm-s-default .cm-def {color: #00f;} .cm-s-default .cm-variable, .cm-s-default .cm-punctuation, .cm-s-default .cm-property, .cm-s-default .cm-operator {} .cm-s-default .cm-variable-2 {color: #05a;} .cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;} .cm-s-default .cm-comment {color: #a50;} .cm-s-default .cm-string {color: #a11;} .cm-s-default .cm-string-2 {color: #f50;} .cm-s-default .cm-meta {color: #555;} .cm-s-default .cm-qualifier {color: #555;} .cm-s-default .cm-builtin {color: #30a;} .cm-s-default .cm-bracket {color: #997;} .cm-s-default .cm-tag {color: #170;} .cm-s-default .cm-attribute {color: #00c;} .cm-s-default .cm-hr {color: #999;} .cm-s-default .cm-link {color: #00c;} .cm-s-default .cm-error {color: #f00;} .cm-invalidchar {color: #f00;} .CodeMirror-composing { border-bottom: 2px solid; } ``` -------------------------------- ### CodeMirror Cursor Styling and Animations (CSS) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/public/playground.html Defines the visual style of the editor's cursor, including its width and border. It also includes styles for secondary cursors, 'fat' cursors, and CSS keyframe animations for a blinking effect, enhancing cursor visibility and feedback. ```CSS .CodeMirror-cursor { border-left: 1px solid black; border-right: none; width: 0; } /* Shown when moving in bi-directional text */ .CodeMirror div.CodeMirror-secondarycursor { border-left: 1px solid silver; } .cm-fat-cursor .CodeMirror-cursor { width: auto; border: 0 !important; background: #7e7; } .cm-fat-cursor div.CodeMirror-cursors { z-index: 1; } .cm-fat-cursor-mark { background-color: rgba(20, 255, 20, 0.5); -webkit-animation: blink 1.06s steps(1) infinite; -moz-animation: blink 1.06s steps(1) infinite; animation: blink 1.06s steps(1) infinite; } .cm-animate-fat-cursor { width: auto; border: 0; -webkit-animation: blink 1.06s steps(1) infinite; -moz-animation: blink 1.06s steps(1) infinite; animation: blink 1.06s steps(1) infinite; background-color: #7e7; } @-moz-keyframes blink { 0% {} 50% { background-color: transparent; } 100% {} } @-webkit-keyframes blink { 0% {} 50% { background-color: transparent; } 100% {} } @keyframes blink { 0% {} 50% { background-color: transparent; } 100% {} } /* Can style cursor different in overwrite (non-insert) mode */ .CodeMirror-overwrite .CodeMirror-cursor {} ``` -------------------------------- ### Managing Canvas Instance and Updates in JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/api/tags.md This JavaScript code demonstrates how to programmatically interact with a canvas element. It retrieves the canvas instance by ID, manually assigns a `sharedCanvas` (common in WeChat minigame open data domains), and registers an `update` function with `Layout.ticker` to ensure the canvas is redrawn every frame, enabling dynamic content. ```javascript const rank = Layout.getElementsById('rank')[0]; const updateRank = () => { rank.update(); } // 手动指定 canvas 实例 rank.canvas = sharedCanvas; // sharedCanvas 为业务自己管理的 canvas 实例 // 要求Layout每帧刷新开放数据域 canvas 的绘制 Layout.ticker.add(updateRank); ``` -------------------------------- ### Showing ScrollBar using show() method - Javascript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/components/scrollbar.md This snippet demonstrates how to make the vertical scrollbar of a ScrollView element visible programmatically. The `show()` method is called on the `vertivalScrollbar` property within a `Layout.ticker.next` callback to correctly access the component after initialization. ```Javascript const list = Layout.getElementById('scrolllist'); // 在 init 之后内部有些异步逻辑取不到 vertivalScrollbar,需要延迟一帧执行 Layout.ticker.next(() => { list.vertivalScrollbar.show(); }); ``` -------------------------------- ### Core CodeMirror Editor Styling - CSS Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/public/playground.html This CSS snippet defines the fundamental visual styles for the CodeMirror editor. It includes rules for scrollbar fillers, gutters, lines, selections, and various other internal components, ensuring a consistent and functional appearance. It also contains general body and HTML styling for the surrounding page. ```CSS .CodeMirror-scrollbar-filler { right: 0; bottom: 0; } .CodeMirror-gutter-filler { left: 0; bottom: 0; } .CodeMirror-gutters { position: absolute; left: 0; top: 0; min-height: 100%; z-index: 3; } .CodeMirror-gutter { white-space: normal; height: 100%; display: inline-block; vertical-align: top; margin-bottom: -30px; } .CodeMirror-gutter-wrapper { position: absolute; z-index: 4; background: none !important; border: none !important; } .CodeMirror-gutter-background { position: absolute; top: 0; bottom: 0; z-index: 4; } .CodeMirror-gutter-elt { position: absolute; cursor: default; z-index: 4; } .CodeMirror-gutter-wrapper ::selection { background-color: transparent } .CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent } .CodeMirror-lines { cursor: text; min-height: 1px; /* prevents collapsing before first draw */ } .CodeMirror pre.CodeMirror-line, .CodeMirror pre.CodeMirror-line-like { /* Reset some styles that the rest of the page might have set */ -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0; border-width: 0; background: transparent; font-family: inherit; font-size: inherit; margin: 0; white-space: pre; word-wrap: normal; line-height: inherit; color: inherit; z-index: 2; position: relative; overflow: visible; -webkit-tap-highlight-color: transparent; -webkit-font-variant-ligatures: contextual; font-variant-ligatures: contextual; } .CodeMirror-wrap pre.CodeMirror-line, .CodeMirror-wrap pre.CodeMirror-line-like { word-wrap: break-word; white-space: pre-wrap; word-break: normal; } .CodeMirror-linebackground { position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: 0; } .CodeMirror-linewidget { position: relative; z-index: 2; padding: 0.1px; /* Force widget margins to stay inside of the container */ } .CodeMirror-widget {} .CodeMirror-rtl pre { direction: rtl; } .CodeMirror-code { outline: none; } /* Force content-box sizing for the elements where we expect it */ .CodeMirror-scroll, .CodeMirror-sizer, .CodeMirror-gutter, .CodeMirror-gutters, .CodeMirror-linenumber { -moz-box-sizing: content-box; box-sizing: content-box; } .CodeMirror-measure { position: absolute; width: 100%; height: 0; overflow: hidden; visibility: hidden; } .CodeMirror-cursor { position: absolute; pointer-events: none; } .CodeMirror-measure pre { position: static; } div.CodeMirror-cursors { visibility: hidden; position: relative; z-index: 3; } div.CodeMirror-dragcursors { visibility: visible; } .CodeMirror-focused div.CodeMirror-cursors { visibility: visible; } .CodeMirror-selected { background: #d9d9d9; } .CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } .CodeMirror-crosshair { cursor: crosshair; } .CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; } .CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; } .cm-searching { background-color: #ffa; background-color: rgba(255, 255, 0, .4); } /* Used to force a border model for a node */ .cm-force-border { padding-right: .1px; } @media print { /* Hide the cursor when printing */ .CodeMirror div.CodeMirror-cursors { visibility: hidden; } } /* See issue #2901 */ .cm-tab-wrap-hack:after { content: ''; } /* Help users use markselection to safely style text background */ span.CodeMirror-selectedtext { background: none; } * { margin: 0; } body, html { margin: 0; padding: 0; height: 100%; } section, article { display: block; padding: 0; } body { background: #f8f8f8; font-family: 'Source Sans Pro', Helvetica, Arial, sans-serif; line-height: 1.5; } p { margin-top: 0; } h2, h3, h1 { font-weight: normal; margin-bottom: .7em; } h1 { font-size: 140%; } h2 { font-size: 120%; } h3 { font-size: 110%; } article > h2:first-child, section:first-child > h2 { margin-top: 0; } #nav h1 { margin-right: 12px; margin-top: 0; margin-bottom: 2px; color: #d30707; letter-spacing: .5px; } a, a:visited, a:link, .quasilink { color: #A21313; } em { padding-right: 2px; } .quasilink { cursor: pointer; } article { max-width: 700px; margin: 0 0 0 160px; border-left: 2px solid #E30808; border-right: 1px solid #ddd; padding: 30px 50px 100px 50px; background: white; z-index: 2; position: relative; min-height: 100%; box-sizing: border-box; -moz-box-sizing: border-box; } #nav { position: fixed; padding-top: 30px; max-height: 100%; box-sizing: -moz-border-box; box-sizing: border-box; overflow-y: auto; left: 0; right: none; width: 160px; text-align: right; z-index: 1; } @media screen and (min-width: 1000px) { article { margin: 0 auto; } #nav { right: 50%; width: auto; border-right: 349px solid transparent; } } #nav ul { display: block; margin: 0; padding: 0; margin-bottom: 32px; } #nav a { text-decoration: none; } #nav li { display: block; margin-bottom: 4px; } #nav li ul { font-size: 80%; margin-bottom: 0; display: none; } #nav li.active ul { display: block; } #nav li li a { padding-right: ``` -------------------------------- ### Using bitmaptext Tag in HTML Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/api/tags.md This HTML snippet demonstrates the usage of the `bitmaptext` tag for displaying text with custom bitmap fonts. It specifies the `font` attribute to link to a registered bitmap font, a `class` for styling, and a `value` for the text content. ```html ``` -------------------------------- ### Updating Viewport in Web Mode - Layout - JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/api/api.md Demonstrates how to update the `Layout` engine's viewport information using `canvas.getBoundingClientRect()` when running in a Web environment. This is crucial for correct event handling (clicks, slides) as it provides the absolute position and dimensions of the canvas on the screen. ```JavaScript Layout.updateViewPort(canvas.getBoundingClientRect()); ``` -------------------------------- ### CodeMirror Padding and Filler Styles (CSS) Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/public/playground.html Manages the vertical and horizontal padding for content lines within the CodeMirror editor and sets the background color for scrollbar and gutter fillers, ensuring proper spacing and visual consistency. ```CSS .CodeMirror-lines { padding: 4px 0; /* Vertical padding around content */ } .CodeMirror pre.CodeMirror-line, .CodeMirror pre.CodeMirror-line-like { padding: 0 4px; /* Horizontal padding of content */ } .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { background-color: white; /* The little square between H and V scrollbars */ } ``` -------------------------------- ### Styling Canvas and Container with JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/api/tags.md This JavaScript object defines the layout and appearance styles for both the `container` view and the `rank` canvas. It sets their respective `width`, `height`, and a `backgroundColor` for the container, influencing how these elements are rendered and positioned on the page. ```javascript let style = { container: { width: 500, height: 500, backgroundColor: '#f3f3f3', }, rank: { width: 300, height: 300, } } ``` -------------------------------- ### Defining CSS Styles for Loading Indicator - JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/tutorial/loading.md This JavaScript object defines the inline styles for the loading container and the loading image. The container is set to a fixed size with a white background and centers its content. The loading image is styled as a small, circular element. ```JavaScript let style = { container: { width: 400, height: 400, backgroundColor: "#ffffff", justifyContent: "center", alignItems: "center", }, loading: { width: 50, height: 50, borderRadius: 25, }, }; ``` -------------------------------- ### Declaring Canvas Component HTML Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/components/canvas.md Defines the HTML structure for the canvas component within a layout view. It includes a container view and the canvas element with specified ID, width, and height attributes. This structure is used by the layout engine to create the component instance. ```html ``` -------------------------------- ### Defining Layout Styles JavaScript Source: https://github.com/wechat-miniprogram/minigame-canvas-engine/blob/master/docs/components/canvas.md Specifies JavaScript style objects for the layout elements. It defines dimensions and background color for the container view and dimensions for the canvas element identified by 'rank'. These styles are typically applied by the layout engine. ```javascript let style = { container: { width: 500, height: 500, backgroundColor: '#f3f3f3', }, rank: { width: 300, height: 300, } } ```