search
HomeWeb Front-endH5 TutorialHtml5 game framework createJS component-EaselJS detailed explanation

CreateJS library is an engine for HTML5 game development. It is an open source toolkit that can build HTML5 games with rich interactive experience, aiming to reduce the development of HTML5 projects. difficulty and cost, allowing developers to create a more modern online interaction experience in a familiar way.

Mastering CreateJS can more easily complete HTML5 game development.

CreateJS provides four tools: EaselJS, TweenJS, SoundJS and PreLoadJS:

EaselJS:简化处理HTML5画布
TweenJS:用来帮助调整HTML5和Javascript属性
SoundJS:用来简化处理HTML5 audio
PreLoadJS:帮助管理和协调加载中的一些资源

You can download the JS file on the download page of the official website, or use the direct official CDN link

## The #EaselJS library provides a preserved graphics mode for the canvas, which includes a complete hierarchical display list, a core interaction model, and a helper class to make 2D graphics easier to implement on the canvas.

Start

First we need to create a Stage object to wrap a canvas (

Canvas) element and add a DisplayObject object instance as a subclass. EaselJS supports:

* Use Bitmap to create images

* Use Shape and Graphics to create vector graphics

* Use SpriteSheet and Sprite to create dynamic bitmaps

* Use Text to create simple text

* Use Container to create a container to save other display objects

All display objects can be added to the stage as subclasses, or directly on the stage Drawn on canvas.

User interaction

When interacting with the mouse or touch, all display objects except DOM elements can dispatch events. EaselJS supports hover, press, and release events, as well as an easy-to-use drag-and-drop module. Click MouseEvent for more information.

Example

##1. Use Bitmap to create an imageFirst, we need to reference the EaselJS file:

<script src="js/easeljs-0.8.2.min.js"></script>

Next, we need to create a canvas element in the

HTML document

:

<canvas id="imageView" width="560" height="410">您的浏览器版本过低,请更换更高版本的浏览器</canvas>
Then, I can create the image in the Javascript code:

// 通过画布ID 创建一个 Stage 实例
var stage = new createjs.Stage("imageView");
// 创建一个 Bitmap 实例
var theBitmap = new createjs.Bitmap("imgs/testImg.jpg");
// 设置画布大小等于图片实际大小
stage.canvas.width = theBitmap.image.naturalWidth;
stage.canvas.height = theBitmap.image.naturalHeight;
// 把Bitmap 实例添加到 stage 的显示列表中
stage.addChild(theBitmap);
// 更新 stage 渲染画面
stage.update();

In this way, the image is created successfully. See easeljs-image.html for the source code.

2. Use Shape and Graphics to create vector graphicsSame as above, we You need to add a reference to EaselJS and create a canvas element in the HTML document. Then there is our customized js file code:

//Create a stage by getting a reference to the canvas
var stage = new createjs.Stage("circleView");
//Create a Shape DisplayObject.
var circle = new createjs.Shape();
circle.graphics.beginFill("DeepSkyBlue").drawCircle(0,0,40);
//Set position of Shape instance.
circle.x = circle.y = 50;
//Add Shape instance to stage display list.
stage.addChild(circle);
//Update stage will render next frame
stage.update();

In this way, we create a dark sky blue circle with a center of (50.50) and a radius of 40 pixels (see easeljs-shape-circle.html for the source code ):

The canvas before rendering is as follows (width and height are 100 pixels):

We can also add simple Interactive events:

stage.addEventListener("click",handleClick);function handleClick() {    
// Click happened;
    console.log("The mouse is clicked.");
}
stage.addEventListener("mousedown",handlePress);function handlePress() {    
// A mouse press happened.
    // Listen for mouse move while the mouse is down:
    
    console.log("The mouse is pressed.");
    stage.addEventListener("mousemove",handleMove);
}function handleMove() {    
// Check out the DragAndDrop example in GitHub for more
    console.log("The mouse is moved.");
}

When we click on the circle event, the console will display:

The mouse is pressed.
The mouse is clicked.

We can also use the tick event to perform animation effects such as graphic movement (see source code in

easeljs -shape-circle-move.js

):

// Update stage will render next frame
createjs.Ticker.addEventListener("tick",handleTick);
//添加一个Ticker类帮助避免多次调用update方法
function handleTick() {    
var maxX =  stage.canvas.width - 50;    
var maxY =  stage.canvas.height - 50;    
//Will cause the circle to wrap back
    if(circle.x < maxX && circle.y == 50){        
    // Circle will move 10 units to the right.
        circle.x +=10;
    }else if(circle.x == maxX && circle.y <maxY){
        circle.y +=10;
    }else if(circle.x > 50 && circle.y == maxY){
        circle.x -=10;
    }else if(circle.x<= 50){
        circle.y -=10;
    }
    stage.update();
}
Effect:

3 .Use SpriteSheet and Sprite to create dynamic bitmaps Similarly, first reference EaselJS, and then create the canvas

HTML element

<canvas id="view" width="80" height="80"></canvas>

Pictures to be used:

Next, edit the resources in the JS file Quote loading:

var stage = new createjs.Stage("view");
container = new createjs.Container();var data = {    
// 源图像的数组。图像可以是一个html image实例,或URI图片。前者是建议控制堆载预压
    images:["imgs/easeljs-preloadjs-animation/moveGuy.png"],    
    // 定义单个帧。有两个支持格式的帧数据:当所有的帧大小是一样的(在一个网格), 使用对象的width, height, regX, regY 统计特性。
    // width & height 所需和指定的帧的尺寸
    // regX & regY 指示帧的注册点或“原点”
    // spacing 表示帧之间的间隔
    // margin 指定图像边缘的边缘
    // count 允许您指定在spritesheet帧的总数;如果省略,这将根据源图像的尺寸和结构计算。帧将被分配的指标,根据他们的位置在源图像(左至右,顶部至底部)。
    frames:{width:80,height:80, count:16, regX: 0, regY:0, spacing:0, margin:0},    
    // 一个定义序列的帧的对象,以发挥命名动画。每个属性对应一个同名动画。
    // 每个动画必须指定播放的帧,还可以包括相关的播放速度(如2 将播放速度的两倍,0.5半)和下一个动画序列的名称。    
    animations:{
        run:[0,3]
    }
}var spriteSheet = new createjs.SpriteSheet(data)var instance = new createjs.Sprite(spriteSheet,"run")

container.addChild(instance);
stage.addChild(container);
createjs.Ticker.setFPS(5); //设置帧createjs.Ticker.addEventListener("tick",stage);
stage.update();

In this way, the effect of simple walking comes out (see the source code

easeljs-sprite-01.html

):

If you want to control the transformation of animation through buttons, just use the gotoAndPlay(action) method to call the corresponding animation effect.

We modify the HTML document code as follows:

<canvas id="view" width="80" height="80"></canvas>

Then modify the JS code as follows:

var stage = new createjs.Stage("view");
container = new createjs.Container();var data = {
    images:["imgs/easeljs-preloadjs-animation/moveGuy.png"],
    frames:{width:80,height:80, count:16, regX: 0, regY:0, spacing:0, margin:0},
    animations:{
        stand:0,
        run1:[0,3],
        run2:[4,7],
        run3:[8,11],
        run4:[12,15]
    }
}var spriteSheet = new createjs.SpriteSheet(data)var instance = new createjs.Sprite(spriteSheet,"run1")

container.addChild(instance);
stage.addChild(container);
createjs.Ticker.setFPS(5);
createjs.Ticker.addEventListener("tick",stage);
stage.update();

document.getElementById(&#39;goStraight&#39;).onclick =  function goStraight() {
    instance.gotoAndPlay("run1");
}
document.getElementById(&#39;goLeft&#39;).onclick =  function goLeft() {
    instance.gotoAndPlay("run2");
}
document.getElementById(&#39;goRight&#39;).onclick =  function goRight() {
    instance.gotoAndPlay("run3");
}
document.getElementById(&#39;goBack&#39;).onclick =  function goBack() {
    instance.gotoAndPlay("run4");
}

效果就出来了(源码见 easeljs-sprite-02.html):

 

4.使用 Text 创建简单的文本

这个就比较简单了,直接看代码:


<canvas id="View" width="300" height="80"></canvas><script>
    var stage = new createjs.Stage("View");    
    var theText = new createjs.Text("Hello,EaselJS!","normal 32px microsoft yahei","#222222");
    stage.addChild(theText);
    stage.update();</script>

这里有设置背景色为粉红:

#View { background-color: #fddfdf;}

显示效果为:

 

5.使用 Container 创建保存其他显示对象的容器

其实这个在前面已经用过了。不过还是单独写个例子,这个比较简单:

<!DOCTYPE html>

<html lang="en"><head>
    <meta charset="UTF-8">
    <title>使用 Container 创建保存其他显示对象的容器</title>
    <script src="js/base/easeljs-0.8.2.min.js">
    </script>
    </head>
    <body>
    <canvas id="view" width="300" height="300">
    </canvas>
    <script>
    var stage = new createjs.Stage("view");
    container = new createjs.Container();    //先来绘制个正方形
    var square = new createjs.Shape();
    square.graphics.beginFill("#ff0000").drawRect(0,0,300,300);
    container.addChild(square);    //先来绘制个正方形
    var square2 = new createjs.Shape();
    square2.graphics.beginFill("orange").drawRect(50,50,200,200);
    container.addChild(square2);    //然后我们来绘制个圆形
    var circle = new createjs.Shape();
    circle.graphics.beginFill("blue").drawCircle(150,150,100);
    container.addChild(circle);    //最后我们再绘制个圆形
    var circle2 = new createjs.Shape();
    circle2.graphics.beginFill("white").drawCircle(150,150,50);
    container.addChild(circle2);

    stage.addChild(container);
    stage.update();</script></body></html>

效果如下:

 

The above is the detailed content of Html5 game framework createJS component-EaselJS detailed explanation. 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
HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5: How It Enhances User Experience on the WebH5: How It Enhances User Experience on the WebApr 19, 2025 am 12:08 AM

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

Deconstructing H5 Code: Tags, Elements, and AttributesDeconstructing H5 Code: Tags, Elements, and AttributesApr 18, 2025 am 12:06 AM

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.