A cross platform high-performance graphics system.

Overview

spritejs logo

spritejs.org

npm status build status dependency status Package Quality Maintainability License

Spritejs is a cross platform high-performance graphics system, which can render graphics on web, node, desktop applications and mini-programs.

SpritejsNext is the new version of spritejs. It is renderer agnostic enabling the same api to render in multiple contexts: webgl2, webgl, and canvas2d.

Manipulate the sprites in canvas as you do with the DOM elements.

Features

  • Manipulate the sprites element as you do with the DOM elements.
  • Rendering by WebGL2 context.
  • Multiple layers.
  • DOM Events.
  • Object Oriented Programmed Development with ES6+.
  • OffscreenCanvas and Web Worker.
  • Work with d3.
  • Server-side rendering.
  • Vue.

Quick Start

SpriteJS - spritejs.org

<script src="https://unpkg.com/spritejs@3/dist/spritejs.min.js"></script>
<div id="container" style="width:400px;height:400px"></div>
<script>
    const imgUrl = 'https://s5.ssl.qhres.com/static/ec9f373a383d7664.svg'
    const {Scene, Sprite} = spritejs;
    const container = document.getElementById('container');
    const paper = new Scene({
      container,
      width: 400,
      height: 400,
    })

    const sprite = new Sprite(imgUrl)
    sprite.attr({
      bgcolor: '#fff',
      pos: [0, 0],
      size: [400, 400],
      borderRadius: '200'
    })

    paper.layer().appendChild(sprite)
</script>
Learn more at spritejs.org

Usage

In browser:

<script src="https://unpkg.com/spritejs@3/dist/spritejs.min.js"></script>

With Node.js:

npm install spritejs --save
import * as spritejs from 'spritejs';

3D

SpriteJSNext can render 3D elements through 3D extension library.

<script src="https://unpkg.com/spritejs@3/dist/spritejs.es.min.js"></script>
<script src="https://unpkg.com/sprite-extend-3d/dist/sprite-extend-3d.js"></script>

Or from NPM

import {Scene} from 'spritejs';
import {Cube, shaders} from 'sprite-extend-3d';

Examples

Basic

With D3

Compatible with d3.js.

3D Extension

Q-Charts

A visulization library based on spritejs.

Ecosystem & Extensions

Project Description
sprite-vue SpriteJS for Vue.js.
sprite-react Rendering spritejs elements with React.
q-charts A visulization library based on spritejs
cat-charts-vue A visulization library based on spritejs , qcharts and Vue.

Architecture

SpritejsNext provides several kinds of basic sprite elements, which can be operated on the layer like DOM elements.

架构图

Build

Build with NPM

npm run build

Build Doc

npm run build-doc

Tests

npm test

V2

SpriteJS v2.0

Compatibility

Compatible for most modern browsers.

You should import babel-polyfill for early browers(i.e. iOS 8).

Contributors

Thanks goes to these wonderful people (emoji key):


betseyliu

💻 📖

Shero0311

📖

有马

📖 💻

文蔺

💻 🐛

蔡斯杰

💻 📖

Shaofei Cheng

💻 📖

摇太阳

📖

公子

💻

justemit

💻 📖 🐛

Welefen Lee

💻

YUPENG12138

📖

xinde

🐛

ggvswild

🐛

liulinboyi

💻

Lulzx

💻

asidar

💻

alphatr

💻

W-Qing

📖

Credits and Acknowledgements

  • svg-path-contours Approximates an SVG path into a discrete list of 2D contours (polylines).

  • extrude-polyline Extrudes a 2D polyline with a given line thickness and the desired join/cap types.

  • triangulate-contours Triangulates a series of contours using Tess2.js.

  • OGL OGL is a small, effective WebGL library aimed at developers who like minimal layers of abstraction, and are comfortable creating their own shaders.

License

MIT

Comments
  • 快速移动丢帧怎么优化啊

    快速移动丢帧怎么优化啊

    
    p1.on('touchstart', evt => {
          startX = evt.layerX
          startY = evt.layerY
          sprites = p1.attr('pos')
        })
        p1.on('touchmove', evt => {
          const dx = evt.layerX - startX,
            dy = evt.layerY - startY
          p1.attr({
            'pos': [sprites[0] + dx, sprites[1] + dy]
          })
        })
    
    

    在touchstart 保存 起始位置 移动时监听 位置变化 精灵移动慢些还好 如果 移动快了 会出现丢帧 的 情况 有没有 办法 优化啊?

    opened by lunaticnotcrazy 12
  • 加载大图 黑屏

    加载大图 黑屏

    https://zgyrmfy-wfy-in-test-1258757587.cos.ap-beijing.myqcloud.com/0.4729464615246759canvasBg.png 可以试一试 加载这种大图 出来的是黑色背景 电脑浏览器没问题 用手机浏览器就会出问题 https://zgyrmfy-wfy-in-test-1258757587.cos.ap-beijing.myqcloud.com/0.29088296266819724 加载成这样了 黑色
    1.我是直接加载的本地图片 如果用scene.preload加载远程图片就会一直无响应 不回调Promise 现在我的措施是吧大图拆分成九张小图 一张一张的拼接(蛋疼啊) 请大佬有空看看 我用的最新版本 右下角那张小图就能加载出来 Screenshot_2020-03-25-09-25-31-609_mark via

    wontfix 
    opened by xiang473535976 8
  • 试了一下在node端的示例,报错不能用

    试了一下在node端的示例,报错不能用

    官方示例: ` const fs = require('fs'); const {Container} = require('../lib/polyfill/node-canvas'); const {Scene, Sprite} = require('../lib');

    const container = new Container(512, 512); const scene = new Scene({container}); const fglayer = scene.layer('fglayer'); const url = 'https://p0.ssl.qhimg.com/t01a72262146b87165f.png';

    const sprite = new Sprite(); sprite.attr({ pos: [256, 256], size: [100, 100], anchor: 0.5, bgcolor: 'red', texture: url, });

    fglayer.append(sprite);

    setTimeout(() => { const canvas = scene.snapshot(); fs.writeFileSync('snap.png', canvas.toBuffer()); }, 1000); `

    修正路径'spritejs/lib/platform/node-canvas' 也报错。

    opened by deiphi 7
  • 图片在旋转后出现renderRect尺寸长宽增大1的情况。

    图片在旋转后出现renderRect尺寸长宽增大1的情况。

    我现在在做一个比较精细的图片拼版程序,而且需要把拼完后的图片打印出来。这个程序里需要对个别的图片进行(0,90,270)这三个角度的旋转。在旋转后需要知道精确的图片位置、大小,来做一个自动吸附的功能。方便快速处理。但因为图片在旋转后,出现的图片属性renderRect值的不确定。(旋转后图片尺寸在原来的基础上减1,或加1)。特别是在旋转到270度的情况下,这种情况很常见。也有可能根据位置的不同有差异。起初以为原点是中心点的问题而出现的这种情况。测试把中心点就设为初始值的左上角。发现在旋转后,再位移。还是出现这样的问题 。求解决。谢谢。

    bug 
    opened by MrTsao 6
  • TypeError: _this.getResolution is not a function. (In '_this.getResolution()', '_this.getResolution' is undefined)

    TypeError: _this.getResolution is not a function. (In '_this.getResolution()', '_this.getResolution' is undefined)

    多线程worker TypeError: _this.getResolution is not a function. (In '_this.getResolution()', '_this.getResolution' is undefined) spritejs.js 行37065

    `if (!options.canvas) { var _this$getResolution = _this.getResolution(), width = _this$getResolution.width, height = _this$getResolution.height;

        var canvas = _mesh_js_core__WEBPACK_IMPORTED_MODULE_7__["ENV"].createCanvas(width, height, {
          offscreen: false
        });
        if (canvas.style) canvas.style.position = 'absolute';
        if (canvas.dataset) canvas.dataset.layerId = options.id;
        options.canvas = canvas;
      }`
    
    wontfix compatibility 
    opened by superEdwardLong 5
  • 从 https://threejs.org/editor/ 导出的json,不能使用

    从 https://threejs.org/editor/ 导出的json,不能使用

    https://spritejs.org/#/zh-cn/ext3d/index?id=%e7%bb%98%e5%88%b6%e6%a8%a1%e5%9e%8b SpriteJSNext的3D扩展支持ThreeJS的json数据模型,因此只需要将模型以model参数传给Mesh3D对象即可。

    请问如何能快捷准确的导入3d模型呢,比如从obj转json,或者还是有其他的什么方式, threejs官方的导出json,好像也不能用,不知道为啥,是我哪里弄错了么

    opened by xinde 4
  • [types]  parameter type should  convert by Partial

    [types] parameter type should convert by Partial

    //replace 
    export class Node  {
      animate (frames: Array<Attr>>, timing: Timing): Animation
    }
    //to
    export class Node  {
      animate (frames: Array<Partial<Attrs>>, timing: Timing): Animation
    }
    

    原先的写法,在ts里会报错,因为Attr里所有属性都不是可选项。

    opened by odex21 4
  • 如何渲染一个视频呢

    如何渲染一个视频呢

    想将一个视频渲染进去,但是总是只显示第一帧,不更新,请问应该怎么让其更新呢,我的代码如下 const canvas = document.createElement('canvas') canvas.width = 1200 canvas.height = 1200 const ctx = canvas.getContext('2d') video.addEventListener('playing', draw) function draw() { ctx.drawImage(video, 0, 0, 1200, 1200) video.attr({ texture: canvas }) requestAnimationFrame(draw) }

    bug 
    opened by satawait 4
  • spritejs3 服务端渲染画图无效

    spritejs3 服务端渲染画图无效

    按照官方文档例子

    const fs = require('fs');
    const {Container} = require('../lib/polyfill/node-canvas');
    const {Scene, Sprite} = require('../lib');
    
    const container = new Container(512, 512);
    const scene = new Scene({container});
    const fglayer = scene.layer('fglayer');
    const url = 'https://p0.ssl.qhimg.com/t01a72262146b87165f.png';
    
    const sprite = new Sprite();
    sprite.attr({
      pos: [256, 256],
      size: [100, 100],
      anchor: 0.5,
      bgcolor: 'red',
      texture: url,
    });
    
    fglayer.append(sprite);
    
    setTimeout(() => {
      const canvas = scene.snapshot();
      fs.writeFileSync('snap.png', canvas.toBuffer());
    }, 1000);
    

    问题是npm安装的spritejs 3.1.24中找不到这个路径,导致无法运行,通过阅读代码发现了 spritejs/lib/platform/node-canvas

    
    import { polyfill } from 'spritejs/lib/platform/node-canvas';
    polyfill({ENV});
    
    const scene = new Scene({width: 300, height: 300});
    log.info('preload', BackgroundImage);
    
    await scene.preload(BackgroundImage, this.productImage);
    const layer = scene.layer();
    
    log.info('bgSprite');
    const bgSprite = new Sprite();
    bgSprite.attr({
      textures: [{
        src: BackgroundImage, rect: [0, 0, DEFAULT_RESOLUTION[0], DEFAULT_RESOLUTION[1]]
       }],
      size: DEFAULT_RESOLUTION
    });
    
    log.info('productImageSprite');
    const productImageSprite = new Sprite();
    // TODO: 图片处理
    productImageSprite.attr({
      textures: [{
        src: this.productImage, rect: [0, 0, vsize(380), vsize(380)]
      }],
      size: [ vsize(380), vsize(380) ],
      pos: [ vsize(38), vsize(28) ],
      zIndex: -1
    });
    
    log.info('priceGroup');
    const priceGroup = new Group();
    priceGroup.attr({
      display: 'flex',
      alignItems: 'flex-end',
      pos: [ vsize(430), vsize(242) ]
    });
    
    const pricePrefixLabel = new Label('¥');
    pricePrefixLabel.attr({
      font: `900 ${vsize(38)}px SimHei`,
      color: '#e82033',
      marginBottom: `${vsize(this.priceMarginBottom)}px`,
      textAlign: 'center'
    });
    
    const priceTextLabel = new Label(this.priceText);
    priceTextLabel.attr({
      font: `900 ${vsize(this.fontSize)}px SimHei`,
      color: '#e82033',
      textAlign: 'center'
    });
    
    priceGroup.append(pricePrefixLabel, priceTextLabel);
    layer.append(bgSprite, productImageSprite, priceGroup);
    log.info('snapshot');
    const canvas = await scene.snapshot();
    log.info('toBuffer');
    return canvas.toBuffer('image/png', {});
    

    结果画出的图片是空的,一张透明的png图片。

    PS:上述代码使用spritejs2可以正常绘制(区别是构造Scene的参数不一样),请问我是错误使用了么?如果正确使用spritejs3在nodeJS环境下绘制图片(server rendering)。

    bug Q-question Q-resolved 
    opened by alfredking12 4
  • 部分机型引入 spritejs.min.js 报错

    部分机型引入 spritejs.min.js 报错

    【问题描述】

    • 当前版本的spritejs在部分机型上运行直接报错:

    【复现方法】

    // 仅仅引入该依赖,在部分机型上立即报错白屏了
    import {Scene, Sprite} from 'spritejs/dist/spritejs.min.js';
    ....
    

    【报错信息】 TypeError: Cannot redefine property: name

    【相关机型】

    • vivo x7Plus (Android 5.1.1)
    • vivo x6sa (Android 5.1.1)
    • oppo R831(Android 4.3)

    已尝试单独打包并Babel处理,未果。不知道是否由打包方式引起。

    求助~

    opened by ggvswild 4
  • 华为自带浏览器不支持startsWith导致监听touch事件失效

    华为自带浏览器不支持startsWith导致监听touch事件失效

    华为自带浏览器不支持startsWith导致监听touch事件失效,需要增加polyfill

    if (type.startsWith('touch')) { // 执行到这里报错
      var touches = (0, _from2.default)(evt.originalEvent.touches),
          _layer = this.layer;
      evt.targetTouches = [];
    
      touches.forEach(function (touch) {
        var identifier = touch.identifier;
        if (_layer.touchedTargets[identifier] && _layer.touchedTargets[identifier].indexOf(_this5) >= 0) {
          evt.targetTouches.push(touch);
        }
      });
      evt.touches = touches;
      evt.changedTouches = (0, _from2.default)(changedTouches);
    }
    

    可以复现机型:

    • 华为P10 Plus
    • 华为荣耀Note 10
    compatibility 
    opened by PiLee 4
  • seal 不起效果

    seal 不起效果

    官方的例子:

    group_sealed 删除 bufferSize 属性

    fglayer = scene.layer('fg', {
        handleEvent: false,
        bufferSize: 12000,
      });
    

    drawcall 一直在增加, seal 不起效果

    本地开发

    本地开发的时候, 设置group seal 页面直接不显示了

    bug 
    opened by avenir-zhang 0
  • node 端使用报错 scene.preload 报错

    node 端使用报错 scene.preload 报错

    const earthPNG = 'https://p3.ssl.qhimg.com/t01806718065fe97c65.png', earthJSON = 'https://s3.ssl.qhres2.com/static/d479c28f553c6cff.json';

    await scene.preload([earthPNG, earthJSON]);

    在node端运行上面的代码加载雪碧图会直接报错,fetch is not defined

    compatibility 
    opened by Liting1 1
Releases(v3.8.2)
  • v3.8.2(Nov 9, 2022)

  • v3.6.0(Apr 20, 2020)

  • v3.4.0(Mar 18, 2020)

  • v3.2.5(Feb 19, 2020)

  • v3.2.0(Feb 5, 2020)

  • v3.1.23(Jan 17, 2020)

  • v3.1.2(Dec 31, 2019)

  • v3.0.7(Dec 30, 2019)

    • Fixed the bug that the sprite image did not display because the image was not loaded completely when preloading.
    • Fixed the bug that the cloud texture cannot be updated after meshNode's texture loaded.
    • Add ProtonJS examples.
    Source code(tar.gz)
    Source code(zip)
  • v3.0.6(Dec 29, 2019)

    • SpriteJS v3 released 🚀
    • Support webgl2/webgl rendering.
    • Performance greatly improved.
    • Fix support sprite-vue.
    • Optimized for protonjs.
    • Fixed label vertical position.
    Source code(tar.gz)
    Source code(zip)
  • v2.16.0(Sep 20, 2018)

    features

    • Add displayRatio for Scene and Layer
    • Add enableCache attribute for all sprites
    • Allow append DOM Element into Scene

    bug fix

    • Fix zIndex bug when appendChild or insertBefore
    • Fix .9 Background Image one pixcel bug
    • Fix resolveStates bugs
    Source code(tar.gz)
    Source code(zip)
  • v2.15.0(Sep 10, 2018)

    • Add DOM API for sprite-vue
    • Add percent value for width/height and x/y
    • Add rw、rh unit for width/height and x/y
    • Support inherit value for font, color attributes
    • Optimized cache policy
    • Optimized animation performance
    Source code(tar.gz)
    Source code(zip)
  • v2.6.0(Jul 31, 2018)

    • 🎨 Add bgimage attribute for all elements
    • 🐛 Fixed label with both height and width fixed display lineBreak error.
    • 🐛 Fixed textAlign center or right in multi-line text display error.
    Source code(tar.gz)
    Source code(zip)
  • v2.5.0(Jul 24, 2018)

    • 🎨 Add bounding attribute to Path
    • 🎨 Add lineBreak & wordBreak attributes to Label
    • 🎨 Optimize touch events, support multi-touch
    • 🎨 Add sprite.setMouseCapture to mouse event
    • 📝 More docs
    Source code(tar.gz)
    Source code(zip)
  • v2.4.4(Jul 20, 2018)

  • v2.4.2(Jul 13, 2018)

  • v2.4.1(Jul 12, 2018)

  • v2.4.0(Jul 12, 2018)

  • v2.3.0(Jul 4, 2018)

  • v2.2.0(Jul 2, 2018)

    • 🎨 change sprite.attrs to sprite.attributes
    • 🎨 export utils.findColor and utils.cacheContextPool
    • 📝 add more docs
    • 🐛 fixed cloneNode don't copy dataset bug
    • 🐛 fixed transition.reverse() state bug
    • 🐛 fixed sprite-extend-bmfont load remote image bug
    Source code(tar.gz)
    Source code(zip)
  • untagged-fca8d7b96863548d9b20(Jun 27, 2018)

    • 🎨 add shadow attr
    • 🎨 add sprite.data() and sprite.dataset
    • 🎨 sprite.data() and sprite.attr() support async accessor
    • 🎨 sprite.attrs() to sprite.attrs
    • 🎨 transition.end() and transition.reverse()
    • 🐛 fixed animation reverser finished event not trigger
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0(Jun 19, 2018)

  • v2.0.0-beta.1(Jun 18, 2018)

  • v2.0.0-alpha.32(Jun 15, 2018)

    • 🐛 fixed stickExtend clearRect bug
    • 🎨 group auto virtualization
    • 📝 add proton demos
    • 🎨 improve layer.draw, more friendly with other libraries.
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0-alpha.30(Jun 14, 2018)

  • v2.0.0-alpha.29(Jun 11, 2018)

  • v2.0.0-alpha.25(Jun 8, 2018)

  • v2.0.0-alpha.22(Jun 6, 2018)

  • v2.0.0-alpha.21(Jun 2, 2018)

  • v2.0.0-alpha.20(Jun 1, 2018)

  • v2.0.0-alpha.16(May 29, 2018)

The JavaScript library for modern SVG graphics.

Snap.svg · A JavaScript SVG library for the modern web. Learn more at snapsvg.io. Follow us on Twitter. Install Bower - bower install snap.svg npm - n

Adobe Web Platform 13.6k Dec 30, 2022
The Swiss Army Knife of Vector Graphics Scripting – Scriptographer ported to JavaScript and the browser, using HTML5 Canvas. Created by @lehni & @puckey

Paper.js - The Swiss Army Knife of Vector Graphics Scripting If you want to work with Paper.js, simply download the latest "stable" version from http:

Paper.js 13.5k Dec 30, 2022
A library optimized for concise and principled data graphics and layouts.

MetricsGraphics is a library built for visualizing and laying out time-series data. At around 15kB (gzipped), it provides a simple way to produce comm

Metrics Graphics 7.5k Dec 22, 2022
A lightweight JavaScript graphics library with the intuitive API, based on SVG/VML technology.

GraphicsJS GraphicsJS is a lightweight JavaScript graphics library with the intuitive API, based on SVG/VML technology. Overview Quick Start Articles

AnyChart 973 Jan 3, 2023
Create graphics with a hand-drawn, sketchy, appearance

Rough.js Rough.js is a small (<9 kB) graphics library that lets you draw in a sketchy, hand-drawn-like, style. The library defines primitives to draw

Rough 17.8k Dec 30, 2022
React + Canvas = Love. JavaScript library for drawing complex canvas graphics using React.

React Konva React Konva is a JavaScript library for drawing complex canvas graphics using React. It provides declarative and reactive bindings to the

konva 4.9k Jan 9, 2023
A library optimized for concise and principled data graphics and layouts.

MetricsGraphics is a library built for visualizing and laying out time-series data. At around 15kB (gzipped), it provides a simple way to produce comm

Metrics Graphics 7.5k Dec 22, 2022
A lightweight JavaScript graphics library with the intuitive API, based on SVG/VML technology.

GraphicsJS GraphicsJS is a lightweight JavaScript graphics library with the intuitive API, based on SVG/VML technology. Overview Quick Start Articles

AnyChart 937 Feb 5, 2021
An open-source visualization library specialized for authoring charts that facilitate data storytelling with a high-level action-driven grammar.

Narrative Chart Introduction Narrative Chart is an open-source visualization library specialized for authoring charts that facilitate data storytellin

Narrative Chart 45 Nov 2, 2022
An easy-to-use cross-framework JS charting library

Compact Chart Visualize your data under a minute, in any Javascript framework Table of Contents About How to use it Examples Demo Plain HTML Example w

Mireo 1 Jul 28, 2021
Processing Foundation 18.6k Jan 1, 2023
Gephi - The Open Graph Viz Platform

Gephi - The Open Graph Viz Platform Gephi is an award-winning open-source platform for visualizing and manipulating large graphs. It runs on Windows,

Gephi 5.1k Jan 4, 2023
Apache Superset is a Data Visualization and Data Exploration Platform

Superset A modern, enterprise-ready business intelligence web application. Why Superset? | Supported Databases | Installation and Configuration | Rele

The Apache Software Foundation 49.9k Dec 31, 2022
A platform for creating interactive data visualizations

owid-grapher This is the project we use at Our World in Data to create embeddable visualizations like this one (click for interactive): ⚠️ This projec

Our World in Data 1.1k Jan 4, 2023
The friendly, pragmatic and functional ID system

pika Combine Stripe IDs with Snowflake IDs and you get... pika! - the last ID system you'll ever need, combining pragmatism with functionality. Exampl

Hop 89 Jan 3, 2023
A TypeScript implementation of High-Performance Polynomial Root Finding for Graphics (Yuksel 2022)

Nomial Nomial is a TypeScript implementation of Cem Yuksel's extremely fast, robust, and simple root finding algorithm presented in the paper "High-Pe

Peter Boyer 10 Aug 3, 2022
Theatre.js is an animation library for high-fidelity motion graphics.

Theatre.js is an animation library for high-fidelity motion graphics. It is designed to help you express detailed animation, enabling you to create intricate movement, and convey nuance.

Aria 8.6k Jan 3, 2023
A scalable, high-performance feature management and progressive experimentation platform

Introduction & Our Philosophy FeatBit is a scalable, high-performance Feature Management and Progressive Experimentation platform. Feature Management

null 345 Jan 1, 2023
The Frontend of Escobar's Inventory Management System, Employee Management System, Ordering System, and Income & Expense System

Usage Create an App # with npx $ npx create-nextron-app my-app --example with-javascript # with yarn $ yarn create nextron-app my-app --example with-

Viver Bungag 4 Jan 2, 2023