Git Product home page Git Product logo

spritejs's Introduction

spritejs logo

spritejs.com

npm status build 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.com

<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.qhres2.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.com

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

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

spritejs's People

Contributors

akira-cn avatar alphatr avatar angusfu avatar betseyliu avatar lidongjies avatar liulinboyi avatar lizheming avatar lulzx avatar mintnoii avatar odex21 avatar pytxt avatar senasiko avatar shero0311 avatar sijiecai avatar welefen avatar wintercn avatar xgqfrms avatar yaotaiyang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

spritejs's Issues

如何用一张本地图片作为精灵

如果在没开服务器的情况下,我把textures设置为一张本地图片的url时,会报跨域错误,不知道目前有没有解决办法,之后会不会考虑一下使用imgDataUrl作为参数?

borderRadius 大于 50% 。。

提一个不知道是不是 bug 的问题。。。

下面是 DSL:

<s-sprite size="400 400" pos="1000 100" border="4 #c7c" border-radius="300"></s-sprite>

JS(伪代码?) 大概如下:

const sprite = new Sprite()
sprite.size = [400, 400]
sprite.borderRadius = 300
sprite.borderColor = '#c7c'
sprite.borderWitdh = 4

结果如下图:

image

说是问题吧,确实是个问题。。可是严格来说,确实不算 bug,只不过和正常的 DOM & CSS 那一套不太一致而已。。。

Can combine with PIXI.js?

Thanks for author ! It's a very nice frame.

My projects is using PIXI, I'd like to replace the Sprite with Sprite.js. Can it combine with PIXI.js?

是否支持rotate3d,perspective等3d变换

看到attrjs源码里只有translate、rotate、scale、skew、和matrix的2d变换,那么像rotate3d、translate3d、skew3d、perspective等或者rotateX,translateY等该如何实现,是只能引入threejs这样的库吗

请问预加载最大加载时间怎么设置?

有个项目要加载很多图片,所以加载了30秒后出现了
Uncaught (in promise) Error: load img timeout

于是我找到了 node_modules\spritejs\lib\resource.js 里面修改了 var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 30000;的时长,但是这样的话不是一个很好的解决办法,所以我再应用层该怎么设置。

Path的bug:path.d属性无效(Bug of Path: path.d not work)

官方文档的示例无法工作:

code from official document doesn't work.

const imgUrl = 'https://p4.ssl.qhimg.com/t01423053c4cb748581.jpg'
const scene = new Scene('#demo-quickStart', {viewport: ['auto', 'auto'], resolution: [1540, 600]})
const group = new Group()
const arcD = 'M0 0L 50 0A50 50 0 0 1 43.3 25z'
const layer = scene.layer();

group.attr({
  size: [300, 300],
  pos: [770, 300],
  anchor: [0.5, 0.5],
})
layer.append(group)

for(let i = 0; i < 6; i++) {
  const arc = new Path()
  arc.attr({
    path: {
      d:arcD,
      transform: {scale: 3, rotate: -15},
      trim: true,
    },
    pos: [150, 150],
    anchor: [0, 0.5],
    strokeColor: 'red',
    rotate: i * 60,
  })
  arc.attr('fillColor', `rgb(${i * 139 % 255}, 0, 0)`)
  group.append(arc)
}

need some modification

const imgUrl = 'https://p4.ssl.qhimg.com/t01423053c4cb748581.jpg'
const scene = new Scene('#demo-quickStart', {viewport: ['auto', 'auto'], resolution: [1540, 600]})
const group = new Group()
const arcD = 'M0 0L 50 0A50 50 0 0 1 43.3 25z'
const layer = scene.layer();

group.attr({
  size: [300, 300],
  pos: [770, 300],
  anchor: [0.5, 0.5],
})
layer.append(group)

for(let i = 0; i < 6; i++) {
  const arc = new Path(arcD)
  arc.attr({
    path: {
      transform: {scale: 3, rotate: -15},
      trim: true,
    },
    pos: [150, 150],
    anchor: [0, 0.5],
    strokeColor: 'red',
    rotate: i * 60,
  })
  arc.attr('fillColor', `rgb(${i * 139 % 255}, 0, 0)`)
  group.append(arc)
}

官网文档纠错

速查表->Layer->toLocalPos()
toLocalPos(x, y) 将相对于layer所在canvas的相对坐标### 还算成相对于layer的坐标
换算成

animate.timeline.currentTime =0 出现报错

//代码如下:
if (!this.walk.animate) {
//没有调用过的时候
var a = (0, _index.walk)();
this.walk.animate = this.animate(a.frame, a.opt);
this.currentStatus = Object.assign(this.currentStatus, this.STATUS.walk, { type: "walk" });
} else if (this.walk.animate && this.walk.animate.playState !== "running") {
// console.log("pase!!!!!!!!")
//调用过,并且已经停止
this.walk.animate.timeline.currentTime = 0;//报错的行
this.walk.animate.pause(); //必须pause后才能play ;;;
this.walk.animate.play();
this.currentStatus = Object.assign(this.currentStatus, this.STATUS.walk, { type: "walk" });
}

报错如下:
Uncaught TypeError: Cannot read property 'resolve' of undefined
at (anonymous function).reverseTimerID.timeline.setTimeout.delay (http://localhost:3000/static/js/spritejs.js:3761:34)
at spritejs.js:667
at Array.forEach ()
at Timeline.set (spritejs.js:651)
at Sprite.walk (tree.js:840)
at Object.Action (tree.js:2606)
at Object.parallel (tree.js:2562)
at Object.Sequence (tree.js:2545)
at Object.probability (tree.js:2588)
at Object.Filter (tree.js:2650)

请问这个是什么原因,我经常会遇到这个问题。但是不知道是什么回事

快速移动丢帧怎么优化啊

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 保存 起始位置 移动时监听 位置变化
精灵移动慢些还好 如果 移动快了 会出现丢帧 的 情况
有没有 办法 优化啊?

sprite update 事件

sprite.on('update', (evt) => {
rangeBar.value = animation.progress * 100
})

如果在evt中直接包含 progress 或者 animation.progress 或者 animation ,从使用的角度来说,会更方便。

preload多个textures的时候前面那个里面的数据会被覆盖,

问题:
load多个JSON文件的时候后面的json里面的图片无法识别

下面源码:
grenadeJSON2里面的图片找不到
textures: "Grenade_000.png", ///直接在项目根目录找这个文件

已经确认的确有这个图片

const grenadePNG = require("../static/sprite/dead.png"),
grenadeJSON = require("../static/sprite/dead.json");
//第二次加载json和精灵片
` const grenadePNG2 = require("../static/sprite/grenade-0.png"),
grenadeJSON2 = require("../static/sprite/grenade.json");

await scene.preload([grenadePNG, grenadeJSON,grenadePNG2, grenadeJSON2]);  

//,grenadePNG,grenadeJSON
// await load();
const layer = scene.layer();
const group = new Group();
group.attr({
pos: [10, 0],
size: [321, 484],
anchor: [0, 0],
border: {
style: "solid",
width: 6,
color: '#37c',
}
});
const abcd = new Sprite();
abcd.attr({
textures: "Dead (1).png",
anchor: [0, 0],
size: [321, 450],
x: -115 / 2,
y: -26,
border: {
style: "solid",
width: 1,
color:"green"
}
});

const grenade = new Sprite();
grenade.attr({
textures: "Grenade_000.png", ///直接在项目根目录找这个文件
anchor: [0, 0],
size: [321, 450],
x: 100,
y: -26,
border: {
style: "solid",
width: 1,
color:"green"
}
});

group.append(abcd);
group.append(grenade);
layer.append(group);`

能完善文档吗?

感觉目前的文档还不够详细,像Layer就没具体介绍。
然后是API文档,也是很简陋,可以的话增加点示例代码吧,而且还没有中文版的。

如何将代码拆分成多个js引用?

比如我写了一个load.js,里面是预加载,但是预加载完成的texture数据我不知道存在哪里,只能在异步function里面使用吗?我能不能在layer里面拿到这些加载完成的数据?

不同group里面的sprite不能使用OBBCollision检测碰撞

问题:
一个group里面的子弹sprite和另外一个group里面的怪物sprite碰撞了但是没有检测到
疑惑:
我需要做什么额外的配置么
还是不同group里面的sprite不能检测碰撞
感谢:
期待回复,非常谢谢。

源码
bullet.js(子弹):
const grenade = new Sprite();
export { grendeInit, PNG, JSON, grenade, shoot };

Grenade.js(人物和子弹放到一个group):
import {grendeInit as bulltInit, PNG as bulltPng,JSON as bulltJSON,grenade as bulltGrenade,shoot as bulltShoot} from "../bullet/bullet.js"

const group = new Group();
const grenade = new Sprite();

group.append(grenade); //添加人物
group.append(bulltGrenade); //添加子弹

export { grendeInit, grenadePNG,grenadeJSON,grenade,shoot,group,bulltGrenade};

group.js(组合页面):
import { grendeInit, grenadePNG, grenadeJSON,grenade,shoot, group as ggroup,bulltGrenade} from "./group/Grenade.js";;

//...
const scene = new Scene( ....
//...
const layer = scene.layer();
const group = new Group(); //包含怪物一个分组
//...
group.append(abcd);
layer.append(group);
layer.append(ggroup); //ggroup是包含子弹和人物的另外一个分组

//碰撞检测=======
const collision = function(obj, obj2) {
if (obj.OBBCollision(obj2)) {
console.log("中枪!疼!")

     }

}
layer.on('update', (evt) => {
//检测子弹和怪物abcd的碰撞
collision(bulltGrenade,abcd);
});

Bitmap font feature?

Recently, I am looking for a simple canvas library with bitmap font feature which is compatible with wechat mini app.

运行报错

运行命令 npm test,32 passed,1 failed.报错信息如下:
2018-09-05 4 16 36

webpack引入后build报错

使用yarn add spritejs引入
使用yarn start能正常使用
使用yarn build报错

yarn run v1.3.2
$ react-scripts build
Creating an optimized production build...
Failed to compile.

Failed to minify the code from this file:

        ./node_modules/spritejs/src/spritejs.esm.js:7

Read more here: http://bit.ly/2tRViJ9

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

是否能改为es5的编译版本?

建议增加一个removeAllChildren方法

建议增加一个removeAllChildren方法,这样就不用去遍历所有子节点然后删除了,这种操作都是常有的,清空节点内所有子节点。
所以建议写在spritejs内部。

高倍屏下模糊

一开始遇到的问题

我一开始使用的scene配置

 const scene = new Scene('#plane', {
      resolution: [632, 421],
      viewport: ['auto', 'auto'],
});

这时候canvas的width、height与style里的width、height是一样的。
image
渲染的图片存在模糊的问题(左边是绘制的,右边是网页dom)
image

后面的解决方案

网上找了资料发现是因为高倍屏的缘故导致canvas模糊,需要乘设备像素比
于是修改了scene配置

 const scene = new Scene('#plane', {
      resolution: [1264, 842],
      viewport: ['auto', 'auto'],
});

并修改外部div的height和width
image

这时候显示倒是正常了,但是所有的sprite,label坐标和大小等等都要重新修改

真正的问题

spritejs有没有对针对高倍屏的相关配置可以简化这些操作?

windows系统下,yarn start / yarn doc 报错

windows系统下,yarn start / yarn doc 报错,Linux mac正常
Error occured while trying to proxy to: localhost:9090/

webpack-dev-server -d --quiet --port 9090 & http-server example -c-1 -p 9091 (node:56736) DeprecationWarning: loaderUtils.parseQuery() received a non-string value which can be problematic, see https://github.com/webpack/loader-utils/issues/56 parseQuery() will be replaced with getOptions() in the next major version of loader-utils. [HPM] Error occurred while trying to proxy request / from localhost:9090 to http://localhost:9091 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors) [HPM] Error occurred while trying to proxy request /favicon.ico from localhost:9090 to http://localhost:9091 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)

Uploading 1529477597(1).jpg…

Issue on accuracy(?) with official D3 demo

反馈下官网 D3 demo 中的一些细节 ——

链接:官网 D3 demo

原因:未知。(performance?bug?accuracy issue?)

example 01

鼠标快速移动时,从外部进入靠近边缘的圆圈,出现如下现象(问题:城市选中而省份却没选中):

default

default

example 02

操作路径:空白 -> 甘肃 -> 武威 -> (停留一阵)-> (常规速度移动) 哈尔滨 -> 牡丹江 -> 浙江绍兴

default

example 03

操作方式:Mac 下选中江苏,然后滑动到另外一屏,接着滑回到页面移动鼠标至另一省份,如是操作再三即可出现类似如下效果。

default

typescript 支持

后期有对typescript相关支持么,如添加类型描述文件等

layer 配置了{autoRender:false}之后,其父scene调用snapshot一直显示为pendding

首先感谢spritejs这个框架,目前已经写了两个比较有趣的项目了。

const scrawlLayer = this.scene.layer('scrawl', {autoRender: false});
// do something

this.scene.snapshot().then(res=>{
  // never run here
}).catch(e=>{
  // never run here too
})

这是在项目中偶然发现的,发现移除改配置或者在截图前移除该layer后,才可截图成功,具体bug原因等我这两天忙完了再看下

mousedown事件是在鼠标按键弹起时触发的

库版本:master分支的dist里的库文件

如题,mousedown事件的回调并没有在鼠标按下时触发,而是在弹起的时候触发了,
紧接着是mouseup事件触发。
是不是有bug?

追加:按下后拖动鼠标,再弹起鼠标,就不会有任何事件触发。

有没有办法做到在windows onload之后再创建舞台?

现在我是用一个 createstage.js 来创建舞台,再index.js中引入 createstage.js

import {Scene} from 'spritejs';

console.log('in frame window height:' + window.innerHeight);
window.onload = function(){
    console.log('out frame window onloaded height:' + window.innerHeight); 
}
const stage = new Scene('#stage', {
    viewport: [750, 1334-110],  
    resolution: [750,1334-110],
    stickMode: '', 
    stickExtend :true,
}
);
const stageprop = {
    width:stage.resolution[0],
    height:stage.resolution[1],
};

export {stage,stageprop}

这样在场景页面我就能通过stageprop拿到场景的宽高,但是这个宽高其实是设计宽高,手机实际宽高window.innerHeight需要在window.onload里面拿的才是真实的,所以我想问有没有解决方法在window.onload之后再创建舞台?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.