Home Web Front-end JS Tutorial Introduction to Stage.js

Introduction to Stage.js

Feb 19, 2025 am 11:00 AM

Introduction to Stage.js

Stage.js is a lightweight, open source JavaScript library for cross-platform 2D HTML5 game development. It uses a DOM-like model to manipulate the canvas and manages the rendering cycle of the application itself. This tutorial will introduce the core features of Stage.js to help you get started easily.

Key Points

  • Stage.js is a lightweight, open source JavaScript library for cross-platform 2D HTML5 game development, which uses DOM-like models to handle canvas and independently manage the rendering cycle of your application.
  • The library provides multiple features including node positioning (determining how nodes attach to their parent node), mouse and touch events for interactive updates, tween animations for smooth transitions, and graphic displays and animations for graphical displays and animations texture collection.
  • Stage.js is easy to use and intuitive, and is suitable for developers who want to create interactive web applications or games without complex coding or extensive knowledge of web graphics. It can be installed using npm (Node package manager) and thanks to its responsive design, it is compatible with desktop and mobile platforms.

Installation and use

First, download the Stage.js library. You can get the latest version from the GitHub repository (which contains some beginner examples). You can also load it directly from the CDN if you prefer. After including the core files, you must add your own JavaScript files, but be careful not to include your application files before the library .

1

2

<🎜>

<🎜>

Copy after login
Copy after login
Creating an application in Stage.js is achieved by passing a callback function to

. The library will load all required components. Finally, it will call the callback function and render everything to the screen. Each application you create will have a tree and the stage will be at the root of that tree. All other elements, such as images or strings, will become their nodes. During each rendering cycle, when the node is updated, the application tree will be redrawn. Stage()

Node Positioning (Pinning)

Node positioning determines how a node is attached to its parent node. There are many options you can set using node positioning. Some of them are size, position, alignment, and transformation. Here is a simple example and its explanation.

1

2

3

4

5

6

7

8

9

10

11

Stage(function (stage) {

    stage.viewbox(700, 700);

    Stage.image('wheel')

        .appendTo(stage)

        .pin('handle', 0.5);

});

 

Stage({

    name: 'wheel',

    image: 'wheel.png'

});

Copy after login
Copy after login
We first specify the viewport size. We attach the image wheel.png referenced as "wheel" to the stage. After that, we use "handle" to set the initial position of this image or node. "handle" on any node, placing itself at the offset specified by the alignment point on its parent node. Both "handle" and "align" are specified as relative units. For example, 0 is the upper left corner and 1 is the lower right corner. The above code positions the wheel in the center of the viewport.

To position the image at a specific horizontal distance from the center, you can use "offsetX" as shown below:

1

2

<🎜>

<🎜>

Copy after login
Copy after login

Please note that the distance above is not 300 pixels, but 3/14 times the size of the viewport. You can also set other values ​​for nodes such as scaling, tilting, and rotation. To scale in a specific direction (such as horizontal), you can use scaleX. The following code snippet scales the wheel horizontally by 1.4 times.

1

2

3

4

5

6

7

8

9

10

11

Stage(function (stage) {

    stage.viewbox(700, 700);

    Stage.image('wheel')

        .appendTo(stage)

        .pin('handle', 0.5);

});

 

Stage({

    name: 'wheel',

    image: 'wheel.png'

});

Copy after login
Copy after login

Rotation, zoom, and tilt will be the center of the node as the rotation point by default. You can also set different rotation points for nodes using the following methods:

1

2

3

4

5

6

Stage.image('wheel')

    .appendTo(stage)

    .pin({

        handle: 0.5,

        offsetX: 300

    });

Copy after login

All in all, fixed elements allow you to move them and scale or rotate them.

Mouse and touch events

To update nodes in user interaction, you can use a variety of mouse and touch events. Continue with our wheel example above, we can write the following code:

1

2

3

4

5

6

Stage.image('wheel')

    .appendTo(stage)

    .pin({

        handle: 0.5,

        scaleX: 1.4

    });

Copy after login

Or you can define these events, such as Stage.Mouse.CLICK = 'click';. The updated code will be:

1

2

3

4

node.pin({

    pivotX: x,

    pivotY: y

});

Copy after login

Another example is Stage.Mouse.MOVE = 'touchmove mousemove';.

Tween animation (Tweening)

Tween animation applies smooth transitions to node positioning values. This prevents sudden changes in the position or size of the relevant nodes. For example, the code below rotates the wheel abruptly in PI radians and changes its position by 600 each time it clicks.

1

2

3

4

5

6

7

var wheelNode = Stage.image('wheel').appendTo(stage);

wheelNode.pin({

    'handle': 0.5

});

wheelNode.on('click', function () {

    // 在此处对轮子执行某些操作。

});

Copy after login

However, adding the tween method can smooth the transition.

1

2

3

wheelNode.on(click, function () {

     // 在此处对轮子执行某些操作。

 });

Copy after login

A number of options are available, such as easing method, duration, and delay. In the above code, I have set the duration to 3000 milliseconds and the easing function to bounce. Additionally, you can use a variety of easing functions such as linear, quad, cubic, and quart. Setting the delay will start the transition after the specified delay. If no node is needed after the animation is completed, you can call tween.remove(); to delete the node. To do other actions, you can execute the callback function using the following code snippet after the tween animation is completed:

1

2

3

4

5

6

7

8

9

10

11

var wheelRotation = Math.PI;

var wheelPosition = 300;

 

wheelNode.on('click', function () {

    wheelRotation = -wheelRotation;

    wheelPosition = -wheelPosition;

    this.pin({

        rotation: wheelRotation,

        offsetX: wheelPosition

    });

});

Copy after login

Texture Atlas

Texture is used by the tree node to draw graphics on the canvas. To display graphics on a canvas, you can use a sprite table, also known as a "texture gallery." Setting the name of the texture atlas is optional. The sprite table needs to have a set of named textures. To use them in an application, we can refer to them by name. You can use texture arrays as frames to create animations. The animation itself is a node. Here is an example with animated warriors:

1

2

3

4

5

6

7

8

9

10

wheelNode.on('click', function () {

    wheelRotation = -wheelRotation;

    wheelPosition = -wheelPosition;

    this.tween(3000)

        .pin({

            rotation: wheelRotation,

            offsetX: wheelPosition

        })

        .ease('bounce');

});

Copy after login

To animate a warrior, you need the following code. To make it faster you can increase fps:

1

2

3

tween.done(function () {

    // 在此处执行您的操作。

});

Copy after login

anim There are many other methods, such as gotoFrame(n), which will take you directly to the n frame. Depending on the value of n, you can also use moveFrame(n) to move the n frame forward or backward.

Summary

In this introductory tutorial, we cover everything you need to get started with Stage.js. The concepts discussed should help you create basic character animations and interact with users using sprites. You can learn more about this library from the official website. I also recommend that you download files from their GitHub page. The demo included in the download file will further clarify the issue.

(The FAQ section should be added here, the content is the same as the FAQ section in the input text, but can be slightly rewrite and adjust as needed)

The above is the detailed content of Introduction to Stage.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1244
24
The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles