Writing in the front

First of all, thank you for your support. Thank you! Remember in the previous post I said that I am a semi-literary programmer and have always wanted to write technical and other literary articles. Although my foundation is not very good, but always think that this process can urge myself to think, urge myself to learn and communicate. After all, in addition to busy every day, or to live their own different life.

Secondly, I opened my personal homepage, which contains my own technical articles, as well as personal random thoughts, thoughts and logs. All future posts will be updated here as soon as possible and then synchronized to other platforms. Have like friends can have no matter to go to browse, thank you again for your support!

What is a CreateJS

website (
Chinese) : CreateJS is a modular code base and tool suite that can work independently or in combination to develop rich interactive content on the Web using HTML5 technology.

Four core libraries

CreateJS consists of the following four classes:

  • EaselJS— Simplify working with HTML5 canvas (core)
  • TweenJS— To help design H5 animations and adjust HTML5 attributes
  • SoundJS– To simplify processing HTML5 Audio audio
  • PreloadJS– Helps manage and coordinate some resources during loading

Today, mainly to understandEaselJS

EaselJS



EaselJS profile

EaselJSIs a JavaScript library for simple and quick operations
HTML5 CanvasThe label. I had a very friendly experience building H5 games, generating art works, and dealing with other advanced graphics.

Some of the core classes in EaselJS

  1. Stage Class— Create a stage
  2. Text Class— Draw text
  3. Graphics Class— Draw graph
  4. Shape Class— Draw graph
  5. Bitmap Class— Draw pictures
  6. Ticker Class— Time broadcast
  7. . Etc.

Some chestnuts.

Draw Text (Text Class)

Define a
canvas.

// HTML:
<! -- Text Class -->
<canvas id="demo1" width="650" height="400"></canvas>Copy the code

Call the API provided by EaselJS – new createjs.text () to draw the Text

// JS
<script src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
<script>
  window.onload = (a)= > {
    /** * Test Class -- demo */
    let stage1 = new createjs.Stage("demo1");

    let text1 = new createjs.Text("Text 1 !"."bold 26px Arial"."#ff7700");
    text1.regX = - 50;     // The offset along the negative X-axis
    text1.regY = - 50;     // The offset in the negative direction of the Y axis
    text1.x = 100;        // Draw the X coordinate of the source point
    text1.y = 50;         // Draw the Y coordinate of the source point

    let text2 = new createjs.Text("Rotate +XY stretch!"."bold 18px Arial"."#ff7700");
    text2.x = 50;
    text2.y = 50;
    text2.rotation = 50;      // Rotation Angle DEG
    text2.scaleX = 3;         // X - X - X - X
    text2.scaleY = 2;         // X - X - X - X

    let text3 = new createjs.Text("XY axis tilt"."bold 50px Arial"."#ff7700");
    text3.x = 300;
    text3.y = 200;
    text3.skewX = 45;         // The X axis tilt Angle DEG
    text3.skewY = 20;         // The tilt Angle of Y cycle DEG

    let text4 = new createjs.Text("Text shadow"."bold 30px Arial"."#ff7700");
    text4.x = 400;
    text4.y = 100;
    text4.shadow = new createjs.Shadow("# 000000".5.5.10);      // Create a shadow instance Object

    stage1.addChild(text1, text2, text3, text4);
    stage1.update();    // Update the stage. After each change, you need to update the whole stage
  }
</script>Copy the code

Draw Graphics Class

Define a
canvas.

// HTML:
<! -- Graphics Class -->
<canvas id="demo2" width="650" height="400"></canvas>Copy the code

Draw the Graphics by calling the API provided by EaselJS – new createjs.graphics ()

// JS
<script src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
<script>
  window.onload = (a)= > {
    /** * Graphics Class -- demo * for generating vector drawing instructions */
    let stage2 = new createjs.Stage('demo2')

    Draw a line / /
    let g = new createjs.Graphics();
    /* The same Graphics instance can be drawn multiple times, the following line segments, polylines are drawn with g instance */
    g.setStrokeStyle(10).beginStroke("#d23c4f").moveTo(400.10).lineTo(600.100)
    // Short form
    g.ss(20).s('#fafa35').mt(400.100).lt(400.260)
    // Short for multipoint polyline
    g.ss(1).s('# 000').mt(600.400).lt(600.200).lt(400.300).lt(500.550)

    // the Graphics instance cannot addChild() directly to the stage. It must be instantiated as a Shape instance
    let line = new createjs.Shape(g)

    / / round
    let g1 = new createjs.Graphics();
    g1.setStrokeStyle(1);         / / stroke
    g1.beginStroke("# 000000");    // Stroke color
    g1.beginFill("red");          // Fill the graph
    g1.drawCircle(0.0.100);        // Draw (X, X, R)
    let c1 = new createjs.Shape(g1)     // Instantiate the Shape object

    / / rectangle
    let g2 = new createjs.Graphics().beginStroke("red").beginFill("blue").drawRect(150.0.200.100);     // X, Y, W, H
    let c2 = new createjs.Shape(g2)

    // Command object
    let g3 = new createjs.Graphics();
    // Each graphical interface call generates a command object that can be accessed using.command, which holds a reference to the last command created or attached
    let fillCommand = g3.beginFill("green").command;
    g3.drawCircle(200.200.50);        // Draw (X, X, R)
    let c3 = new createjs.Shape(g3);

    // Update the fill style/color after some asynchronous operations:
    setTimeout((a)= > {
      fillCommand.style = "gray";
      stage2.update();                // The stage will not be rerendered without updating
    }, 2000);

    // Click the event
    //c3.addEventListener('click', () => {
    // alert(123)
    // fillCommand.style = "gray";
    // stage2.update(); // The stage will not be rerendered without updating
    / /})
  
    stage2.addChild(c1, c2, c3, line);
    stage2.update();
  }
</script>Copy the code

Draw image imgaes(Bitmap Class)

Define a
canvas.

// HTML:
<! -- Bitmap Class -->
<canvas id="demo3" width="650" height="400"></canvas>Copy the code

Draw the image by calling the API provided by EaselJS – new createJs.bitmap ()

// JS
<script src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
<script>
  window.onload = (a)= > {
    /** * Bitmap Class for rendering images in the canvas display list */
    let stage3 = new createjs.Stage('demo3')

    // Render the image
    let bitmap = new createjs.Bitmap('./assets/img/hill1.png')
    bitmap.alpha = 0.6      / / transparency
    bitmap.cursor = 'help'
    // Create a shadow instance Object(color, offsetX, offsetY, blur)
    bitmap.shadow = new createjs.Shadow("#97c89e".20.10.20);

    // Add a mask to the image
    let bitmap2 = new createjs.Bitmap('./assets/img/avatar.jpg')
    bitmap2.x = 400;        // The X coordinate at which the picture is drawn
    bitmap2.y = 0;          // The starting point of the picture is the Y coordinate
    // Mask graphics
    let shape = new createjs.Shape();
    shape.graphics.beginFill('# 000').drawCircle(0.0.100);
    shape.x = 500;          // The X coordinate of the center
    shape.y = 100;          // The Y coordinate of the center of the circle
    bitmap2.mask = shape;   // Add a mask to the image bg

    // Draw a meadow
    let groundBg = new createjs.Bitmap("./assets/img/ground.png").image;
    let ground = new createjs.Shape();
    w = stage3.canvas.width;      / / 650
    h = stage3.canvas.height;     / / 400
    stage3.addChild(ground)

    stage3.addChild(bitmap, bitmap2)
    stage3.update()       // Refresh is not valid here

    // Listen for periodic broadcasts
    createjs.Ticker.timingMode = createjs.Ticker.RAF;
    createjs.Ticker.addEventListener('tick',(event) => {
      ground.tileW = groundBg.width;
      ground.y = h - groundBg.height;
      ground.graphics.beginBitmapFill(groundBg).drawRect(0.0, w, groundBg.height);
      ground.cache(0.0, w, groundBg.height);
        
      stage3.update()
    });
  }
</script>Copy the code

A small game (from the official website Demo) Running man

Define a canvas

<! -- HTML -->

       
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>running-man game</title>
</head>
<body>
  <canvas id="demoCanvas" width="960" height="400"></canvas>
  </body>
</html>Copy the code

JS code

Here do not write the specific idea of analysis, the code is not long, comments are also very detailed, easy to understand, directly on the code.

// JS
<script src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
<script>
  window.onload = (a)= > {
    let stage, w, h, loader;
    let sky, grant, ground, hill, hill2;

    function init() {
      stage = new createjs.StageGL("demoCanvas");

      // Get the width and height of the canvas
      w = stage.canvas.width;     / / 960
      h = stage.canvas.height;    / / 400

      // Define static resources
      let manifest = [{
        src: "spritesheet_grant.png".id: "grant"}, {     // Sprite action figure
        src: "sky.png".id: "sky"}, {           / / the sky
        src: "ground.png".id: "ground"}, {     / / the ground
        src: "hill1.png".id: "hill"}, {        / / distant mountains
        src: "hill2.png".id: "hill2"           / / close to mountain
      }];     // Array, String, Object
      
      // Create a resource load queue
      // (Boolean) load with XHR or HTML tag
      // If it is false, it is loaded with the tag. If it is not, it is loaded with XHR. The default is true and is loaded using XHR.
      loader = new createjs.LoadQueue(false);
      // Add the "Resource loading completed" event
      loader.addEventListener("complete", handleComplete);
      // Load the resource
      loader.loadManifest(manifest, true."./assets/img/");  // (manifest, loadNow, basePath)
    }

    /** * Static resource loading completed, processing function */
    function handleComplete() {
      // Render the sky
      sky = new createjs.Shape();
      sky.graphics.beginBitmapFill(loader.getResult("sky")).drawRect(0.0, w, h);
      // Define the cache area (the whole sky area))
      sky.cache(0.0, w, h);

      // Render the ground
      let groundImg = loader.getResult("ground");
      ground = new createjs.Shape();
      // Note: drawRect() must be one unit wide
      ground.graphics.beginBitmapFill(groundImg).drawRect(0.0, w + groundImg.width, groundImg.height);
      ground.tileW = groundImg.width;
      ground.y = h - groundImg.height;
      // Cache area (ground area)
      ground.cache(0.0, w + groundImg.width, groundImg.height);

      // Render the mountains in the distance randomly
      hill = new createjs.Bitmap(loader.getResult("hill"));
      // Set image conversion
      // setTransform([x=0], [y=0], [scaleX=1], [scaleY=1], [rotation=0], [skewX=0], [skewY=0], [regX=0], [regY=0])
      hill.setTransform(Math.random() * w, h - hill.image.height * 4 - groundImg.height, 4.4);
      hill.alpha = 0.5;     // Set transparency

      // Render the nearby mountains randomly
      hill2 = new createjs.Bitmap(loader.getResult("hill2"));
      hill2.setTransform(Math.random() * w, h - hill2.image.height * 3 - groundImg.height, 3.3);

      // Create a Sprite image animation
      let spriteSheet = new createjs.SpriteSheet({
        framerate: 30./ / frame rate FPS
        "images": [loader.getResult("grant")].// Sprite original
        "frames": {"width": 165."height": 292."count": 64."regX": 82."regY": 0},  / / initialization
        // Define animation
        "animations": {
          "run": [0.25."run"].// name: [start index, end index, 'next animation name ', multiplier]
          "jump": [26.63."run"]}});// Draw animation
      grant = new createjs.Sprite(spriteSheet, "run");
      // Handle the blank space below the Sprite figure
      grant.y = 35;

      // Render all generated content to the stage
      stage.addChild(sky, ground, hill, hill2, grant);

      // Listen for mouse clicks on the stage
      stage.addEventListener("stagemousedown", () = > {// Play the jump animation
        grant.gotoAndPlay("jump");
      });

      createjs.Ticker.timingMode = createjs.Ticker.RAF;     // RAF / RAF_SYNCHED / TIMEOUT
      createjs.Ticker.addEventListener("tick", tick);
    }


    /** * timer - redraw the stage */
    function tick(event) {
      // event.delta -- Ms from the last tick to the current tick
      let deltaS = event.delta / 1000;
      // The movement distance of the Chevet figure
      let position = grant.x + 150 * deltaS;

      // getBounds() -- Returns the bounds of the current frame relative to the origin of the Sprite diagram
      let grantW = grant.getBounds().width * grant.scaleX;
      grant.x = (position >= w + grantW) ? -grantW : position;

      ground.x = (ground.x - deltaS * 150) % ground.tileW;

      // Move the mountains from right to left
      hill.x = (hill.x - deltaS * 30);
      // If the mountain leaves the screen on the left
      if (hill.x + hill.image.width * hill.scaleX <= 0) {
        hill.x = w;     // Reset to the far right of the screen
      }

      // Handle as above
      hill2.x = (hill2.x - deltaS * 45);
      if (hill2.x + hill2.image.width * hill2.scaleX <= 0) {
        hill2.x = w;
      }

      stage.update();
    }

    // Program main entry - initialization
    init()
  }
</script>Copy the code

The complete code

Demo GitHub address:
The complete code