search
HomeWeb Front-endJS TutorialIntroduction to Stage.js

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 .

<🎜>
<🎜>
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.

Stage(function (stage) {
    stage.viewbox(700, 700);
    Stage.image('wheel')
        .appendTo(stage)
        .pin('handle', 0.5);
});

Stage({
    name: 'wheel',
    image: 'wheel.png'
});
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:

<🎜>
<🎜>

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.

Stage(function (stage) {
    stage.viewbox(700, 700);
    Stage.image('wheel')
        .appendTo(stage)
        .pin('handle', 0.5);
});

Stage({
    name: 'wheel',
    image: 'wheel.png'
});

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:

Stage.image('wheel')
    .appendTo(stage)
    .pin({
        handle: 0.5,
        offsetX: 300
    });

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:

Stage.image('wheel')
    .appendTo(stage)
    .pin({
        handle: 0.5,
        scaleX: 1.4
    });

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

node.pin({
    pivotX: x,
    pivotY: y
});

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.

var wheelNode = Stage.image('wheel').appendTo(stage);
wheelNode.pin({
    'handle': 0.5
});
wheelNode.on('click', function () {
    // 在此处对轮子执行某些操作。
});

However, adding the tween method can smooth the transition.

wheelNode.on(click, function () {
     // 在此处对轮子执行某些操作。
 });

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:

var wheelRotation = Math.PI;
var wheelPosition = 300;

wheelNode.on('click', function () {
    wheelRotation = -wheelRotation;
    wheelPosition = -wheelPosition;
    this.pin({
        rotation: wheelRotation,
        offsetX: wheelPosition
    });
});

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:

wheelNode.on('click', function () {
    wheelRotation = -wheelRotation;
    wheelPosition = -wheelPosition;
    this.tween(3000)
        .pin({
            rotation: wheelRotation,
            offsetX: wheelPosition
        })
        .ease('bounce');
});

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

tween.done(function () {
    // 在此处执行您的操作。
});

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
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
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

See all articles

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.