StageXL

Setting Up

  1. Create a new Dart project:
dart create -t console my_stagexl_project cd my_stagexl_project
  1. Add StageXL to your pubspec.yaml:
dependencies: stagexl: ^3.0.0
  1. Run dart pub get to install the dependency.

Basic Example

Here’s a simple example of a StageXL application that displays a rectangle and handles a mouse click event.

main.dart

import 'dart:html';
import 'package:stagexl/stagexl.dart';

void main() {
  // Create a Stage and Render the Canvas
  var canvas = querySelector('#stage') as CanvasElement;
  var stage = Stage(canvas);
  var renderLoop = RenderLoop();
  renderLoop.addStage(stage);

  // Create a simple rectangle
  var rectangle = Shape()
    ..graphics.rect(100, 100, 200, 100)
    ..graphics.fillColor(Color.Blue);

  // Add the rectangle to the stage
  stage.addChild(rectangle);

  // Add mouse click event
  rectangle.onMouseClick.listen((event) {
    rectangle.graphics.clear();
    rectangle.graphics.fillColor(Color.Red);
    rectangle.graphics.rect(100, 100, 200, 100);
    rectangle.graphics.fill();
  });

  // Start the render loop
  renderLoop.start();
}

HTML Setup

Make sure you have an HTML file to load your Dart application. Create index.html:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>StageXL Example</title>
  <script defer src="main.dart.js"></script>
  <style>
    canvas {
      background-color: #f0f0f0;
    }
  </style>
</head>
<body>
  <canvas id="stage" width="800" height="600"></canvas>
</body>
</html>

Build and Run

  1. Build your Dart application:
dart compile js main.dart -o main.dart.js
  1. Open index.html in your browser.

Explanation

  • Stage: Represents the main area where you draw.
  • Shape: Used to create shapes (like rectangles) that you can draw on the stage.
  • RenderLoop: A loop that continuously renders the stage.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *