omip-svg - eslint

This commit is contained in:
dntzhang 2019-04-15 09:15:00 +08:00
parent e449e95715
commit 804ceaaab0
69 changed files with 2787 additions and 932 deletions

View File

@ -66,22 +66,23 @@ const cax = {
setInterval: setRafInterval,
clearInterval: clearRafInterval,
tick: function (fn) {
tick: function(fn) {
return setRafInterval(fn, 16)
},
untick: function (tickId) {
untick: function(tickId) {
clearRafInterval(tickId)
},
caxCanvasId: 0,
TWEEN,
To,
h: function (type, props, ...children) {
return { type, props, children };
h: function(type, props, ...children) {
return { type, props, children }
}
};
}
['Quadratic',
;[
'Quadratic',
'Cubic',
'Quartic',
'Quintic',
@ -90,35 +91,36 @@ const cax = {
'Circular',
'Elastic',
'Back',
'Bounce'].forEach(item => {
const itemLower = item.toLowerCase()
cax.easing[itemLower + 'In'] = TWEEN.Easing[item].In
cax.easing[itemLower + 'Out'] = TWEEN.Easing[item].Out
cax.easing[itemLower + 'InOut'] = TWEEN.Easing[item].InOut
'Bounce'
].forEach(item => {
const itemLower = item.toLowerCase()
cax.easing[itemLower + 'In'] = TWEEN.Easing[item].In
cax.easing[itemLower + 'Out'] = TWEEN.Easing[item].Out
cax.easing[itemLower + 'InOut'] = TWEEN.Easing[item].InOut
To.easing[itemLower + 'In'] = TWEEN.Easing[item].In
To.easing[itemLower + 'Out'] = TWEEN.Easing[item].Out
To.easing[itemLower + 'InOut'] = TWEEN.Easing[item].InOut
})
To.easing[itemLower + 'In'] = TWEEN.Easing[item].In
To.easing[itemLower + 'Out'] = TWEEN.Easing[item].Out
To.easing[itemLower + 'InOut'] = TWEEN.Easing[item].InOut
})
const isWegame = typeof wx !== 'undefined' && wx.createCanvas
cax.loadImg = function (option) {
cax.loadImg = function(option) {
const img = isWegame ? wx.createImage() : new Image()
img.onload = function () {
img.onload = function() {
option.complete(this)
}
img.src = option.img
}
cax.loadImgs = function (option) {
cax.loadImgs = function(option) {
const result = []
let loaded = 0
const len = option.imgs.length
option.imgs.forEach((src, index) => {
const img = isWegame ? wx.createImage() : new Image()
img.onload = (function (i, img) {
return function () {
img.onload = (function(i, img) {
return function() {
result[i] = img
loaded++
option.progress && option.progress(loaded / len, loaded, i, img, result)

View File

@ -1,105 +1,294 @@
import To from './to'
To.extend('rubber', [['to', ['scaleX', {
'0': 1.25,
'1': 300
}], ['scaleY', {
'0': 0.75,
'1': 300
}]], ['to', ['scaleX', {
'0': 0.75,
'1': 100
}], ['scaleY', {
'0': 1.25,
'1': 100
}]], ['to', ['scaleX', {
'0': 1.15,
'1': 100
}], ['scaleY', {
'0': 0.85,
'1': 100
}]], ['to', ['scaleX', {
'0': 0.95,
'1': 150
}], ['scaleY', {
'0': 1.05,
'1': 150
}]], ['to', ['scaleX', {
'0': 1.05,
'1': 100
}], ['scaleY', {
'0': 0.95,
'1': 100
}]], ['to', ['scaleX', {
'0': 1,
'1': 250
}], ['scaleY', {
'0': 1,
'1': 250
}]]])
To.extend('rubber', [
[
'to',
[
'scaleX',
{
'0': 1.25,
'1': 300
}
],
[
'scaleY',
{
'0': 0.75,
'1': 300
}
]
],
[
'to',
[
'scaleX',
{
'0': 0.75,
'1': 100
}
],
[
'scaleY',
{
'0': 1.25,
'1': 100
}
]
],
[
'to',
[
'scaleX',
{
'0': 1.15,
'1': 100
}
],
[
'scaleY',
{
'0': 0.85,
'1': 100
}
]
],
[
'to',
[
'scaleX',
{
'0': 0.95,
'1': 150
}
],
[
'scaleY',
{
'0': 1.05,
'1': 150
}
]
],
[
'to',
[
'scaleX',
{
'0': 1.05,
'1': 100
}
],
[
'scaleY',
{
'0': 0.95,
'1': 100
}
]
],
[
'to',
[
'scaleX',
{
'0': 1,
'1': 250
}
],
[
'scaleY',
{
'0': 1,
'1': 250
}
]
]
])
To.extend('bounceIn', [['to', ['scaleX', {
'0': 0,
'1': 0
}], ['scaleY', {
'0': 0,
'1': 0
}]], ['to', ['scaleX', {
'0': 1.35,
'1': 200
}], ['scaleY', {
'0': 1.35,
'1': 200
}]], ['to', ['scaleX', {
'0': 0.9,
'1': 100
}], ['scaleY', {
'0': 0.9,
'1': 100
}]], ['to', ['scaleX', {
'0': 1.1,
'1': 100
}], ['scaleY', {
'0': 1.1,
'1': 100
}]], ['to', ['scaleX', {
'0': 0.95,
'1': 100
}], ['scaleY', {
'0': 0.95,
'1': 100
}]], ['to', ['scaleX', {
'0': 1,
'1': 100
}], ['scaleY', {
'0': 1,
'1': 100
}]]])
To.extend('bounceIn', [
[
'to',
[
'scaleX',
{
'0': 0,
'1': 0
}
],
[
'scaleY',
{
'0': 0,
'1': 0
}
]
],
[
'to',
[
'scaleX',
{
'0': 1.35,
'1': 200
}
],
[
'scaleY',
{
'0': 1.35,
'1': 200
}
]
],
[
'to',
[
'scaleX',
{
'0': 0.9,
'1': 100
}
],
[
'scaleY',
{
'0': 0.9,
'1': 100
}
]
],
[
'to',
[
'scaleX',
{
'0': 1.1,
'1': 100
}
],
[
'scaleY',
{
'0': 1.1,
'1': 100
}
]
],
[
'to',
[
'scaleX',
{
'0': 0.95,
'1': 100
}
],
[
'scaleY',
{
'0': 0.95,
'1': 100
}
]
],
[
'to',
[
'scaleX',
{
'0': 1,
'1': 100
}
],
[
'scaleY',
{
'0': 1,
'1': 100
}
]
]
])
To.extend('flipInX', [['to', ['rotateX', {
'0': -90,
'1': 0
}]], ['to', ['rotateX', {
'0': 20,
'1': 300
}]], ['to', ['rotateX', {
'0': -20,
'1': 300
}]], ['to', ['rotateX', {
'0': 10,
'1': 300
}]], ['to', ['rotateX', {
'0': -5,
'1': 300
}]], ['to', ['rotateX', {
'0': 0,
'1': 300
}]]])
To.extend('flipInX', [
[
'to',
[
'rotateX',
{
'0': -90,
'1': 0
}
]
],
[
'to',
[
'rotateX',
{
'0': 20,
'1': 300
}
]
],
[
'to',
[
'rotateX',
{
'0': -20,
'1': 300
}
]
],
[
'to',
[
'rotateX',
{
'0': 10,
'1': 300
}
]
],
[
'to',
[
'rotateX',
{
'0': -5,
'1': 300
}
]
],
[
'to',
[
'rotateX',
{
'0': 0,
'1': 300
}
]
]
])
To.extend('zoomOut', [['to', ['scaleX', {
'0': 0,
'1': 400
}], ['scaleY', {
'0': 0,
'1': 400
}]]])
To.extend('zoomOut', [
[
'to',
[
'scaleX',
{
'0': 0,
'1': 400
}
],
[
'scaleY',
{
'0': 0,
'1': 400
}
]
]
])

View File

@ -0,0 +1,227 @@
const cache = {}
const cssColors = {
aliceblue: 0xF0F8FF,
antiquewhite: 0xFAEBD7,
aqua: 0x00FFFF,
aquamarine: 0x7FFFD4,
azure: 0xF0FFFF,
beige: 0xF5F5DC,
bisque: 0xFFE4C4,
black: 0x000000,
blanchedalmond: 0xFFEBCD,
blue: 0x0000FF,
blueviolet: 0x8A2BE2,
brown: 0xA52A2A,
burlywood: 0xDEB887,
cadetblue: 0x5F9EA0,
chartreuse: 0x7FFF00,
chocolate: 0xD2691E,
coral: 0xFF7F50,
cornflowerblue: 0x6495ED,
cornsilk: 0xFFF8DC,
crimson: 0xDC143C,
cyan: 0x00FFFF,
darkblue: 0x00008B,
darkcyan: 0x008B8B,
darkgoldenrod: 0xB8860B,
darkgray: 0xA9A9A9,
darkgrey: 0xA9A9A9,
darkgreen: 0x006400,
darkkhaki: 0xBDB76B,
darkmagenta: 0x8B008B,
darkolivegreen: 0x556B2F,
darkorange: 0xFF8C00,
darkorchid: 0x9932CC,
darkred: 0x8B0000,
darksalmon: 0xE9967A,
darkseagreen: 0x8FBC8F,
darkslateblue: 0x483D8B,
darkslategray: 0x2F4F4F,
darkslategrey: 0x2F4F4F,
darkturquoise: 0x00CED1,
darkviolet: 0x9400D3,
deeppink: 0xFF1493,
deepskyblue: 0x00BFFF,
dimgray: 0x696969,
dimgrey: 0x696969,
dodgerblue: 0x1E90FF,
firebrick: 0xB22222,
floralwhite: 0xFFFAF0,
forestgreen: 0x228B22,
fuchsia: 0xFF00FF,
gainsboro: 0xDCDCDC,
ghostwhite: 0xF8F8FF,
gold: 0xFFD700,
goldenrod: 0xDAA520,
gray: 0x808080,
grey: 0x808080,
green: 0x008000,
greenyellow: 0xADFF2F,
honeydew: 0xF0FFF0,
hotpink: 0xFF69B4,
indianred: 0xCD5C5C,
indigo: 0x4B0082,
ivory: 0xFFFFF0,
khaki: 0xF0E68C,
lavender: 0xE6E6FA,
lavenderblush: 0xFFF0F5,
lawngreen: 0x7CFC00,
lemonchiffon: 0xFFFACD,
lightblue: 0xADD8E6,
lightcoral: 0xF08080,
lightcyan: 0xE0FFFF,
lightgoldenrodyellow: 0xFAFAD2,
lightgray: 0xD3D3D3,
lightgrey: 0xD3D3D3,
lightgreen: 0x90EE90,
lightpink: 0xFFB6C1,
lightsalmon: 0xFFA07A,
lightseagreen: 0x20B2AA,
lightskyblue: 0x87CEFA,
lightslategray: 0x778899,
lightslategrey: 0x778899,
lightsteelblue: 0xB0C4DE,
lightyellow: 0xFFFFE0,
lime: 0x00FF00,
limegreen: 0x32CD32,
linen: 0xFAF0E6,
magenta: 0xFF00FF,
maroon: 0x800000,
mediumaquamarine: 0x66CDAA,
mediumblue: 0x0000CD,
mediumorchid: 0xBA55D3,
mediumpurple: 0x9370D8,
mediumseagreen: 0x3CB371,
mediumslateblue: 0x7B68EE,
mediumspringgreen: 0x00FA9A,
mediumturquoise: 0x48D1CC,
mediumvioletred: 0xC71585,
midnightblue: 0x191970,
mintcream: 0xF5FFFA,
mistyrose: 0xFFE4E1,
moccasin: 0xFFE4B5,
navajowhite: 0xFFDEAD,
navy: 0x000080,
oldlace: 0xFDF5E6,
olive: 0x808000,
olivedrab: 0x6B8E23,
orange: 0xFFA500,
orangered: 0xFF4500,
orchid: 0xDA70D6,
palegoldenrod: 0xEEE8AA,
palegreen: 0x98FB98,
paleturquoise: 0xAFEEEE,
palevioletred: 0xD87093,
papayawhip: 0xFFEFD5,
peachpuff: 0xFFDAB9,
peru: 0xCD853F,
pink: 0xFFC0CB,
plum: 0xDDA0DD,
powderblue: 0xB0E0E6,
purple: 0x800080,
red: 0xFF0000,
rosybrown: 0xBC8F8F,
royalblue: 0x4169E1,
saddlebrown: 0x8B4513,
salmon: 0xFA8072,
sandybrown: 0xF4A460,
seagreen: 0x2E8B57,
seashell: 0xFFF5EE,
sienna: 0xA0522D,
silver: 0xC0C0C0,
skyblue: 0x87CEEB,
slateblue: 0x6A5ACD,
slategray: 0x708090,
slategrey: 0x708090,
snow: 0xFFFAFA,
springgreen: 0x00FF7F,
steelblue: 0x4682B4,
tan: 0xD2B48C,
teal: 0x008080,
thistle: 0xD8BFD8,
tomato: 0xFF6347,
turquoise: 0x40E0D0,
violet: 0xEE82EE,
wheat: 0xF5DEB3,
white: 0xFFFFFF,
whitesmoke: 0xF5F5F5,
yellow: 0xFFFF00,
yellowgreen: 0x9ACD32
}
function lerp(start, end, percent){
return makeGradientColor(hexToRgb(start),hexToRgb(end),percent)
}
var hexTriplet = ("01".substr(-1) === "1" ?
// pad 6 zeros to the left
function (cssColor) {
return "#" + ("00000" + cssColor.toString(16)).substr(-6);
}
: // IE doesn't support substr with negative numbers
function (cssColor) {
var str = cssColor.toString(16);
return "#" + (new Array( str.length < 6 ? 6 - str.length + 1 : 0)).join("0") + str;
}
)
function hexToRgb(hex) {
if (cache[hex]) return cache[hex]
let cssColor = null
if (cssColors.hasOwnProperty(hex) ) {
cssColor = hex
hex = hexTriplet(cssColors[hex])
}
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
let shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i
hex = hex.replace(shorthandRegex, function (m, r, g, b) {
return r + r + g + g + b + b
})
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
let key = cssColor ? cssColor : hex
cache[key] = result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null
return cache[key]
}
function makeGradientColor(color1, color2, percent) {
var newColor = {}
if (percent < 0)percent = 0
if (percent > 100)percent = 100
function makeChannel(a, b) {
return (a + Math.round((b - a) * (percent / 100)))
}
function makeColorPiece(num) {
num = Math.min(num, 255) // not more than 255
num = Math.max(num, 0) // not less than 0
var str = num.toString(16)
if (str.length < 2) {
str = "0" + str
}
return (str)
}
newColor.r = makeChannel(color1.r, color2.r)
newColor.g = makeChannel(color1.g, color2.g)
newColor.b = makeChannel(color1.b, color2.b)
newColor.cssColor = "#" +
'#' +
makeColorPiece(newColor.r) +
makeColorPiece(newColor.g) +
makeColorPiece(newColor.b)
return newColor.cssColor
}
export default {
lerp,
hexToRgb,
makeGradientColor
}

View File

@ -5,7 +5,7 @@
*/
if (!Date.now) {
Date.now = function now () {
Date.now = function now() {
return new Date().getTime()
}
}
@ -25,17 +25,17 @@ let queue = [],
let raf = isBrowser ? window.requestAnimationFrame : null
let caf = isBrowser ? window.cancelAnimationFrame : null
function mockRaf (callback, element) {
function mockRaf(callback, element) {
let currTime = now()
let timeToCall = Math.max(0, 16 - (currTime - lastTime))
let id = setTimeout(function () {
let id = setTimeout(function() {
callback(currTime + timeToCall)
}, timeToCall)
lastTime = currTime + timeToCall
return id
}
function mockCaf (id) {
function mockCaf(id) {
clearTimeout(id)
}
@ -45,7 +45,8 @@ if (isBrowser) {
for (; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] ||
window.cancelAnimationFrame =
window[vendors[x] + 'CancelAnimationFrame'] ||
window[vendors[x] + 'CancelRequestAnimationFrame']
}
@ -63,13 +64,13 @@ if (isBrowser) {
caf = cancelAnimationFrame
}
export function setRafInterval (fn, interval) {
export function setRafInterval(fn, interval) {
id++
queue.push({ id: id, fn: fn, interval: interval, lastTime: now() })
if (!ticking) {
let tick = function () {
let tick = function() {
tickId = raf(tick)
each(queue, function (item) {
each(queue, function(item) {
if (item.interval < 17 || now() - item.lastTime >= item.interval) {
item.fn()
item.lastTime = now()
@ -82,7 +83,7 @@ export function setRafInterval (fn, interval) {
return id
}
export function clearRafInterval (id) {
export function clearRafInterval(id) {
let i = 0,
len = queue.length
@ -99,7 +100,7 @@ export function clearRafInterval (id) {
}
}
function each (arr, fn) {
function each(arr, fn) {
if (Array.prototype.forEach) {
arr.forEach(fn)
} else {

View File

@ -1,20 +1,20 @@
import TWEEN from './tween'
import {setRafInterval, clearRafInterval} from './raf-interval'
import { setRafInterval, clearRafInterval } from './raf-interval'
class To {
constructor (element) {
constructor(element) {
this.element = element
this.cmds = []
this.index = 0
this.tweens = []
this._pause = false
this.loop = setRafInterval(function () {
this.loop = setRafInterval(function() {
TWEEN.update()
}, 15)
this.cycleCount = 0
}
to (target, duration, easing) {
to(target, duration, easing) {
this.cmds.push(['to'])
if (arguments.length !== 0) {
for (let key in target) {
@ -24,97 +24,97 @@ class To {
return this
}
set (prop, value, duration, easing) {
set(prop, value, duration, easing) {
this.cmds[this.cmds.length - 1].push([prop, [value, duration, easing]])
return this
}
x () {
x() {
this.cmds[this.cmds.length - 1].push(['x', arguments])
return this
}
y () {
y() {
this.cmds[this.cmds.length - 1].push(['y', arguments])
return this
}
z () {
z() {
this.cmds[this.cmds.length - 1].push(['z', arguments])
return this
}
rotation () {
rotation() {
this.cmds[this.cmds.length - 1].push(['rotation', arguments])
return this
}
scaleX () {
scaleX() {
this.cmds[this.cmds.length - 1].push(['scaleX', arguments])
return this
}
scaleY () {
scaleY() {
this.cmds[this.cmds.length - 1].push(['scaleY', arguments])
return this
}
skewX () {
skewX() {
this.cmds[this.cmds.length - 1].push(['skewX', arguments])
return this
}
skewY () {
skewY() {
this.cmds[this.cmds.length - 1].push(['skewY', arguments])
return this
}
originX () {
originX() {
this.cmds[this.cmds.length - 1].push(['originX', arguments])
return this
}
originY () {
originY() {
this.cmds[this.cmds.length - 1].push(['originY', arguments])
return this
}
alpha () {
alpha() {
this.cmds[this.cmds.length - 1].push(['alpha', arguments])
return this
}
begin (fn) {
begin(fn) {
this.cmds[this.cmds.length - 1].begin = fn
return this
}
progress (fn) {
progress(fn) {
this.cmds[this.cmds.length - 1].progress = fn
return this
}
end (fn) {
end(fn) {
this.cmds[this.cmds.length - 1].end = fn
return this
}
wait () {
wait() {
this.cmds.push(['wait', arguments])
return this
}
then () {
then() {
this.cmds.push(['then', arguments])
return this
}
cycle () {
cycle() {
this.cmds.push(['cycle', arguments])
return this
}
start () {
start() {
if (this._pause) return
var len = this.cmds.length
if (this.index < len) {
@ -125,7 +125,7 @@ class To {
return this
}
pause () {
pause() {
this._pause = true
for (var i = 0, len = this.tweens.length; i < len; i++) {
this.tweens[i].pause()
@ -136,7 +136,7 @@ class To {
}
}
toggle () {
toggle() {
if (this._pause) {
this.play()
} else {
@ -144,14 +144,14 @@ class To {
}
}
play () {
play() {
this._pause = false
for (var i = 0, len = this.tweens.length; i < len; i++) {
this.tweens[i].play()
}
var self = this
if (this.currentTask === 'wait') {
setTimeout(function () {
setTimeout(function() {
if (self._pause) return
self.index++
self.start()
@ -160,19 +160,19 @@ class To {
}
}
stop () {
stop() {
for (var i = 0, len = this.tweens.length; i < len; i++) {
this.tweens[i].stop()
}
this.cmds.length = 0
}
animate (name) {
animate(name) {
this.cmds = this.cmds.concat(To.animationMap[name] || [])
return this
}
exec (cmd, last) {
exec(cmd, last) {
var len = cmd.length,
self = this
this.currentTask = cmd[0]
@ -188,15 +188,15 @@ class To {
var t = new TWEEN.Tween(this.element)
.to(target, task[1][1])
.onStart(function () {
.onStart(function() {
if (cmd.begin) cmd.begin.call(self.element, self.element)
})
.onUpdate(function () {
.onUpdate(function() {
if (cmd.progress) cmd.progress.call(self.element, self.element)
// self.element[prop] = this[prop];
})
.easing(ease || TWEEN.Easing.Linear.None)
.onComplete(function () {
.onComplete(function() {
self.stepCompleteCount++
if (self.stepCompleteCount === len - 1) {
if (cmd.end) cmd.end.call(self.element, self.element)
@ -212,7 +212,7 @@ class To {
case 'wait':
this.currentTaskBegin = new Date()
this.timeout = cmd[1][0]
setTimeout(function () {
setTimeout(function() {
if (self._pause) return
self.index++
self.start()
@ -223,7 +223,7 @@ class To {
case 'then':
var arg = cmd[1][0]
arg.index = 0
arg.complete = function () {
arg.complete = function() {
self.index++
self.start()
if (last && self.complete) self.complete()
@ -251,13 +251,13 @@ class To {
}
}
To.get = function (element) {
To.get = function(element) {
var to = new To(element)
return to
}
To.animationMap = {}
To.extend = function (animationName, cmds) {
To.extend = function(animationName, cmds) {
To.animationMap[animationName] = cmds
}

View File

@ -7,33 +7,35 @@
* Thank you all, you're awesome!
*/
var _Group = function () {
var _Group = function() {
this._tweens = {}
this._tweensAddedDuringUpdate = {}
}
_Group.prototype = {
getAll: function () {
return Object.keys(this._tweens).map(function (tweenId) {
return this._tweens[tweenId]
}.bind(this))
getAll: function() {
return Object.keys(this._tweens).map(
function(tweenId) {
return this._tweens[tweenId]
}.bind(this)
)
},
removeAll: function () {
removeAll: function() {
this._tweens = {}
},
add: function (tween) {
add: function(tween) {
this._tweens[tween.getId()] = tween
this._tweensAddedDuringUpdate[tween.getId()] = tween
},
remove: function (tween) {
remove: function(tween) {
delete this._tweens[tween.getId()]
delete this._tweensAddedDuringUpdate[tween.getId()]
},
update: function (time, preserve) {
update: function(time, preserve) {
var tweenIds = Object.keys(this._tweens)
if (tweenIds.length === 0) {
@ -72,38 +74,43 @@ var TWEEN = new _Group()
TWEEN.Group = _Group
TWEEN._nextId = 0
TWEEN.nextId = function () {
TWEEN.nextId = function() {
return TWEEN._nextId++
}
// Include a performance.now polyfill.
// In node.js, use process.hrtime.
if (typeof (window) === 'undefined' && typeof (process) !== 'undefined') {
if (typeof window === 'undefined' && typeof process !== 'undefined') {
if (typeof wx !== 'undefined') {
TWEEN.now = Date.now
} else {
TWEEN.now = function () {
TWEEN.now = function() {
var time = process.hrtime()
// Convert [seconds, nanoseconds] to milliseconds.
return time[0] * 1000 + time[1] / 1000000
}
}
} else if (typeof (window) !== 'undefined' &&
// In a browser, use window.performance.now if it is available.
window.performance !== undefined && window.performance.now !== undefined) {
} else if (
typeof window !== 'undefined' &&
// In a browser, use window.performance.now if it is available.
window.performance !== undefined &&
window.performance.now !== undefined
) {
// This must be bound, because directly assigning this function
// leads to an invocation exception in Chrome.
TWEEN.now = window.performance.now.bind(window.performance)
} else if (Date.now !== undefined) { // Use Date.now if it is available.
} else if (Date.now !== undefined) {
// Use Date.now if it is available.
TWEEN.now = Date.now
} else { // Otherwise, use 'new Date().getTime()'.
TWEEN.now = function () {
} else {
// Otherwise, use 'new Date().getTime()'.
TWEEN.now = function() {
return new Date().getTime()
}
}
TWEEN.Tween = function (object, group) {
TWEEN.Tween = function(object, group) {
this._object = object
this._valuesStart = {}
this._valuesEnd = {}
@ -132,11 +139,11 @@ TWEEN.Tween = function (object, group) {
}
TWEEN.Tween.prototype = {
getId: function getId () {
getId: function getId() {
return this._id
},
toggle () {
toggle() {
if (this._paused) {
this.play()
} else {
@ -144,23 +151,23 @@ TWEEN.Tween.prototype = {
}
},
pause: function () {
pause: function() {
this._paused = true
var pauseTime = TWEEN.now()
this._passTime = pauseTime - this._startTime
},
play: function () {
play: function() {
this._paused = false
var nowTime = TWEEN.now()
this._startTime = nowTime - this._passTime
},
isPlaying: function isPlaying () {
isPlaying: function isPlaying() {
return this._isPlaying
},
to: function to (properties, duration) {
to: function to(properties, duration) {
this._valuesEnd = properties
if (duration !== undefined) {
@ -170,14 +177,19 @@ TWEEN.Tween.prototype = {
return this
},
start: function start (time) {
start: function start(time) {
this._group.add(this)
this._isPlaying = true
this._onStartCallbackFired = false
this._startTime = time !== undefined ? typeof time === 'string' ? TWEEN.now() + parseFloat(time) : time : TWEEN.now()
this._startTime =
time !== undefined
? typeof time === 'string'
? TWEEN.now() + parseFloat(time)
: time
: TWEEN.now()
this._startTime += this._delayTime
for (var property in this._valuesEnd) {
@ -188,7 +200,9 @@ TWEEN.Tween.prototype = {
}
// Create a local copy of the Array with the start value at the front
this._valuesEnd[property] = [this._object[property]].concat(this._valuesEnd[property])
this._valuesEnd[property] = [this._object[property]].concat(
this._valuesEnd[property]
)
}
// If `to()` specifies a property that doesn't exist in the source object,
@ -200,7 +214,7 @@ TWEEN.Tween.prototype = {
// Save the starting value.
this._valuesStart[property] = this._object[property]
if ((this._valuesStart[property] instanceof Array) === false) {
if (this._valuesStart[property] instanceof Array === false) {
this._valuesStart[property] *= 1.0 // Ensures we're using numbers, not strings
}
@ -210,7 +224,7 @@ TWEEN.Tween.prototype = {
return this
},
stop: function stop () {
stop: function stop() {
if (!this._isPlaying) {
return this
}
@ -226,78 +240,82 @@ TWEEN.Tween.prototype = {
return this
},
end: function end () {
end: function end() {
this.update(this._startTime + this._duration)
return this
},
stopChainedTweens: function stopChainedTweens () {
for (var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i++) {
stopChainedTweens: function stopChainedTweens() {
for (
var i = 0, numChainedTweens = this._chainedTweens.length;
i < numChainedTweens;
i++
) {
this._chainedTweens[i].stop()
}
},
group: function group (group) {
group: function group(group) {
this._group = group
return this
},
delay: function delay (amount) {
delay: function delay(amount) {
this._delayTime = amount
return this
},
repeat: function repeat (times) {
repeat: function repeat(times) {
this._repeat = times
return this
},
repeatDelay: function repeatDelay (amount) {
repeatDelay: function repeatDelay(amount) {
this._repeatDelayTime = amount
return this
},
yoyo: function yoyo (yy) {
yoyo: function yoyo(yy) {
this._yoyo = yy
return this
},
easing: function easing (eas) {
easing: function easing(eas) {
this._easingFunction = eas
return this
},
interpolation: function interpolation (inter) {
interpolation: function interpolation(inter) {
this._interpolationFunction = inter
return this
},
chain: function chain () {
chain: function chain() {
this._chainedTweens = arguments
return this
},
onStart: function onStart (callback) {
onStart: function onStart(callback) {
this._onStartCallback = callback
return this
},
onUpdate: function onUpdate (callback) {
onUpdate: function onUpdate(callback) {
this._onUpdateCallback = callback
return this
},
onComplete: function onComplete (callback) {
onComplete: function onComplete(callback) {
this._onCompleteCallback = callback
return this
},
onStop: function onStop (callback) {
onStop: function onStop(callback) {
this._onStopCallback = callback
return this
},
update: function update (time) {
update: function update(time) {
if (this._paused) return true
var property
var elapsed
@ -316,7 +334,7 @@ TWEEN.Tween.prototype = {
}
elapsed = (time - this._startTime) / this._duration
elapsed = (this._duration === 0 || elapsed > 1) ? 1 : elapsed
elapsed = this._duration === 0 || elapsed > 1 ? 1 : elapsed
value = this._easingFunction(elapsed)
@ -333,7 +351,7 @@ TWEEN.Tween.prototype = {
this._object[property] = this._interpolationFunction(end, value)
} else {
// Parses relative end values with start as base (e.g.: +10, -3)
if (typeof (end) === 'string') {
if (typeof end === 'string') {
if (end.charAt(0) === '+' || end.charAt(0) === '-') {
end = start + parseFloat(end)
} else {
@ -342,7 +360,7 @@ TWEEN.Tween.prototype = {
}
// Protect against non numeric properties.
if (typeof (end) === 'number') {
if (typeof end === 'number') {
this._object[property] = start + (end - start) * value
}
}
@ -360,8 +378,10 @@ TWEEN.Tween.prototype = {
// Reassign starting values, restart by making startTime = now
for (property in this._valuesStartRepeat) {
if (typeof (this._valuesEnd[property]) === 'string') {
this._valuesStartRepeat[property] = this._valuesStartRepeat[property] + parseFloat(this._valuesEnd[property])
if (typeof this._valuesEnd[property] === 'string') {
this._valuesStartRepeat[property] =
this._valuesStartRepeat[property] +
parseFloat(this._valuesEnd[property])
}
if (this._yoyo) {
@ -390,7 +410,11 @@ TWEEN.Tween.prototype = {
this._onCompleteCallback(this._object)
}
for (var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i++) {
for (
var i = 0, numChainedTweens = this._chainedTweens.length;
i < numChainedTweens;
i++
) {
// Make the chained tweens start exactly at the time they should,
// even if the `update()` method was called way past the duration of the tween
this._chainedTweens[i].start(this._startTime + this._duration)
@ -405,122 +429,108 @@ TWEEN.Tween.prototype = {
}
TWEEN.Easing = {
Linear: {
None: function (k) {
None: function(k) {
return k
}
},
Quadratic: {
In: function (k) {
In: function(k) {
return k * k
},
Out: function (k) {
Out: function(k) {
return k * (2 - k)
},
InOut: function (k) {
InOut: function(k) {
if ((k *= 2) < 1) {
return 0.5 * k * k
}
return -0.5 * (--k * (k - 2) - 1)
}
},
Cubic: {
In: function (k) {
In: function(k) {
return k * k * k
},
Out: function (k) {
Out: function(k) {
return --k * k * k + 1
},
InOut: function (k) {
InOut: function(k) {
if ((k *= 2) < 1) {
return 0.5 * k * k * k
}
return 0.5 * ((k -= 2) * k * k + 2)
}
},
Quartic: {
In: function (k) {
In: function(k) {
return k * k * k * k
},
Out: function (k) {
return 1 - (--k * k * k * k)
Out: function(k) {
return 1 - --k * k * k * k
},
InOut: function (k) {
InOut: function(k) {
if ((k *= 2) < 1) {
return 0.5 * k * k * k * k
}
return -0.5 * ((k -= 2) * k * k * k - 2)
}
},
Quintic: {
In: function (k) {
In: function(k) {
return k * k * k * k * k
},
Out: function (k) {
Out: function(k) {
return --k * k * k * k * k + 1
},
InOut: function (k) {
InOut: function(k) {
if ((k *= 2) < 1) {
return 0.5 * k * k * k * k * k
}
return 0.5 * ((k -= 2) * k * k * k * k + 2)
}
},
Sinusoidal: {
In: function (k) {
return 1 - Math.cos(k * Math.PI / 2)
In: function(k) {
return 1 - Math.cos((k * Math.PI) / 2)
},
Out: function (k) {
return Math.sin(k * Math.PI / 2)
Out: function(k) {
return Math.sin((k * Math.PI) / 2)
},
InOut: function (k) {
InOut: function(k) {
return 0.5 * (1 - Math.cos(Math.PI * k))
}
},
Exponential: {
In: function (k) {
In: function(k) {
return k === 0 ? 0 : Math.pow(1024, k - 1)
},
Out: function (k) {
Out: function(k) {
return k === 1 ? 1 : 1 - Math.pow(2, -10 * k)
},
InOut: function (k) {
InOut: function(k) {
if (k === 0) {
return 0
}
@ -535,32 +545,28 @@ TWEEN.Easing = {
return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2)
}
},
Circular: {
In: function (k) {
In: function(k) {
return 1 - Math.sqrt(1 - k * k)
},
Out: function (k) {
return Math.sqrt(1 - (--k * k))
Out: function(k) {
return Math.sqrt(1 - --k * k)
},
InOut: function (k) {
InOut: function(k) {
if ((k *= 2) < 1) {
return -0.5 * (Math.sqrt(1 - k * k) - 1)
}
return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1)
}
},
Elastic: {
In: function (k) {
In: function(k) {
if (k === 0) {
return 0
}
@ -572,7 +578,7 @@ TWEEN.Easing = {
return -Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI)
},
Out: function (k) {
Out: function(k) {
if (k === 0) {
return 0
}
@ -584,7 +590,7 @@ TWEEN.Easing = {
return Math.pow(2, -10 * k) * Math.sin((k - 0.1) * 5 * Math.PI) + 1
},
InOut: function (k) {
InOut: function(k) {
if (k === 0) {
return 0
}
@ -596,29 +602,31 @@ TWEEN.Easing = {
k *= 2
if (k < 1) {
return -0.5 * Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI)
return (
-0.5 * Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI)
)
}
return 0.5 * Math.pow(2, -10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI) + 1
return (
0.5 * Math.pow(2, -10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI) + 1
)
}
},
Back: {
In: function (k) {
In: function(k) {
var s = 1.70158
return k * k * ((s + 1) * k - s)
},
Out: function (k) {
Out: function(k) {
var s = 1.70158
return --k * k * ((s + 1) * k + s) + 1
},
InOut: function (k) {
InOut: function(k) {
var s = 1.70158 * 1.525
if ((k *= 2) < 1) {
@ -627,42 +635,37 @@ TWEEN.Easing = {
return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2)
}
},
Bounce: {
In: function (k) {
In: function(k) {
return 1 - TWEEN.Easing.Bounce.Out(1 - k)
},
Out: function (k) {
if (k < (1 / 2.75)) {
Out: function(k) {
if (k < 1 / 2.75) {
return 7.5625 * k * k
} else if (k < (2 / 2.75)) {
return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75
} else if (k < (2.5 / 2.75)) {
return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375
} else if (k < 2 / 2.75) {
return 7.5625 * (k -= 1.5 / 2.75) * k + 0.75
} else if (k < 2.5 / 2.75) {
return 7.5625 * (k -= 2.25 / 2.75) * k + 0.9375
} else {
return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375
return 7.5625 * (k -= 2.625 / 2.75) * k + 0.984375
}
},
InOut: function (k) {
InOut: function(k) {
if (k < 0.5) {
return TWEEN.Easing.Bounce.In(k * 2) * 0.5
}
return TWEEN.Easing.Bounce.Out(k * 2 - 1) * 0.5 + 0.5
}
}
}
TWEEN.Interpolation = {
Linear: function (v, k) {
Linear: function(v, k) {
var m = v.length - 1
var f = m * k
var i = Math.floor(f)
@ -679,7 +682,7 @@ TWEEN.Interpolation = {
return fn(v[i], v[i + 1 > m ? m : i + 1], f - i)
},
Bezier: function (v, k) {
Bezier: function(v, k) {
var b = 0
var n = v.length - 1
var pw = Math.pow
@ -692,7 +695,7 @@ TWEEN.Interpolation = {
return b
},
CatmullRom: function (v, k) {
CatmullRom: function(v, k) {
var m = v.length - 1
var f = m * k
var i = Math.floor(f)
@ -700,7 +703,7 @@ TWEEN.Interpolation = {
if (v[0] === v[m]) {
if (k < 0) {
i = Math.floor(f = m * (1 + k))
i = Math.floor((f = m * (1 + k)))
}
return fn(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i)
@ -713,26 +716,31 @@ TWEEN.Interpolation = {
return v[m] - (fn(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m])
}
return fn(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i)
return fn(
v[i ? i - 1 : 0],
v[i],
v[m < i + 1 ? m : i + 1],
v[m < i + 2 ? m : i + 2],
f - i
)
}
},
Utils: {
Linear: function (p0, p1, t) {
Linear: function(p0, p1, t) {
return (p1 - p0) * t + p0
},
Bernstein: function (n, i) {
Bernstein: function(n, i) {
var fc = TWEEN.Interpolation.Utils.Factorial
return fc(n) / fc(i) / fc(n - i)
},
Factorial: (function () {
Factorial: (function() {
var a = [1]
return function (n) {
return function(n) {
var s = 1
if (a[n]) {
@ -748,21 +756,24 @@ TWEEN.Interpolation = {
}
})(),
CatmullRom: function (p0, p1, p2, p3, t) {
CatmullRom: function(p0, p1, p2, p3, t) {
var v0 = (p2 - p0) * 0.5
var v1 = (p3 - p1) * 0.5
var t2 = t * t
var t3 = t * t2
return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1
return (
(2 * p1 - 2 * p2 + v0 + v1) * t3 +
(-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 +
v0 * t +
p1
)
}
}
};
}
// UMD (Universal Module Definition)
(function (root) {
;(function(root) {
if (typeof module !== 'undefined' && typeof exports === 'object') {
// Node.js
module.exports = TWEEN

View File

@ -1,8 +1,11 @@
export function getImageInWx (img, callback) {
if ((img.indexOf('https://') === -1 && img.indexOf('http://') === -1) || img.indexOf('http://tmp/') === 0) {
export function getImageInWx(img, callback) {
if (
(img.indexOf('https://') === -1 && img.indexOf('http://') === -1) ||
img.indexOf('http://tmp/') === 0
) {
wx.getImageInfo({
src: img,
success: (info) => {
success: info => {
callback({
img: img,
width: info.width,
@ -13,11 +16,11 @@ export function getImageInWx (img, callback) {
} else {
wx.downloadFile({
url: img,
success: (res) => {
success: res => {
if (res.statusCode === 200) {
wx.getImageInfo({
src: res.tempFilePath,
success: (info) => {
success: info => {
callback({
img: res.tempFilePath,
width: info.width,
@ -31,8 +34,13 @@ export function getImageInWx (img, callback) {
}
}
function getGlobal () {
if (typeof global !== 'object' || !global || global.Math !== Math || global.Array !== Array) {
function getGlobal() {
if (
typeof global !== 'object' ||
!global ||
global.Math !== Math ||
global.Array !== Array
) {
if (typeof self !== 'undefined') {
return self
} else if (typeof window !== 'undefined') {
@ -40,18 +48,45 @@ function getGlobal () {
} else if (typeof global !== 'undefined') {
return global
}
return (function () {
return (function() {
return this
})()
}
return global
}
export function toSVGString(shapes) {
return shapes
.map(function(shape) {
shape.forEach(function(point, idx) {
if (!idx) {
/*
* 若是第一个点数组那么对该点数组的处理是前面加M,然后前两个点后面加C
* */
point.splice(2, 0, 'C')
point.unshift('M')
} else {
/*
* 除了第一个点数据外,所有的点数组的前两个点删除掉
* */
point.splice(0, 2, 'C')
}
})
return shape
.map(function(point) {
return point.join(' ')
})
.join('')
})
.join('')
}
const root = getGlobal()
export default{
export default {
getImageInWx,
root,
isWeapp: typeof wx !== 'undefined' && !wx.createCanvas && wx.createCanvasContext,
isWeapp:
typeof wx !== 'undefined' && !wx.createCanvas && wx.createCanvasContext,
isWegame: typeof wx !== 'undefined' && wx.createCanvas
}

View File

@ -0,0 +1,469 @@
import a2c from '../render/base/a2c'
import parser from './svg-path-parser.js'
import { sort, sortCurves } from './sort.js'
let pasition = {}
pasition.parser = parser
pasition.lerpCurve = function (pathA, pathB, t) {
return pasition.lerpPoints(pathA[0], pathA[1], pathB[0], pathB[1], t)
.concat(pasition.lerpPoints(pathA[2], pathA[3], pathB[2], pathB[3], t))
.concat(pasition.lerpPoints(pathA[4], pathA[5], pathB[4], pathB[5], t))
.concat(pasition.lerpPoints(pathA[6], pathA[7], pathB[6], pathB[7], t))
}
pasition.lerpPoints = function (x1, y1, x2, y2, t) {
return [x1 + (x2 - x1) * t, y1 + (y2 - y1) * t]
}
pasition.q2b = function (x1, y1, x2, y2, x3, y3) {
return [x1, y1, (x1 + 2 * x2) / 3, (y1 + 2 * y2) / 3, (x3 + 2 * x2 )/ 3, (y3 + 2 * y2) / 3, x3, y3]
}
pasition.path2shapes = function (path) {
//https://developer.mozilla.org/zh-CN/docs/Web/SVG/Tutorial/Paths
//M = moveto
//L = lineto
//H = horizontal lineto
//V = vertical lineto
//C = curveto
//S = smooth curveto
//Q = quadratic Belzier curve
//T = smooth quadratic Belzier curveto
//A = elliptical Arc
//Z = closepath
//以上所有命令均允许小写字母。大写表示绝对定位,小写表示相对定位(从上一个点开始)。
let cmds = pasition.parser(path),
preX = 0,
preY = 0,
j = 0,
len = cmds.length,
shapes = [],
current = null,
closeX,
closeY,
preCX,
preCY,
sLen,
curves,
lastCurve,
tempX,
tempY
for (; j < len; j++) {
let item = cmds[j]
let action = item[0]
let preItem = cmds[j - 1]
switch (action) {
case 'm':
sLen = shapes.length
shapes[sLen] = []
current = shapes[sLen]
preX = preX+item[1]
preY = preY+item[2]
break
case 'M':
sLen = shapes.length
shapes[sLen] = []
current = shapes[sLen]
preX = item[1]
preY = item[2]
break
case 'l':
current.push([preX, preY, preX, preY, preX, preY, preX+item[1],preY+item[2]])
preX += item[1]
preY += item[2]
break
case 'L':
current.push([preX, preY, item[1], item[2], item[1], item[2], item[1], item[2]])
preX = item[1]
preY = item[2]
break
case 'h':
current.push([preX, preY, preX, preY, preX, preY, preX + item[1], preY])
preX += item[1]
break
case 'H':
current.push([preX, preY, item[1], preY, item[1], preY, item[1], preY])
preX = item[1]
break
case 'v':
current.push([preX, preY, preX, preY, preX, preY, preX, preY + item[1]])
preY += item[1]
break
case 'V':
current.push([preX, preY, preX, item[1], preX, item[1], preX, item[1]])
preY = item[1]
break
case 'C':
current.push([preX, preY, item[1], item[2], item[3], item[4], item[5], item[6]])
preX = item[5]
preY = item[6]
break
case 'S':
if(preItem[0] ==='C'||preItem[0] ==='c'){
current.push([preX, preY, preX + preItem[5] - preItem[3], preY + preItem[6] - preItem[4], item[1], item[2], item[3], item[4]])
}else if(preItem[0] ==='S'||preItem[0] ==='s'){
current.push([preX, preY, preX+ preItem[3] - preItem[1] ,preY+ preItem[4] - preItem[2], item[1], item[2], item[3], item[4]])
} else {
current.push([preX, preY, preX, preY, item[1], item[2], item[3], item[4]])
}
preX = item[3]
preY = item[4]
break
case 'c':
current.push([preX, preY, preX + item[1], preY + item[2], preX + item[3], preY + item[4], preX + item[5], preY + item[6]])
preX = preX + item[5]
preY = preY + item[6]
break
case 's':
if(preItem[0] ==='C'||preItem[0] ==='c'){
current.push([preX, preY, preX+ preItem[5] - preItem[3] ,preY+ preItem[6] - preItem[4],preX+ item[1],preY+ item[2], preX+item[3],preY+ item[4]])
}else if(preItem[0] ==='S'||preItem[0] ==='s' ){
current.push([preX, preY, preX+ preItem[3] - preItem[1] ,preY+ preItem[4] - preItem[2],preX+ item[1],preY+ item[2], preX+item[3],preY+ item[4]])
}
preX = preX+item[3]
preY = preY+item[4]
break
case 'a':
curves = a2c(preX, preY, item[1], item[2], item[3], item[4], item[5], preX + item[6], preY + item[7])
curves.push([preX,preY,curves[0], curves[1], curves[2], curves[3], curves[4], curves[5]])
tempX = curves[4]
tempY = curves[5]
for (let i = 6, len = curves.length; i < len; i += 6) {
curves.push([tempX, tempY, curves[i], curves[i + 1], curves[i + 2], curves[i + 3], curves[i + 4], curves[i + 5]])
tempX = curves[i + 4]
tempY = curves[i + 5]
}
preX = preX + item[6]
preY = preY + item[7]
break
case 'A':
curves = a2c(preX, preY, item[1], item[2], item[3], item[4], item[5], item[6], item[7])
curves.push([preX,preY,curves[0], curves[1], curves[2], curves[3], curves[4], curves[5]])
tempX = curves[4]
tempY = curves[5]
for (let i = 6, len = curves.length; i < len; i += 6) {
curves.push([tempX, tempY, curves[i], curves[i + 1], curves[i + 2], curves[i + 3], curves[i + 4], curves[i + 5]])
tempX = curves[i + 4]
tempY = curves[i + 5]
}
preX = lastCurve.x
preY = lastCurve.y
break
case 'Q':
current.push(pasition.q2b(preX,preY, item[1], item[2], item[3], item[4]))
preX = item[3]
preY = item[4]
break
case 'q':
current.push(pasition.q2b(preX,preY,preX+item[1], preY+item[2],item[3]+preX,item[4]+preY))
preX += item[3]
preY += item[4]
break
case 'T':
if(preItem[0] ==='Q'|| preItem[0] ==='q') {
preCX = preX + preItem[3] - preItem[1]
preCY = preY + preItem[4] - preItem[2]
current.push(pasition.q2b(preX, preY, preCX, preCY, item[1], item[2]))
}else if(preItem[0] ==='T'|| preItem[0] ==='t' ) {
current.push(pasition.q2b(preX, preY, preX + preX - preCX, preY + preY - preCY, item[1], item[2]))
preCX = preX + preX - preCX
preCY = preY + preY - preCY
}
preX = item[1]
preY = item[2]
break
case 't':
if(preItem[0] ==='Q'|| preItem[0] ==='q') {
preCX = preX + preItem[3] - preItem[1]
preCY = preY + preItem[4] - preItem[2]
current.push(pasition.q2b(preX, preY, preCX, preCY,preX+ item[1],preY+ item[2]))
}else if(preItem[0] ==='T'|| preItem[0] ==='t' ) {
current.push(pasition.q2b(preX, preY, preX + preX - preCX, preY + preY - preCY, preX+item[1], preY+item[2]))
preCX = preX + preX - preCX
preCY = preY + preY - preCY
}
preX += item[1]
preY += item[2]
break
case 'Z':
closeX = current[0][0]
closeY = current[0][1]
current.push([preX, preY, closeX, closeY, closeX, closeY, closeX, closeY])
break
case 'z':
closeX = current[0][0]
closeY = current[0][1]
current.push([preX, preY, closeX, closeY, closeX, closeY, closeX, closeY])
break
}
}
return shapes
}
pasition._upCurves = function (curves, count) {
let i = 0,
index = 0,
len = curves.length
for (; i < count; i++) {
curves.push(curves[index].slice(0))
index++
if(index > len-1) {
index -= len
}
}
}
function split(x1, y1, x2, y2, x3, y3, x4, y4, t) {
return {
left: _split(x1, y1, x2, y2, x3, y3, x4, y4, t),
right: _split(x4, y4, x3, y3, x2, y2, x1, y1, 1 - t, true)
}
}
function _split(x1, y1, x2, y2, x3, y3, x4, y4, t, reverse) {
let x12 = (x2 - x1) * t + x1
let y12 = (y2 - y1) * t + y1
let x23 = (x3 - x2) * t + x2
let y23 = (y3 - y2) * t + y2
let x34 = (x4 - x3) * t + x3
let y34 = (y4 - y3) * t + y3
let x123 = (x23 - x12) * t + x12
let y123 = (y23 - y12) * t + y12
let x234 = (x34 - x23) * t + x23
let y234 = (y34 - y23) * t + y23
let x1234 = (x234 - x123) * t + x123
let y1234 = (y234 - y123) * t + y123
if(reverse) {
return [x1234, y1234, x123, y123, x12, y12, x1, y1]
}
return [x1, y1, x12, y12, x123, y123, x1234, y1234]
}
pasition._splitCurves = function (curves, count) {
let i = 0,
index = 0
for (; i < count; i++) {
let curve = curves[index]
let cs = split(curve[0],curve[1],curve[2],curve[3],curve[4],curve[5],curve[6],curve[7],0.5)
curves.splice(index,1)
curves.splice(index,0,cs.left,cs.right)
index+=2
if(index >= curves.length-1) {
index = 0
}
}
}
pasition._upShapes = function (shapes, count) {
for (let i = 0; i < count; i++) {
let shape = shapes[shapes.length - 1]
let newShape = []
shape.forEach(function (curve) {
newShape.push(curve.slice(0))
})
shapes.push(newShape)
}
}
pasition._subShapes= function (shapes, count) {
for (let i = 0; i < count; i++) {
let shape = shapes[shapes.length - 1]
let newShape = []
let x = shape[0][0],
y = shape[0][1]
shape.forEach(function () {
newShape.push([x, y, x, y, x, y, x, y])
})
shapes.push(newShape)
}
}
pasition.lerp = function (pathA, pathB, t) {
return pasition._lerp( pasition.path2shapes(pathA), pasition.path2shapes(pathB), t)
}
pasition.MIM_CURVES_COUNT = 100
pasition._preprocessing = function(pathA, pathB) {
let lenA = pathA.length,
lenB = pathB.length,
clonePathA = JSON.parse(JSON.stringify(pathA)),
clonePathB = JSON.parse(JSON.stringify(pathB))
if (lenA > lenB) {
pasition._subShapes(clonePathB, lenA - lenB)
} else if (lenA < lenB) {
pasition._upShapes(clonePathA, lenB - lenA)
}
clonePathA = sort(clonePathA, clonePathB)
clonePathA.forEach(function (curves, index) {
let lenA = curves.length,
lenB = clonePathB[index].length
if (lenA > lenB) {
if (lenA < pasition.MIM_CURVES_COUNT) {
pasition._splitCurves(curves, pasition.MIM_CURVES_COUNT - lenA)
pasition._splitCurves(clonePathB[index], pasition.MIM_CURVES_COUNT - lenB)
} else {
pasition._splitCurves(clonePathB[index], lenA - lenB)
}
} else if (lenA < lenB) {
if (lenB < pasition.MIM_CURVES_COUNT) {
pasition._splitCurves(curves, pasition.MIM_CURVES_COUNT - lenA)
pasition._splitCurves(clonePathB[index], pasition.MIM_CURVES_COUNT - lenB)
} else {
pasition._splitCurves(curves, lenB - lenA)
}
}
})
clonePathA.forEach(function (curves, index) {
clonePathA[index] = sortCurves(curves, clonePathB[index])
})
return [clonePathA, clonePathB]
}
pasition._lerp = function (pathA, pathB, t) {
let shapes = []
pathA.forEach(function (curves, index) {
let newCurves = []
curves.forEach(function (curve, curveIndex) {
newCurves.push(pasition.lerpCurve(curve, pathB[index][curveIndex], t))
})
shapes.push(newCurves)
})
return shapes
}
let lastTime = 0;
const requestAnimationFrame = function(callback) {
let currTime = new Date().getTime()
let timeToCall = Math.max(0, 16 - (currTime - lastTime))
let id = setTimeout(function() { callback(currTime + timeToCall); },
timeToCall)
lastTime = currTime + timeToCall
return id
};
const cancelAnimationFrame = function(id) {
clearTimeout(id)
}
pasition.animate = function (option) {
let pathA = pasition.path2shapes(option.from)
let pathB = pasition.path2shapes(option.to)
let pathArr = pasition._preprocessing(pathA,pathB)
let beginTime = new Date(),
end = option.end || function () {
},
progress = option.progress || function () {
},
begin = option.begin || function () {
},
easing = option.easing || function (v) {
return v
},
tickId = null,
outShape = null,
duration = option.duration
begin(pathA)
let tick = function () {
let dt = new Date() - beginTime
if (dt >= duration) {
outShape = pathB
progress(outShape, 1)
end(outShape)
cancelAnimationFrame(tickId)
return
}
let percent = easing(dt / duration)
outShape = pasition._lerp(pathArr[0], pathArr[1], percent)
progress(outShape, percent)
tickId = requestAnimationFrame(tick)
}
tick()
}
export default pasition

View File

@ -0,0 +1,159 @@
function shapeBox(shape) {
let minX=shape[0][0], minY=shape[0][1], maxX=minX, maxY=minY
shape.forEach(curve=> {
let x1 = curve[0],
x2 = curve[2],
x3 = curve[4],
x4 = curve[6],
y1 = curve[1],
y2 = curve[3],
y3 = curve[5],
y4 = curve[7]
minX = Math.min(minX, x1, x2, x3, x4)
minY = Math.min(minY, y1, y2, y3, y4)
maxX = Math.max(maxX, x1, x2, x3, x4)
maxY = Math.max(maxY, y1, y2, y3, y4)
})
return [minX, minY, maxX, maxY]
}
function boxDistance(boxA, boxB){
return Math.sqrt(Math.pow( boxA[0] - boxB[0],2)+Math.pow(boxA[1]-boxB[1],2))+ Math.sqrt(Math.pow( boxA[2] - boxB[2],2)+Math.pow(boxA[3]-boxB[3],2))
}
function curveDistance(curveA,curveB) {
let x1 = curveA[0],
x2 = curveA[2],
x3 = curveA[4],
x4 = curveA[6],
y1 = curveA[1],
y2 = curveA[3],
y3 = curveA[5],
y4 = curveA[7],
xb1 = curveB[0],
xb2 = curveB[2],
xb3 = curveB[4],
xb4 = curveB[6],
yb1 = curveB[1],
yb2 = curveB[3],
yb3 = curveB[5],
yb4 = curveB[7]
return Math.sqrt(Math.pow(xb1 - x1, 2) + Math.pow(yb1 - y1, 2)) +
Math.sqrt(Math.pow(xb2 - x2, 2) + Math.pow(yb2 - y2, 2)) +
Math.sqrt(Math.pow(xb3 - x3, 2) + Math.pow(yb3 - y3, 2)) +
Math.sqrt(Math.pow(xb4 - x4, 2) + Math.pow(yb4 - y4, 2))
}
function sortCurves(curvesA, curvesB){
let arrList = permuteCurveNum(curvesA.length)
let list = []
arrList.forEach(arr => {
let distance = 0
let i = 0
arr.forEach(index=> {
distance += curveDistance(curvesA[index], curvesB[i++])
})
list.push({index: arr, distance: distance})
})
list.sort(function(a,b){
return a.distance - b.distance
})
let result = []
list[0].index.forEach(index=>{
result.push(curvesA[index])
})
return result
}
function sort(pathA, pathB){
let arrList = permuteNum(pathA.length)
let list = []
arrList.forEach(arr => {
let distance = 0
arr.forEach(index=> {
distance += boxDistance(shapeBox(pathA[index]), shapeBox(pathB[index]))
})
list.push({index: arr, distance: distance})
})
list.sort(function(a,b){
return a.distance - b.distance
})
let result = []
list[0].index.forEach(index=>{
result.push(pathA[index])
})
return result
}
function permuteCurveNum(num) {
let arr = []
for (let i = 0; i < num; i++) {
let indexArr = []
for (let j = 0; j < num; j++) {
let index = j + i
if (index > num - 1)index -= num
indexArr[index] = j
}
arr.push(indexArr)
}
return arr
}
function permuteNum(num) {
let arr = []
for (let i = 0; i < num; i++) {
arr.push(i)
}
return permute(arr)
}
function permute(input) {
var permArr = [],
usedChars = []
function main(input){
var i, ch
for (i = 0; i < input.length; i++) {
ch = input.splice(i, 1)[0]
usedChars.push(ch)
if (input.length == 0) {
permArr.push(usedChars.slice())
}
main(input)
input.splice(i, 0, ch)
usedChars.pop()
}
return permArr
}
return main(input)
}
export {
sort,
sortCurves
}

View File

@ -0,0 +1,57 @@
//https://github.com/jkroso/parse-svg-path/blob/master/index.js
/**
* expected argument lengths
* @type {Object}
*/
var length = { a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0 }
/**
* segment pattern
* @type {RegExp}
*/
var segment = /([astvzqmhlc])([^astvzqmhlc]*)/gi
/**
* parse an svg path data string. Generates an Array
* of commands where each command is an Array of the
* form `[command, arg1, arg2, ...]`
*
* @param {String} path
* @return {Array}
*/
function parse(path) {
var data = []
path.replace(segment, function(_, command, args) {
var type = command.toLowerCase()
args = parseValues(args)
// overloaded moveTo
if (type == 'm' && args.length > 2) {
data.push([command].concat(args.splice(0, 2)))
type = 'l'
command = command == 'm' ? 'l' : 'L'
}
while (true) {
if (args.length == length[type]) {
args.unshift(command)
return data.push(args)
}
if (args.length < length[type]) throw new Error('malformed path data')
data.push([command].concat(args.splice(0, length[type])))
}
})
return data
}
var number = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi
function parseValues(args) {
var numbers = args.match(number)
return numbers ? numbers.map(Number) : []
}
export default parse

View File

@ -1,12 +1,12 @@
import option from "./stage-propagation-tag"
import option from './stage-propagation-tag'
class EventDispatcher {
constructor () {
constructor() {
this._listeners = null
this._captureListeners = null
}
addEventListener (type, listener, useCapture) {
addEventListener(type, listener, useCapture) {
var listeners
if (useCapture) {
listeners = this._captureListeners = this._captureListeners || {}
@ -14,17 +14,27 @@ class EventDispatcher {
listeners = this._listeners = this._listeners || {}
}
var arr = listeners[type]
if (arr) { this.removeEventListener(type, listener, useCapture) }
if (arr) {
this.removeEventListener(type, listener, useCapture)
}
arr = listeners[type] // remove may have deleted the array
if (!arr) { listeners[type] = [listener] } else { arr.push(listener) }
if (!arr) {
listeners[type] = [listener]
} else {
arr.push(listener)
}
return listener
}
removeEventListener (type, listener, useCapture) {
removeEventListener(type, listener, useCapture) {
var listeners = useCapture ? this._captureListeners : this._listeners
if (!listeners) { return }
if (!listeners) {
return
}
var arr = listeners[type]
if (!arr) { return }
if (!arr) {
return
}
arr.every((item, index) => {
if (item === listener) {
@ -35,46 +45,51 @@ class EventDispatcher {
})
}
on (type, listener, useCapture) {
on(type, listener, useCapture) {
this.addEventListener(type, listener, useCapture)
}
off (type, listener, useCapture) {
off(type, listener, useCapture) {
this.removeEventListener(type, listener, useCapture)
}
dispatchEvent (evt) {
option.stagePropagationStopped[evt.type] = false
dispatchEvent(evt) {
option.stagePropagationStopped[evt.type] = false
var top = this, list = [top]
while (top.parent) { list.push(top = top.parent) }
var i, l = list.length
var top = this,
list = [top]
while (top.parent) {
list.push((top = top.parent))
}
var i,
l = list.length
// capture & atTarget
for (i = l - 1; i >= 0 && !evt.propagationStopped; i--) {
list[i]._dispatchEvent(evt, 0)
}
// bubbling
for (i = 0; i < l && !evt.propagationStopped; i++) {
list[i]._dispatchEvent(evt, 1)
}
// capture & atTarget
for (i = l - 1; i >= 0 && !evt.propagationStopped; i--) {
list[i]._dispatchEvent(evt, 0)
}
// bubbling
for (i = 0; i < l && !evt.propagationStopped; i++) {
list[i]._dispatchEvent(evt, 1)
}
}
_dispatchEvent (evt, type) {
_dispatchEvent(evt, type) {
evt.target = this
if (this._captureListeners && type === 0) {
let cls = this._captureListeners[evt.type]
cls && cls.forEach(fn => {
fn.call(this, evt)
})
cls &&
cls.forEach(fn => {
fn.call(this, evt)
})
}
if (this._listeners && type === 1) {
let ls = this._listeners[evt.type]
ls && ls.forEach(fn => {
fn.call(this, evt)
})
ls &&
ls.forEach(fn => {
fn.call(this, evt)
})
}
}
}

View File

@ -1,19 +1,19 @@
import option from "./stage-propagation-tag"
import option from './stage-propagation-tag'
class Event {
constructor () {
constructor() {
this.propagationStopped = false
this.stageX = null
this.stageY = null
this.pureEvent = null
}
stopPropagation () {
stopPropagation() {
option.stagePropagationStopped[this.type] = true
this.propagationStopped = true
}
preventDefault () {
preventDefault() {
this.pureEvent.preventDefault()
}
}

View File

@ -1,9 +1,8 @@
const DEG_TO_RAD = 0.017453292519943295
const PI_2 = Math.PI * 2
class Matrix2D {
constructor (a, b, c, d, tx, ty) {
constructor(a, b, c, d, tx, ty) {
this.a = a == null ? 1 : a
this.b = b || 0
this.c = c || 0
@ -13,13 +12,23 @@ class Matrix2D {
return this
}
identity () {
identity() {
this.a = this.d = 1
this.b = this.c = this.tx = this.ty = 0
return this
}
appendTransform (x, y, scaleX, scaleY, rotation, skewX, skewY, originX, originY) {
appendTransform(
x,
y,
scaleX,
scaleY,
rotation,
skewX,
skewY,
originX,
originY
) {
if (rotation % 360) {
var r = rotation * DEG_TO_RAD
var cos = Math.cos(r)
@ -31,7 +40,14 @@ class Matrix2D {
if (skewX || skewY) {
skewX *= DEG_TO_RAD
skewY *= DEG_TO_RAD
this.append(Math.cos(skewY), Math.sin(skewY), -Math.sin(skewX), Math.cos(skewX), x, y)
this.append(
Math.cos(skewY),
Math.sin(skewY),
-Math.sin(skewX),
Math.cos(skewX),
x,
y
)
this.append(cos * scaleX, sin * scaleX, -sin * scaleY, cos * scaleY, 0, 0)
} else {
this.append(cos * scaleX, sin * scaleX, -sin * scaleY, cos * scaleY, x, y)
@ -43,7 +59,7 @@ class Matrix2D {
return this
}
append (a, b, c, d, tx, ty) {
append(a, b, c, d, tx, ty) {
var a1 = this.a
var b1 = this.b
var c1 = this.c
@ -57,7 +73,7 @@ class Matrix2D {
return this
}
initialize (a, b, c, d, tx, ty) {
initialize(a, b, c, d, tx, ty) {
this.a = a
this.b = b
this.c = c
@ -67,7 +83,7 @@ class Matrix2D {
return this
}
setValues (a, b, c, d, tx, ty) {
setValues(a, b, c, d, tx, ty) {
this.a = a == null ? 1 : a
this.b = b || 0
this.c = c || 0
@ -77,7 +93,7 @@ class Matrix2D {
return this
}
invert () {
invert() {
let a1 = this.a
let b1 = this.b
let c1 = this.c
@ -92,45 +108,47 @@ class Matrix2D {
this.tx = (c1 * this.ty - d1 * tx1) / n
this.ty = -(a1 * this.ty - b1 * tx1) / n
return this
};
}
copy (matrix) {
return this.setValues(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty)
copy(matrix) {
return this.setValues(
matrix.a,
matrix.b,
matrix.c,
matrix.d,
matrix.tx,
matrix.ty
)
}
}
Matrix2D.decompose = function(a, b, c, d, tx, ty, transform){
const skewX = -Math.atan2(-c, d);
const skewY = Math.atan2(b, a);
Matrix2D.decompose = function(a, b, c, d, tx, ty, transform) {
const skewX = -Math.atan2(-c, d)
const skewY = Math.atan2(b, a)
const delta = Math.abs(skewX + skewY);
const delta = Math.abs(skewX + skewY)
if (delta < 0.00001 || Math.abs(PI_2 - delta) < 0.00001)
{
transform.rotation = skewY;
if (delta < 0.00001 || Math.abs(PI_2 - delta) < 0.00001) {
transform.rotation = skewY
if (a < 0 && d >= 0)
{
transform.rotation += (transform.rotation <= 0) ? Math.PI : -Math.PI;
}
if (a < 0 && d >= 0) {
transform.rotation += transform.rotation <= 0 ? Math.PI : -Math.PI
}
transform.skewX = transform.skewY = 0;
}
else
{
transform.rotation = 0;
transform.skewX = skewX;
transform.skewY = skewY;
transform.skewX = transform.skewY = 0
} else {
transform.rotation = 0
transform.skewX = skewX
transform.skewY = skewY
}
// next set scale
transform.scaleX = Math.sqrt((a * a) + (b * b));
transform.scaleY = Math.sqrt((c * c) + (d * d));
transform.scaleX = Math.sqrt(a * a + b * b)
transform.scaleY = Math.sqrt(c * c + d * d)
// next set position
transform.x = tx;
transform.y = ty;
transform.x = tx
transform.y = ty
}
export default Matrix2D

View File

@ -4,14 +4,14 @@
* @type {Object}
*/
var length = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0}
var length = { a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0 }
/**
* segment pattern
* @type {RegExp}
*/
var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig
var segment = /([astvzqmhlc])([^astvzqmhlc]*)/gi
/**
* parse an svg path data string. Generates an Array
@ -22,9 +22,9 @@ var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig
* @return {Array}
*/
function parse (path) {
function parse(path) {
var data = []
path.replace(segment, function (_, command, args) {
path.replace(segment, function(_, command, args) {
var type = command.toLowerCase()
args = parseValues(args)
@ -47,9 +47,9 @@ function parse (path) {
return data
}
var number = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig
var number = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi
function parseValues (args) {
function parseValues(args) {
var numbers = args.match(number)
return numbers ? numbers.map(Number) : []
}

View File

@ -1,3 +1,3 @@
export default {
stagePropagationStopped:{}
}
stagePropagationStopped: {}
}

View File

@ -2,7 +2,7 @@ var UID = {}
UID._nextID = 0
UID.get = function () {
UID.get = function() {
return UID._nextID++
}

View File

@ -2,7 +2,7 @@ import DisplayObject from './display-object.js'
import util from '../../common/util'
class Bitmap extends DisplayObject {
constructor (img, onLoad) {
constructor(img, onLoad) {
super()
if (typeof img === 'string') {
if (Bitmap.cache[img]) {
@ -19,7 +19,7 @@ class Bitmap extends DisplayObject {
}
onLoad && onLoad.call(this)
} else if (util.isWeapp) {
util.getImageInWx(img, (result) => {
util.getImageInWx(img, result => {
this.img = result.img
if (!this.rect) {
this.rect = [0, 0, result.width, result.height]
@ -31,9 +31,8 @@ class Bitmap extends DisplayObject {
})
} else {
this.img = util.isWegame ? wx.createImage() : new window.Image()
this.img.onload = () => {
if (!this.rect) {
this.rect = [0, 0, this.img.width, this.img.height]
}
@ -53,9 +52,11 @@ class Bitmap extends DisplayObject {
}
}
clone () {
clone() {
// 复制完img宽度0所以直接传字符串
const bitmap = new Bitmap(typeof this.img === 'string' ? this.img : this.img.src)
const bitmap = new Bitmap(
typeof this.img === 'string' ? this.img : this.img.src
)
bitmap.x = this.x
bitmap.y = this.y
bitmap.scaleX = this.scaleX
@ -73,8 +74,6 @@ class Bitmap extends DisplayObject {
}
}
Bitmap.cache = {
}
Bitmap.cache = {}
export default Bitmap

View File

@ -3,7 +3,7 @@ import EventDispatcher from '../base/event-dispatcher'
import UID from '../base/uid.js'
class DisplayObject extends EventDispatcher {
constructor () {
constructor() {
super()
this.alpha = this.complexAlpha = this.scaleX = this.scaleY = 1
this.x = this.y = this.rotation = this.skewX = this.skewY = this.originX = this.originY = 0
@ -25,22 +25,30 @@ class DisplayObject extends EventDispatcher {
Object.defineProperties(this, {
stage: { get: this._getStage },
scale: {
get: function() { return this.scaleX; },
set: function(scale) { this.scaleX = this.scaleY = scale; }
get: function() {
return this.scaleX
},
set: function(scale) {
this.scaleX = this.scaleY = scale
}
}
});
})
} catch (e) {}
this.hitBox = null
}
isVisible () {
return this.visible && this.alpha > 0 && this.scaleX !== 0 && this.scaleY !== 0
isVisible() {
return (
this.visible && this.alpha > 0 && this.scaleX !== 0 && this.scaleY !== 0
)
}
initAABB () {
if ((this.width === undefined || this.height === undefined) && !this.hitBox) {
initAABB() {
if (
(this.width === undefined || this.height === undefined) &&
!this.hitBox
) {
return
}
@ -52,7 +60,7 @@ class DisplayObject extends EventDispatcher {
tx = mtx.tx,
ty = mtx.ty
if(this.hitBox){
if (this.hitBox) {
width = this.hitBox[2]
height = this.hitBox[3]
tx = this.hitBox[0] * mtx.a + this.hitBox[1] * mtx.c + tx
@ -99,51 +107,56 @@ class DisplayObject extends EventDispatcher {
maxY = y
}
this.AABB = [minX, minY, maxX - minX, maxY - minY]
this.rectPoints = [{
x: tx,
y: ty
}, {
x: xA + tx,
y: xB + ty
}, {
x: xA + yC + tx,
y: xB + yD + ty
}, {
x: yC + tx,
y: yD + ty
}]
this.rectPoints = [
{
x: tx,
y: ty
},
{
x: xA + tx,
y: xB + ty
},
{
x: xA + yC + tx,
y: xB + yD + ty
},
{
x: yC + tx,
y: yD + ty
}
]
}
destroy () {
destroy() {
this.parent.remove(this)
}
hover (over, out, move) {
hover(over, out, move) {
this.on('mouseover', over)
this.on('mouseout', out)
move && this.on('mousemove', move)
}
// https://developer.mozilla.org/zh-CN/docs/Web/API/CanvasRenderingContext2D/clip
clip (graphics, notClipRuleNonzero) {
clip(graphics, notClipRuleNonzero) {
this.clipGraphics = graphics
this.clipRuleNonzero = !notClipRuleNonzero
}
unclip () {
unclip() {
this.clipGraphics = null
}
absClip (graphics, notClipRuleNonzero) {
absClip(graphics, notClipRuleNonzero) {
this.absClipGraphics = graphics
this.absClipRuleNonzero = !notClipRuleNonzero
}
unAbsClip () {
unAbsClip() {
this.absClipGraphics = null
}
cache (x, y, width, height, scale, cacheUpdating) {
cache(x, y, width, height, scale, cacheUpdating) {
this._cacheData = {
x: x || 0,
y: y || 0,
@ -168,47 +181,55 @@ class DisplayObject extends EventDispatcher {
this._readyToCache = true
}
uncache () {
uncache() {
this.cacheCanvas = null
}
filter(filterName, filterBox) {
filterBox = Object.assign({}, {
x: 0,
y: 0,
width: this.width,
height: this.height
}, filterBox)
filterBox = Object.assign(
{},
{
x: 0,
y: 0,
width: this.width,
height: this.height
},
filterBox
)
this.cache(filterBox.x, filterBox.y, filterBox.width, filterBox.height)
this._readyToFilter = true
this._filterName = filterName
}
setTransform (x, y, scaleX, scaleY, rotation, skewX, skewY, originX, originY) {
this.x = x || 0;
this.y = y || 0;
this.scaleX = scaleX == null ? 1 : scaleX;
this.scaleY = scaleY == null ? 1 : scaleY;
this.rotation = rotation || 0;
this.skewX = skewX || 0;
this.skewY = skewY || 0;
this.originX = originX || 0;
this.originY = originY || 0;
setTransform(x, y, scaleX, scaleY, rotation, skewX, skewY, originX, originY) {
this.x = x || 0
this.y = y || 0
this.scaleX = scaleX == null ? 1 : scaleX
this.scaleY = scaleY == null ? 1 : scaleY
this.rotation = rotation || 0
this.skewX = skewX || 0
this.skewY = skewY || 0
this.originX = originX || 0
this.originY = originY || 0
}
setMatrix(a, b, c, d, tx, ty){
setMatrix(a, b, c, d, tx, ty) {
Matrix2D.decompose(a, b, c, d, tx, ty, this)
}
unfilter () {
unfilter() {
this.uncache()
}
_getStage () {
var o = this
while (o.parent) { o = o.parent }
if (o.___instanceof === 'Stage') { return o; }
return null
_getStage() {
var o = this
while (o.parent) {
o = o.parent
}
if (o.___instanceof === 'Stage') {
return o
}
return null
}
}

View File

@ -16,16 +16,16 @@ Options
*/
class Button extends Group {
constructor (option) {
constructor(option) {
super()
this.width = option.width
this.height = option.height
this.x = option.x
this.y = option.y
let textHeight = 0
var textGroup
if (option.text) {
textGroup = new Group()
this.text = new Text(option.text, {
@ -35,7 +35,9 @@ class Button extends Group {
const textWidth = this.text.getWidth()
if (textWidth > option.width) {
const step = Math.round(option.text.length * (option.width) / textWidth / 2)
const step = Math.round(
(option.text.length * option.width) / textWidth / 2
)
const textList = this.stringSplit(option.text, step)
const lineHeight = option.lineHeight || 12
@ -47,17 +49,31 @@ class Button extends Group {
color: option.color
})
this.text.x = option.width / 2 - this.text.getWidth() / 2 * this.text.scaleX + (option.textX || 0)
this.text.y = Math.max(textHeight, option.height) / 2 - 10 + 5 * this.text.scaleY + (option.textY || 0) + index * 12 - textHeight / 2 + lineHeight / 2
this.text.x =
option.width / 2 -
(this.text.getWidth() / 2) * this.text.scaleX +
(option.textX || 0)
this.text.y =
Math.max(textHeight, option.height) / 2 -
10 +
5 * this.text.scaleY +
(option.textY || 0) +
index * 12 -
textHeight / 2 +
lineHeight / 2
textGroup.add(this.text)
})
} else {
this.text.x = option.width / 2 - this.text.getWidth() / 2 * this.text.scaleX + (option.textX || 0)
this.text.y = option.height / 2 - 10 + 5 * this.text.scaleY + (option.textY || 0)
this.text.x =
option.width / 2 -
(this.text.getWidth() / 2) * this.text.scaleX +
(option.textX || 0)
this.text.y =
option.height / 2 - 10 + 5 * this.text.scaleY + (option.textY || 0)
textGroup.add(this.text)
}
}
if (option.bgImage) {
var ratio = SCALE_RATIO
let bitmap = new Bitmap(option.bgImage[0])
@ -69,13 +85,18 @@ class Button extends Group {
bitmap.y = (this.height - bitmap.height) / 2
this.add(bitmap)
} else if (option.bgColor || option.borderColor) {
this.roundedRect = new RoundedRect(option.width, option.autoHeight ? Math.max(textHeight, option.height) : option.height, option.borderRadius, {
strokeStyle: option.borderColor || 'black',
fillStyle: option.bgColor || '#F5F5F5'
})
this.roundedRect = new RoundedRect(
option.width,
option.autoHeight ? Math.max(textHeight, option.height) : option.height,
option.borderRadius,
{
strokeStyle: option.borderColor || 'black',
fillStyle: option.bgColor || '#F5F5F5'
}
)
this.add(this.roundedRect)
}
if (option.image) {
var ratio = SCALE_RATIO
let bitmap = new Bitmap(option.image[0])
@ -87,22 +108,29 @@ class Button extends Group {
bitmap.y = (this.height - bitmap.height) / 2
this.add(bitmap)
}
if (textGroup) {
this.add(textGroup)
}
}
stringSplit (str, len) {
stringSplit(str, len) {
let arr = [],
offset = 0,
char_length = 0
for (let i = 0; i < str.length; i++) {
let son_str = str.charAt(i)
encodeURI(son_str).length > 2 ? char_length += 1 : char_length += 0.5
encodeURI(son_str).length > 2 ? (char_length += 1) : (char_length += 0.5)
if (char_length >= len || (char_length < len && i === str.length - 1)) {
let sub_len = char_length == len ? i + 1 : i
arr.push(str.substr(offset, sub_len - offset + ((char_length < len && i === str.length - 1) ? 1 : 0)))
arr.push(
str.substr(
offset,
sub_len -
offset +
(char_length < len && i === str.length - 1 ? 1 : 0)
)
)
offset = i + 1
char_length = 0
}

View File

@ -11,159 +11,166 @@ const assMap = {
}
class Graphics extends DisplayObject {
constructor () {
constructor() {
super()
this.cmds = []
this.currentGradient = null
}
clearRect () {
clearRect() {
this.cmds.push(['clearRect', arguments])
return this
}
rect () {
rect() {
this.cmds.push(['rect', arguments])
return this
}
clear () {
clear() {
this.cmds.length = 0
return this
}
setLineDash () {
setLineDash() {
this.cmds.push(['setLineDash', arguments])
return this
}
strokeRect () {
strokeRect() {
this.cmds.push(['strokeRect', arguments])
return this
}
fillRect () {
fillRect() {
this.cmds.push(['fillRect', arguments])
return this
}
beginPath () {
beginPath() {
this.cmds.push(['beginPath', arguments])
return this
}
arc () {
arc() {
this.cmds.push(['arc', arguments])
return this
}
closePath () {
closePath() {
this.cmds.push(['closePath', arguments])
return this
}
fillStyle () {
fillStyle() {
this.cmds.push(['fillStyle', arguments])
return this
}
fill () {
fill() {
this.cmds.push(['fill', arguments])
return this
}
strokeStyle () {
strokeStyle() {
this.cmds.push(['strokeStyle', arguments])
return this
}
lineWidth () {
lineWidth() {
this.cmds.push(['lineWidth', arguments])
return this
}
lineCap () {
lineCap() {
this.cmds.push(['lineCap', arguments])
return this
}
lineDashOffset () {
lineDashOffset() {
this.cmds.push(['lineDashOffset', arguments])
return this
}
lineJoin () {
lineJoin() {
this.cmds.push(['lineJoin', arguments])
return this
}
miterLimit () {
miterLimit() {
this.cmds.push(['miterLimit', arguments])
return this
}
stroke () {
stroke() {
this.cmds.push(['stroke', arguments])
return this
}
moveTo () {
moveTo() {
this.cmds.push(['moveTo', arguments])
return this
}
lineTo () {
lineTo() {
this.cmds.push(['lineTo', arguments])
return this
}
bezierCurveTo () {
bezierCurveTo() {
this.cmds.push(['bezierCurveTo', arguments])
return this
}
quadraticCurveTo () {
quadraticCurveTo() {
this.cmds.push(['quadraticCurveTo', arguments])
return this
}
createRadialGradient () {
createRadialGradient() {
this.cmds.push(['createRadialGradient', arguments])
return this
}
createLinearGradient () {
createLinearGradient() {
this.cmds.push(['createLinearGradient', arguments])
return this
}
addColorStop () {
addColorStop() {
this.cmds.push(['addColorStop', arguments])
return this
}
fillGradient () {
fillGradient() {
this.cmds.push(['fillGradient'])
return this
}
arcTo () {
arcTo() {
this.cmds.push(['arcTo', arguments])
return this
}
render (ctx) {
render(ctx) {
this.cmds.forEach(cmd => {
const methodName = cmd[0]
if (assMap[methodName]) {
ctx[methodName] = cmd[1][0]
} else if (methodName === 'addColorStop') {
this.currentGradient && this.currentGradient.addColorStop(cmd[1][0], cmd[1][1])
this.currentGradient &&
this.currentGradient.addColorStop(cmd[1][0], cmd[1][1])
} else if (methodName === 'fillGradient') {
ctx.fillStyle = this.currentGradient
} else {
let result = ctx[methodName].apply(ctx, Array.prototype.slice.call(cmd[1]))
if (methodName === 'createRadialGradient' || methodName === 'createLinearGradient') {
let result = ctx[methodName].apply(
ctx,
Array.prototype.slice.call(cmd[1])
)
if (
methodName === 'createRadialGradient' ||
methodName === 'createLinearGradient'
) {
this.currentGradient = result
}
}

View File

@ -1,18 +1,18 @@
import DisplayObject from './display-object.js'
class Group extends DisplayObject {
constructor (data) {
constructor(data) {
super(data)
this.children = []
}
add (child) {
add(child) {
const len = arguments.length
for (let i = 0; i < len; i++) {
const c = arguments[i]
const parent = c.parent
if(parent){
if (parent) {
parent.removeChildAt(parent.children.indexOf(c))
}
this.children.push(c)
@ -20,26 +20,28 @@ class Group extends DisplayObject {
}
}
addChildAt (child, index) {
addChildAt(child, index) {
var par = child.parent
par && par.removeChildAt(par.children.indexOf(child))
child.parent = this
this.children.splice(index, 0, child)
}
removeChildAt (index) {
removeChildAt(index) {
var child = this.children[index]
if (child) { child.parent = null }
if (child) {
child.parent = null
}
this.children.splice(index, 1)
}
replace (current, pre) {
replace(current, pre) {
const index = pre.parent.children.indexOf(pre)
this.removeChildAt(index)
this.addChildAt(current, index)
}
remove (child) {
remove(child) {
const len = arguments.length
let cLen = this.children.length
@ -55,14 +57,14 @@ class Group extends DisplayObject {
}
}
empty () {
empty() {
this.children.forEach(child => {
child.parent = null
})
this.children.length = 0
}
destroy () {
destroy() {
this.empty()
// Stage does not have a parent
this.parent && super.destroy()

View File

@ -1,20 +1,23 @@
import Shape from './shape'
class ArrowPath extends Shape {
constructor (path, option) {
constructor(path, option) {
super()
this.path = path
this.option = Object.assign({
strokeStyle: 'black',
lineWidth: 1,
headSize: 10
}, option)
this.option = Object.assign(
{
strokeStyle: 'black',
lineWidth: 1,
headSize: 10
},
option
)
}
draw () {
draw() {
const path = this.path
const len = path.length
if (len === 2) {
this.drawArrow(path[0].x, path[0].y, path[1].x, path[1].y, 30)
@ -23,16 +26,22 @@ class ArrowPath extends Shape {
for (let i = 1; i < len - 1; i++) {
this.lineTo(path[i].x, path[i].y)
}
this.drawArrow(path[len - 2].x, path[len - 2].y, path[len - 1].x, path[len - 1].y, 30)
this.drawArrow(
path[len - 2].x,
path[len - 2].y,
path[len - 1].x,
path[len - 1].y,
30
)
}
//this.stroke()
}
drawArrow (fromX, fromY, toX, toY, theta) {
let angle = Math.atan2(fromY - toY, fromX - toX) * 180 / Math.PI,
angle1 = (angle + theta) * Math.PI / 180,
angle2 = (angle - theta) * Math.PI / 180,
drawArrow(fromX, fromY, toX, toY, theta) {
let angle = (Math.atan2(fromY - toY, fromX - toX) * 180) / Math.PI,
angle1 = ((angle + theta) * Math.PI) / 180,
angle2 = ((angle - theta) * Math.PI) / 180,
hs = this.option.headSize,
topX = hs * Math.cos(angle1),
topY = hs * Math.sin(angle1),

View File

@ -1,7 +1,7 @@
import Shape from './shape'
class Circle extends Shape {
constructor (r, option) {
constructor(r, option) {
super()
this.option = option || {}
this.r = r
@ -9,11 +9,8 @@ class Circle extends Shape {
this._dp = Math.PI * 2
}
draw () {
draw() {
this.arc(0, 0, this.r, 0, this._dp, false)
}
}

View File

@ -1,15 +1,14 @@
import Shape from './shape'
class Ellipse extends Shape {
constructor (width, height, option) {
constructor(width, height, option) {
super()
this.option = option || {}
this.width = width
this.height = height
}
draw () {
draw() {
const w = this.width
const h = this.height
const k = 0.5522848
@ -25,7 +24,6 @@ class Ellipse extends Shape {
this.bezierCurveTo(xm + ox, 0, xe, ym - oy, xe, ym)
this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye)
this.bezierCurveTo(xm - ox, ye, 0, ym + oy, 0, ym)
}
}

View File

@ -1,7 +1,7 @@
import Shape from './shape'
class EquilateralPolygon extends Shape {
constructor (num, r, options) {
constructor(num, r, options) {
super()
this.num = num
@ -12,46 +12,44 @@ class EquilateralPolygon extends Shape {
this.initVertex()
}
initVertex () {
initVertex() {
this.vertex.length = []
const num = this.num
const r = this.r
let i, startX, startY, newX, newY
if (num % 2 === 0) {
startX = r * Math.cos(2 * Math.PI * 0 / num)
startY = r * Math.sin(2 * Math.PI * 0 / num)
startX = r * Math.cos((2 * Math.PI * 0) / num)
startY = r * Math.sin((2 * Math.PI * 0) / num)
this.vertex.push([startX, startY])
for (i = 1; i < num; i++) {
newX = r * Math.cos(2 * Math.PI * i / num)
newY = r * Math.sin(2 * Math.PI * i / num)
newX = r * Math.cos((2 * Math.PI * i) / num)
newY = r * Math.sin((2 * Math.PI * i) / num)
this.vertex.push([newX, newY])
}
} else {
startX = r * Math.cos(2 * Math.PI * 0 / num - Math.PI / 2)
startY = r * Math.sin(2 * Math.PI * 0 / num - Math.PI / 2)
startX = r * Math.cos((2 * Math.PI * 0) / num - Math.PI / 2)
startY = r * Math.sin((2 * Math.PI * 0) / num - Math.PI / 2)
this.vertex.push([startX, startY])
for (i = 1; i < num; i++) {
newX = r * Math.cos(2 * Math.PI * i / num - Math.PI / 2)
newY = r * Math.sin(2 * Math.PI * i / num - Math.PI / 2)
newX = r * Math.cos((2 * Math.PI * i) / num - Math.PI / 2)
newY = r * Math.sin((2 * Math.PI * i) / num - Math.PI / 2)
this.vertex.push([newX, newY])
}
}
}
draw () {
draw() {
this.moveTo(this.vertex[0][0], this.vertex[0][1])
for (let i = 1, len = this.vertex.length; i < len; i++) {
this.lineTo(this.vertex[i][0], this.vertex[i][1])
}
this.closePath()
}
}

View File

@ -1,7 +1,7 @@
import Shape from './shape'
class Line extends Shape {
constructor (x1,y1,x2,y2, option) {
constructor(x1, y1, x2, y2, option) {
super()
this.option = option || {}
this.x1 = x1
@ -10,11 +10,9 @@ class Line extends Shape {
this.y2 = y2
}
draw () {
this.moveTo(this.x1,this.y1)
this.lineTo(this.x2,this.y2)
draw() {
this.moveTo(this.x1, this.y1)
this.lineTo(this.x2, this.y2)
}
}

View File

@ -7,9 +7,12 @@ class Path extends Shape {
super()
this.d = d
option = Object.assign({
lineWidth: 1
}, option)
option = Object.assign(
{
lineWidth: 1
},
option
)
this.option = option
}
@ -28,9 +31,7 @@ class Path extends Shape {
// A = elliptical Arc 暂时未实现,用贝塞尔拟合椭圆
// Z = closepath
// 以上所有命令均允许小写字母。大写表示绝对定位,小写表示相对定位(从上一个点开始)。
let preX,
preY,
curves
let preX, preY, curves
// 参考我的 pasition https://github.com/AlloyTeam/pasition/blob/master/src/index.js
for (let j = 0, cmdLen = cmds.length; j < cmdLen; j++) {
@ -63,11 +64,24 @@ class Path extends Shape {
this.bezierCurveTo(item[1], item[2], item[3], item[4], preX, preY)
break
case 'S':
if (preItem[0] === 'C' || preItem[0] === 'c') {
this.bezierCurveTo(preX + preItem[5] - preItem[3], preY + preItem[6] - preItem[4], item[1], item[2], item[3], item[4])
if (preItem[0] === 'C' || preItem[0] === 'c') {
this.bezierCurveTo(
preX + preItem[5] - preItem[3],
preY + preItem[6] - preItem[4],
item[1],
item[2],
item[3],
item[4]
)
} else if (preItem[0] === 'S' || preItem[0] === 's') {
this.bezierCurveTo(preX + preItem[3] - preItem[1], preY + preItem[4] - preItem[2], item[1], item[2], item[3], item[4])
this.bezierCurveTo(
preX + preItem[3] - preItem[1],
preY + preItem[4] - preItem[2],
item[1],
item[2],
item[3],
item[4]
)
} else {
this.bezierCurveTo(preX, preY, item[1], item[2], item[3], item[4])
}
@ -100,23 +114,48 @@ class Path extends Shape {
this.lineTo(preX, preY)
break
case 'c':
this.bezierCurveTo(preX + item[1], preY + item[2], preX + item[3], preY + item[4], preX + item[5], preY + item[6])
this.bezierCurveTo(
preX + item[1],
preY + item[2],
preX + item[3],
preY + item[4],
preX + item[5],
preY + item[6]
)
preX = preX + item[5]
preY = preY + item[6]
break
case 's':
if (preItem[0] === 'C' || preItem[0] === 'c') {
this.bezierCurveTo(preX + preItem[5] - preItem[3], preY + preItem[6] - preItem[4], preX + item[1], preY + item[2], preX + item[3], preY + item[4])
this.bezierCurveTo(
preX + preItem[5] - preItem[3],
preY + preItem[6] - preItem[4],
preX + item[1],
preY + item[2],
preX + item[3],
preY + item[4]
)
} else if (preItem[0] === 'S' || preItem[0] === 's') {
this.bezierCurveTo(preX + preItem[3] - preItem[1], preY + preItem[4] - preItem[2], preX + item[1], preY + item[2], preX + item[3], preY + item[4])
this.bezierCurveTo(
preX + preItem[3] - preItem[1],
preY + preItem[4] - preItem[2],
preX + item[1],
preY + item[2],
preX + item[3],
preY + item[4]
)
}
preX += item[3]
preY += item[4]
break
case 'q':
this.quadraticCurveTo(preX + item[1], preY + item[2], item[3] + preX, item[4] + preY)
this.quadraticCurveTo(
preX + item[1],
preY + item[2],
item[3] + preX,
item[4] + preY
)
preX += item[3]
preY += item[4]
break
@ -128,14 +167,37 @@ class Path extends Shape {
break
case 'a':
curves = a2c(preX, preY, item[1], item[2], item[3], item[4], item[5], preX + item[6], preY + item[7])
curves = a2c(
preX,
preY,
item[1],
item[2],
item[3],
item[4],
item[5],
preX + item[6],
preY + item[7]
)
//不能 moveTo ,会导致 closePath 重新设置起点
// this.moveTo(preX, preY)
this.bezierCurveTo(curves[0], curves[1], curves[2], curves[3], curves[4], curves[5])
this.bezierCurveTo(
curves[0],
curves[1],
curves[2],
curves[3],
curves[4],
curves[5]
)
for (let i = 6, len = curves.length; i < len; i += 6) {
this.bezierCurveTo(curves[i], curves[i + 1], curves[i + 2], curves[i + 3], curves[i + 4], curves[i + 5])
this.bezierCurveTo(
curves[i],
curves[i + 1],
curves[i + 2],
curves[i + 3],
curves[i + 4],
curves[i + 5]
)
}
preX = preX + item[6]
preY = preY + item[7]
@ -143,13 +205,36 @@ class Path extends Shape {
break
case 'A':
curves = a2c(preX, preY, item[1], item[2], item[3], item[4], item[5], item[6], item[7])
curves = a2c(
preX,
preY,
item[1],
item[2],
item[3],
item[4],
item[5],
item[6],
item[7]
)
//this.moveTo(preX, preY)
this.bezierCurveTo(curves[0], curves[1], curves[2], curves[3], curves[4], curves[5])
this.bezierCurveTo(
curves[0],
curves[1],
curves[2],
curves[3],
curves[4],
curves[5]
)
for (let i = 6, len = curves.length; i < len; i += 6) {
this.bezierCurveTo(curves[i], curves[i + 1], curves[i + 2], curves[i + 3], curves[i + 4], curves[i + 5])
this.bezierCurveTo(
curves[i],
curves[i + 1],
curves[i + 2],
curves[i + 3],
curves[i + 4],
curves[i + 5]
)
}
preX = item[6]
@ -158,13 +243,19 @@ class Path extends Shape {
break
case 'T':
if (preItem[0] === 'Q' || preItem[0] === 'q') {
preCX = preX + preItem[3] - preItem[1]
preCY = preY + preItem[4] - preItem[2]
this.quadraticCurveTo(preX, preY, preCX, preCY, item[1], item[2])
} else if (preItem[0] === 'T' || preItem[0] === 't') {
this.quadraticCurveTo(preX, preY, preX + preX - preCX, preY + preY - preCY, item[1], item[2])
this.quadraticCurveTo(
preX,
preY,
preX + preX - preCX,
preY + preY - preCY,
item[1],
item[2]
)
preCX = preX + preX - preCX
preCY = preY + preY - preCY
}
@ -177,9 +268,23 @@ class Path extends Shape {
if (preItem[0] === 'Q' || preItem[0] === 'q') {
preCX = preX + preItem[3] - preItem[1]
preCY = preY + preItem[4] - preItem[2]
this.quadraticCurveTo(preX, preY, preCX, preCY, preX + item[1], preY + item[2])
this.quadraticCurveTo(
preX,
preY,
preCX,
preCY,
preX + item[1],
preY + item[2]
)
} else if (preItem[0] === 'T' || preItem[0] === 't') {
this.quadraticCurveTo(preX, preY, preX + preX - preCX, preY + preY - preCY, preX + item[1], preY + item[2])
this.quadraticCurveTo(
preX,
preY,
preX + preX - preCX,
preY + preY - preCY,
preX + item[1],
preY + item[2]
)
preCX = preX + preX - preCX
preCY = preY + preY - preCY
}

View File

@ -1,14 +1,13 @@
import Shape from './shape'
class Polygon extends Shape {
constructor (points, option) {
constructor(points, option) {
super()
this.option = option || {}
this.points = points
}
draw () {
draw() {
this.moveTo(this.points[0], this.points[1])
for (let i = 2, len = this.points.length; i < len; i += 2) {
@ -22,7 +21,6 @@ class Polygon extends Shape {
// this.lineJoin('round');
// this.stroke();
// }
}
}

View File

@ -5,20 +5,16 @@ class Polyline extends Shape {
super()
this.option = option || {}
this.points = points
}
draw() {
this.moveTo(this.points[0], this.points[1])
for (let i = 2, len = this.points.length; i < len; i += 2) {
this.lineTo(this.points[i], this.points[i + 1])
}
this.fill()
}
}

View File

@ -1,7 +1,7 @@
import Shape from './shape'
class Rect extends Shape {
constructor (width, height, option) {
constructor(width, height, option) {
super()
this.width = width
@ -9,7 +9,7 @@ class Rect extends Shape {
this.option = option || {}
}
draw () {
draw() {
this.rect(0, 0, this.width, this.height)
}
}

View File

@ -1,21 +1,24 @@
import Shape from './shape'
class RoundedRect extends Shape {
constructor (width, height, r, option) {
constructor(width, height, r, option) {
super()
this.option = Object.assign({
lineWidth: 1,
lt: true,
rt: true,
lb: true,
rb: true
}, option)
this.option = Object.assign(
{
lineWidth: 1,
lt: true,
rt: true,
lb: true,
rb: true
},
option
)
this.r = r || 0
this.width = width
this.height = height
}
draw () {
draw() {
const width = this.width,
height = this.height,
r = this.r
@ -31,7 +34,6 @@ class RoundedRect extends Shape {
ex = 0,
ey = 0
this.moveTo(ax, ay)
if (this.option.rt) {
this.arcTo(bx, by, cx, cy, r)

View File

@ -1,7 +1,7 @@
import Shape from './shape'
class Sector extends Shape {
constructor (r, from, to, option) {
constructor(r, from, to, option) {
super()
this.option = option || {}
@ -10,7 +10,7 @@ class Sector extends Shape {
this.to = to
}
draw () {
draw() {
this.moveTo(0, 0)
.arc(0, 0, this.r, this.from, this.to)
.closePath()

View File

@ -5,23 +5,21 @@ class Shape extends Graphics {
// super()
// }
draw () {
draw() {}
}
render (ctx) {
render(ctx) {
this.clear()
this.beginPath()
this.draw()
if (this.option.fillStyle&&this.option.fillStyle!=='none') {
if (this.option.fillStyle && this.option.fillStyle !== 'none') {
this.fillStyle(this.option.fillStyle)
this.fill()
}
if (this.option.strokeStyle) {
this.strokeStyle(this.option.strokeStyle )
if(this.option.lineWidth !== undefined){
this.strokeStyle(this.option.strokeStyle)
if (this.option.lineWidth !== undefined) {
this.lineWidth(parseFloat(this.option.lineWidth))
}
this.stroke()

View File

@ -3,7 +3,7 @@ import util from '../../common/util'
import Bitmap from './bitmap'
class Sprite extends DisplayObject {
constructor (option) {
constructor(option) {
super()
this.option = option
const len = this.option.imgs.length
@ -13,7 +13,7 @@ class Sprite extends DisplayObject {
if (util.isWeapp) {
this.option.imgs.forEach(img => {
util.getImageInWx(img, (result) => {
util.getImageInWx(img, result => {
this.imgMap[img] = result.img
count++
if (count === len) {
@ -21,8 +21,7 @@ class Sprite extends DisplayObject {
this.rect = [0, 0, 0, 0]
}
})
}
)
})
} else {
if (typeof firstImg === 'string') {
const len = this.option.imgs.length
@ -67,7 +66,7 @@ class Sprite extends DisplayObject {
this.interval = 1e3 / option.framerate
this.paused = false
this.animationEnd = option.animationEnd || function () {}
this.animationEnd = option.animationEnd || function() {}
if (this.currentAnimation) {
if (option.playOnce) {
this.gotoAndPlayOnce(this.currentAnimation)
@ -77,27 +76,27 @@ class Sprite extends DisplayObject {
}
}
play () {
play() {
this.paused = false
}
pause () {
pause() {
this.paused = true
}
reset () {
reset() {
this.currentFrameIndex = 0
this.animationFrameIndex = 0
}
updateFrame () {
updateFrame() {
if (!this.paused) {
let opt = this.option
this.dt = Date.now() - this.startTime
let frames = opt.animations[this.currentAnimation].frames
const len = frames.length
const index = Math.floor(this.dt / this.interval % len)
this.rect = opt.frames[ frames[ index ] ]
const index = Math.floor((this.dt / this.interval) % len)
this.rect = opt.frames[frames[index]]
const rectLen = this.rect.length
rectLen > 4 && (this.originX = this.rect[2] * this.rect[4])
@ -107,7 +106,10 @@ class Sprite extends DisplayObject {
this.img = typeof img === 'string' ? this.imgMap[img] : img
}
if (index === len - 1 && (!this.endTime || Date.now() - this.endTime > this.interval)) {
if (
index === len - 1 &&
(!this.endTime || Date.now() - this.endTime > this.interval)
) {
this.endTime = Date.now()
this.animationEnd()
if (this._willDestroy) {
@ -117,14 +119,14 @@ class Sprite extends DisplayObject {
}
}
gotoAndPlay (animation) {
gotoAndPlay(animation) {
this.paused = false
this.reset()
this.currentAnimation = animation
this.startTime = Date.now()
}
gotoAndStop (animation) {
gotoAndStop(animation) {
this.reset()
this.paused = true
this.currentAnimation = animation
@ -143,7 +145,7 @@ class Sprite extends DisplayObject {
}
}
gotoAndPlayOnce (animation) {
gotoAndPlayOnce(animation) {
this.gotoAndPlay(animation)
this._willDestroy = true
}

View File

@ -7,22 +7,28 @@ import WeStage from './we-stage'
import option from '../base/stage-propagation-tag'
class Stage extends Group {
constructor (width, height, renderTo) {
constructor(width, height, renderTo) {
super()
const len = arguments.length
this.isWegame = typeof wx !== 'undefined' && wx.createCanvas
this.moveDetectionInterval = 0
if (len === 0) { // wegame
if (len === 0) {
// wegame
this.canvas = wegameCanvas
this.disableMoveDetection = true
this.moveDetectionInterval = 500
} else if (len === 4) { // weapp
} else if (len === 4) {
// weapp
return new WeStage(arguments[0], arguments[1], arguments[2], arguments[3])
} else {
if (len === 1) {
this.canvas = typeof width === 'string' ? document.querySelector(width) : width
this.canvas =
typeof width === 'string' ? document.querySelector(width) : width
} else {
this.renderTo = typeof renderTo === 'string' ? document.querySelector(renderTo) : renderTo
this.renderTo =
typeof renderTo === 'string'
? document.querySelector(renderTo)
: renderTo
if (this.renderTo.tagName === 'CANVAS') {
this.canvas = this.renderTo
this.canvas.width = width
@ -48,18 +54,28 @@ class Stage extends Group {
wx.onTouchEnd(evt => this._handleMouseUp(evt))
} else {
this.canvas.addEventListener('click', evt => this._handleClick(evt))
this.canvas.addEventListener('mousedown', evt => this._handleMouseDown(evt))
this.canvas.addEventListener('mousemove', evt => this._handleMouseMove(evt))
this.canvas.addEventListener('mousedown', evt =>
this._handleMouseDown(evt)
)
this.canvas.addEventListener('mousemove', evt =>
this._handleMouseMove(evt)
)
this.canvas.addEventListener('mouseup', evt => this._handleMouseUp(evt))
this.canvas.addEventListener('mouseout', evt => this._handleMouseOut(evt))
this.canvas.addEventListener('touchstart', evt => this._handleMouseDown(evt))
this.canvas.addEventListener('touchmove', evt => this._handleMouseMove(evt))
this.canvas.addEventListener('touchstart', evt =>
this._handleMouseDown(evt)
)
this.canvas.addEventListener('touchmove', evt =>
this._handleMouseMove(evt)
)
this.canvas.addEventListener('touchend', evt => this._handleMouseUp(evt))
this.canvas.addEventListener('dblclick', evt => this._handleDblClick(evt))
// this.addEvent(this.canvas, "mousewheel", this._handleMouseWheel.bind(this));
document.addEventListener('contextmenu', evt => this._handleContextmenu(evt))
document.addEventListener('contextmenu', evt =>
this._handleContextmenu(evt)
)
}
this.borderTopWidth = 0
@ -91,21 +107,24 @@ class Stage extends Group {
this._moveDetectionTime = Date.now()
}
_handleContextmenu (evt) {
_handleContextmenu(evt) {
this._getObjectUnderPoint(evt)
}
_handleDblClick (evt) {
_handleDblClick(evt) {
this._getObjectUnderPoint(evt)
}
_handleClick (evt) {
if (Math.abs(this._mouseDownX - this._mouseUpX) < 20 && Math.abs(this._mouseDownY - this._mouseUpY) < 20) {
_handleClick(evt) {
if (
Math.abs(this._mouseDownX - this._mouseUpX) < 20 &&
Math.abs(this._mouseDownY - this._mouseUpY) < 20
) {
this._getObjectUnderPoint(evt)
}
}
_handleMouseDown (evt) {
_handleMouseDown(evt) {
if (this.isWegame) {
evt.type = 'touchstart'
}
@ -118,12 +137,12 @@ class Stage extends Group {
this.preStageY = evt.stageY
}
scaleEventPoint (x, y) {
scaleEventPoint(x, y) {
this._scaleX = x
this._scaleY = y
}
_handleMouseUp (evt) {
_handleMouseUp(evt) {
if (this.isWegame) {
evt.type = 'touchend'
}
@ -140,13 +159,18 @@ class Stage extends Group {
this.preStageX = null
this.preStageY = null
if (obj && evt.type === 'touchend' && Math.abs(this._mouseDownX - this._mouseUpX) < 30 && Math.abs(this._mouseDownY - this._mouseUpY) < 30) {
if (
obj &&
evt.type === 'touchend' &&
Math.abs(this._mouseDownX - this._mouseUpX) < 30 &&
Math.abs(this._mouseDownY - this._mouseUpY) < 30
) {
mockEvt.type = 'tap'
obj.dispatchEvent(mockEvt)
}
}
_handleMouseOut (evt) {
_handleMouseOut(evt) {
this._computeStageXY(evt)
this.dispatchEvent({
pureEvent: evt,
@ -156,8 +180,8 @@ class Stage extends Group {
})
}
_handleMouseMove (evt) {
if(Date.now() - this._moveDetectionTime < this.moveDetectionInterval){
_handleMouseMove(evt) {
if (Date.now() - this._moveDetectionTime < this.moveDetectionInterval) {
return
}
this._moveDetectionTime = Date.now()
@ -214,8 +238,8 @@ class Stage extends Group {
}
}
_setCursor (obj) {
if(!this.canvas.style){
_setCursor(obj) {
if (!this.canvas.style) {
return
}
if (obj.cursor) {
@ -227,7 +251,7 @@ class Stage extends Group {
}
}
_getObjectUnderPoint (evt) {
_getObjectUnderPoint(evt) {
this._computeStageXY(evt)
if (this.hitAABB) {
return this._hitRender.hitAABB(this, evt)
@ -236,8 +260,10 @@ class Stage extends Group {
}
}
_computeStageXY (evt) {
this._boundingClientRect = this.isWegame ? {left: 0, top: 0} : this.canvas.getBoundingClientRect()
_computeStageXY(evt) {
this._boundingClientRect = this.isWegame
? { left: 0, top: 0 }
: this.canvas.getBoundingClientRect()
if (evt.touches || evt.changedTouches) {
const firstTouch = evt.touches[0] || evt.changedTouches[0]
if (firstTouch) {
@ -245,18 +271,25 @@ class Stage extends Group {
evt.stageY = (firstTouch.pageY - this.offset[1]) / this._scaleY
}
} else {
evt.stageX = (evt.clientX - this._boundingClientRect.left - this.borderLeftWidth) / this._scaleX
evt.stageY = (evt.clientY - this._boundingClientRect.top - this.borderTopWidth) / this._scaleY
evt.stageX =
(evt.clientX - this._boundingClientRect.left - this.borderLeftWidth) /
this._scaleX
evt.stageY =
(evt.clientY - this._boundingClientRect.top - this.borderTopWidth) /
this._scaleY
}
}
_getOffset (el) {
_getOffset(el) {
if (this.isWegame) {
return [0, 0]
}
let _t = 0,
_l = 0
if (document.documentElement.getBoundingClientRect && el.getBoundingClientRect) {
if (
document.documentElement.getBoundingClientRect &&
el.getBoundingClientRect
) {
let box = el.getBoundingClientRect()
_l = box.left
_t = box.top
@ -268,25 +301,28 @@ class Stage extends Group {
}
return [_l, _t]
}
return [_l + Math.max(document.documentElement.scrollLeft, document.body.scrollLeft), _t + Math.max(document.documentElement.scrollTop, document.body.scrollTop)]
return [
_l +
Math.max(document.documentElement.scrollLeft, document.body.scrollLeft),
_t + Math.max(document.documentElement.scrollTop, document.body.scrollTop)
]
}
update () {
update() {
this.renderer.update(this)
}
on (type, fn) {
this.canvas.addEventListener(type, (evt) => {
if(!option.stagePropagationStopped[type]){
on(type, fn) {
this.canvas.addEventListener(type, evt => {
if (!option.stagePropagationStopped[type]) {
this._computeStageXY(evt)
fn(evt)
}
option.stagePropagationStopped[type] = false
})
}
off (type, fn) {
off(type, fn) {
this.canvas.removeEventListener(type, fn)
}
}

View File

@ -10,7 +10,7 @@ if (util.isWeapp) {
}
class Text extends DisplayObject {
constructor (text, option) {
constructor(text, option) {
super()
this.text = text
@ -21,7 +21,7 @@ class Text extends DisplayObject {
this.baseline = option.baseline || 'top'
}
getWidth () {
getWidth() {
if (!measureCtx) {
if (util.isWegame) {
measureCtx = wx.createCanvas().getContext('2d')

View File

@ -4,7 +4,7 @@ import WxHitRender from '../render/wx-hit-render.js'
import Event from '../base/event.js'
class WeStage extends Group {
constructor (width, height, id, page) {
constructor(width, height, id, page) {
super()
const component = page.selectComponent('#' + id)
@ -24,15 +24,16 @@ class WeStage extends Group {
this.hitAABB = true
this.width = width
this.height = height
this.___instanceof = 'Stage'
}
touchStartHandler (evt) {
touchStartHandler(evt) {
const p1 = evt.changedTouches[0]
evt.stageX = Math.round(p1.x * this.scaleX);
evt.stageY = Math.round(p1.y * this.scaleY);
evt.stageX = Math.round(p1.x * this.scaleX)
evt.stageY = Math.round(p1.y * this.scaleY)
this._getObjectUnderPoint(evt, (obj) => {
this._getObjectUnderPoint(evt, obj => {
this.willDragObject = obj
this._mouseDownX = evt.stageX
this._mouseDownY = evt.stageY
@ -41,13 +42,13 @@ class WeStage extends Group {
})
}
touchMoveHandler (evt) {
touchMoveHandler(evt) {
const p1 = evt.changedTouches[0]
evt.stageX = Math.round(p1.x * this.scaleX);
evt.stageY = Math.round(p1.y * this.scaleY);
evt.stageX = Math.round(p1.x * this.scaleX)
evt.stageY = Math.round(p1.y * this.scaleY)
this._getObjectUnderPoint(evt, (obj) => {
this._getObjectUnderPoint(evt, obj => {
let mockEvt = new Event()
mockEvt.stageX = evt.stageX
mockEvt.stageY = evt.stageY
@ -79,11 +80,11 @@ class WeStage extends Group {
})
}
touchEndHandler (evt) {
touchEndHandler(evt) {
const p1 = evt.changedTouches[0]
evt.stageX = Math.round(p1.x * this.scaleX);
evt.stageY = Math.round(p1.y * this.scaleY);
evt.stageX = Math.round(p1.x * this.scaleX)
evt.stageY = Math.round(p1.y * this.scaleY)
let mockEvt = new Event()
mockEvt.stageX = evt.stageX
@ -91,7 +92,7 @@ class WeStage extends Group {
mockEvt.pureEvent = evt
this._getObjectUnderPoint(evt, (obj) => {
this._getObjectUnderPoint(evt, obj => {
this._mouseUpX = evt.stageX
this._mouseUpY = evt.stageY
@ -99,14 +100,18 @@ class WeStage extends Group {
this.preStageX = null
this.preStageY = null
if (obj && Math.abs(this._mouseDownX - this._mouseUpX) < 30 && Math.abs(this._mouseDownY - this._mouseUpY) < 30) {
if (
obj &&
Math.abs(this._mouseDownX - this._mouseUpX) < 30 &&
Math.abs(this._mouseDownY - this._mouseUpY) < 30
) {
mockEvt.type = 'tap'
obj.dispatchEvent(mockEvt)
}
})
}
_handleMouseOut (evt) {
_handleMouseOut(evt) {
this.dispatchEvent({
pureEvent: evt,
type: 'mouseout',
@ -115,7 +120,7 @@ class WeStage extends Group {
})
}
_getObjectUnderPoint (evt, cb) {
_getObjectUnderPoint(evt, cb) {
//const list = this.renderer.getHitRenderList(this)
if (this.hitAABB) {
return this._hitRender.hitAABB(this, evt, cb)
@ -138,8 +143,8 @@ class WeStage extends Group {
break
}
}
update () {
update() {
this.renderer.update(this)
}
}

View File

@ -1,6 +1,6 @@
import { createImageData } from './create-image-data'
export function blur (pixels, diameter) {
export function blur(pixels, diameter) {
diameter = Math.abs(diameter)
if (diameter <= 1) return pixels
var radius = diameter / 2
@ -24,14 +24,15 @@ export function blur (pixels, diameter) {
return separableConvolve(pixels, weights, weights, false)
}
function separableConvolve (pixels, horizWeights, vertWeights, opaque) {
function separableConvolve(pixels, horizWeights, vertWeights, opaque) {
return horizontalConvolve(
verticalConvolve(pixels, vertWeights, opaque),
horizWeights, opaque
horizWeights,
opaque
)
}
function horizontalConvolve (pixels, weightsVector, opaque) {
function horizontalConvolve(pixels, weightsVector, opaque) {
var side = weightsVector.length
var halfSide = Math.floor(side / 2)
@ -51,7 +52,10 @@ function horizontalConvolve (pixels, weightsVector, opaque) {
var sy = y
var sx = x
var dstOff = (y * w + x) * 4
var r = 0, g = 0, b = 0, a = 0
var r = 0,
g = 0,
b = 0,
a = 0
for (var cx = 0; cx < side; cx++) {
var scy = sy
var scx = Math.min(sw - 1, Math.max(0, sx + cx - halfSide))
@ -71,7 +75,7 @@ function horizontalConvolve (pixels, weightsVector, opaque) {
return output
}
function verticalConvolve (pixels, weightsVector, opaque) {
function verticalConvolve(pixels, weightsVector, opaque) {
var side = weightsVector.length
var halfSide = Math.floor(side / 2)
@ -91,7 +95,10 @@ function verticalConvolve (pixels, weightsVector, opaque) {
var sy = y
var sx = x
var dstOff = (y * w + x) * 4
var r = 0, g = 0, b = 0, a = 0
var r = 0,
g = 0,
b = 0,
a = 0
for (var cy = 0; cy < side; cy++) {
var scy = Math.min(sh - 1, Math.max(0, sy + cy - halfSide))
var scx = sx
@ -109,4 +116,4 @@ function verticalConvolve (pixels, weightsVector, opaque) {
}
}
return output
};
}

View File

@ -1,4 +1,4 @@
export function brightness (pixels, adjustment) {
export function brightness(pixels, adjustment) {
const data = pixels.data
const length = data.length
for (let i = 0; i < length; i += 4) {

View File

@ -1,7 +1,8 @@
export function colorize (pixels, option) {
export function colorize(pixels, option) {
const data = pixels.data
const length = data.length
const hex = (option.color.charAt(0) === '#') ? option.color.substr(1) : option.color
const hex =
option.color.charAt(0) === '#' ? option.color.substr(1) : option.color
const colorRGB = {
r: parseInt(hex.substr(0, 2), 16),
g: parseInt(hex.substr(2, 2), 16),
@ -9,10 +10,10 @@ export function colorize (pixels, option) {
}
for (let i = 0; i < length; i += 4) {
data[i] -= (data[i] - colorRGB.r) * (option.amount)
data[i + 1] -= (data[i + 1] - colorRGB.g) * (option.amount)
data[i + 2] -= (data[i + 2] - colorRGB.b) * (option.amount)
data[i] -= (data[i] - colorRGB.r) * option.amount
data[i + 1] -= (data[i + 1] - colorRGB.g) * option.amount
data[i + 2] -= (data[i + 2] - colorRGB.b) * option.amount
}
return pixels
};
}

View File

@ -1,4 +1,4 @@
export function contrast (pixels, contrast) {
export function contrast(pixels, contrast) {
const data = pixels.data
const length = data.length
const factor = (259 * (contrast + 255)) / (255 * (259 - contrast))
@ -10,4 +10,4 @@ export function contrast (pixels, contrast) {
}
return pixels
};
}

View File

@ -6,6 +6,6 @@ if (typeof document !== 'undefined') {
tmpCtx = wx.createCanvas().getContext('2d')
}
export function createImageData (w, h) {
export function createImageData(w, h) {
return tmpCtx.createImageData(w, h)
}

View File

@ -1,4 +1,4 @@
export function gamma (pixels, adjustment) {
export function gamma(pixels, adjustment) {
const data = pixels.data
const length = data.length
for (let i = 0; i < length; i += 4) {
@ -7,4 +7,4 @@ export function gamma (pixels, adjustment) {
data[i + 2] = Math.pow(data[i + 2] / 255, adjustment) * 255
}
return pixels
};
}

View File

@ -1,4 +1,4 @@
export function grayscale (pixels, adjustment) {
export function grayscale(pixels, adjustment) {
const data = pixels.data
const length = data.length
for (let i = 0; i < length; i += 4) {
@ -14,4 +14,4 @@ export function grayscale (pixels, adjustment) {
data[i + 2] = b + (v - b) * adjustment
}
return pixels
};
}

View File

@ -1,4 +1,3 @@
import { invert } from './invert'
import { blur } from './blur'
import { brightness } from './brightness'
@ -9,7 +8,7 @@ import { threshold } from './threshold'
import { gamma } from './gamma'
import { colorize } from './colorize'
export function filter (pixels, name) {
export function filter(pixels, name) {
if (typeof name === 'string') {
let type = name.split('(')[0]
let num = getNumber(name)
@ -39,8 +38,13 @@ export function filter (pixels, name) {
}
}
function getNumber (str) {
str = str.replace(/(invert)|(brightness)|(blur)|(contrast)|(grayscale)|(sepia)|(threshold)|(gamma)?\(/g, '').replace(')', '')
function getNumber(str) {
str = str
.replace(
/(invert)|(brightness)|(blur)|(contrast)|(grayscale)|(sepia)|(threshold)|(gamma)?\(/g,
''
)
.replace(')', '')
if (str.indexOf('%') !== -1) {
return Number(str.replace('%', '')) / 100
} else if (str.indexOf('px') !== -1) {

View File

@ -1,5 +1,4 @@
export function invert (pixels, ratio) {
export function invert(pixels, ratio) {
const d = pixels.data
ratio = ratio === undefined ? 1 : ratio
for (var i = 0; i < d.length; i += 4) {

View File

@ -1,4 +1,4 @@
export function sepia (pixels, adjustment) {
export function sepia(pixels, adjustment) {
const data = pixels.data
const length = data.length
for (let i = 0; i < length; i += 4) {
@ -6,9 +6,9 @@ export function sepia (pixels, adjustment) {
const g = data[i + 1]
const b = data[i + 2]
const sr = (r * 0.393) + (g * 0.769) + (b * 0.189)
const sg = (r * 0.349) + (g * 0.686) + (b * 0.168)
const sb = (r * 0.272) + (g * 0.534) + (b * 0.131)
const sr = r * 0.393 + g * 0.769 + b * 0.189
const sg = r * 0.349 + g * 0.686 + b * 0.168
const sb = r * 0.272 + g * 0.534 + b * 0.131
data[i] = r + (sr - r) * adjustment
data[i + 1] = g + (sg - g) * adjustment
@ -16,4 +16,4 @@ export function sepia (pixels, adjustment) {
}
return pixels
};
}

View File

@ -1,12 +1,12 @@
export function threshold (pixels, threshold) {
export function threshold(pixels, threshold) {
const data = pixels.data
const length = data.length
for (let i = 0; i < length; i += 4) {
const r = data[i]
const g = data[i + 1]
const b = data[i + 2]
const v = (0.2126 * r + 0.7152 * g + 0.0722 * b >= threshold) ? 255 : 0
const v = 0.2126 * r + 0.7152 * g + 0.0722 * b >= threshold ? 255 : 0
data[i] = data[i + 1] = data[i + 2] = v
}
return pixels
};
}

View File

@ -7,7 +7,7 @@ import Text from '../display/text.js'
import { filter } from '../filter/index.js'
class CanvasRender extends Render {
constructor (canvasOrContext, width, height) {
constructor(canvasOrContext, width, height) {
super()
if (arguments.length === 3) {
this.ctx = canvasOrContext
@ -20,11 +20,11 @@ class CanvasRender extends Render {
}
}
clear (ctx, width, height) {
clear(ctx, width, height) {
ctx.clearRect(0, 0, width, height)
}
render (ctx, o, cacheData) {
render(ctx, o, cacheData) {
let mtx = o._matrix
if (o.children) {
let list = o.children.slice(0),
@ -32,7 +32,17 @@ class CanvasRender extends Render {
for (let i = 0; i < l; i++) {
let child = list[i]
mtx.initialize(1, 0, 0, 1, 0, 0)
mtx.appendTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, o.originX, o.originY)
mtx.appendTransform(
o.x,
o.y,
o.scaleX,
o.scaleY,
o.rotation,
o.skewX,
o.skewY,
o.originX,
o.originY
)
// if (!this.checkBoundEvent(child)) continue
ctx.save()
this._render(ctx, child, cacheData ? null : mtx, cacheData, true)
@ -43,12 +53,19 @@ class CanvasRender extends Render {
}
}
_render (ctx, o, mtx, cacheData, inGroup) {
_render(ctx, o, mtx, cacheData, inGroup) {
if (!o.isVisible()) return
if (mtx && !o.fixed) {
o._matrix.initialize(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty)
} else if (cacheData && !o.fixed) {
o._matrix.initialize(cacheData.scale, 0, 0, cacheData.scale, cacheData.x * -1, cacheData.y * -1)
o._matrix.initialize(
cacheData.scale,
0,
0,
cacheData.scale,
cacheData.x * -1,
cacheData.y * -1
)
} else {
o._matrix.initialize(1, 0, 0, 1, 0, 0)
}
@ -57,14 +74,41 @@ class CanvasRender extends Render {
// group 进行 cache canvas 内部的子元素需要进行appendTransform
// cache canvas 渲染不叠加自身的 transform因为进入主渲染会进行appendTransform
if (inGroup || !cacheData) {
mtx.appendTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, o.originX, o.originY)
mtx.appendTransform(
o.x,
o.y,
o.scaleX,
o.scaleY,
o.rotation,
o.skewX,
o.skewY,
o.originX,
o.originY
)
}
const ocg = o.clipGraphics
if (ocg) {
ctx.beginPath()
ocg._matrix.copy(mtx)
ocg._matrix.appendTransform(ocg.x, ocg.y, ocg.scaleX, ocg.scaleY, ocg.rotation, ocg.skewX, ocg.skewY, ocg.originX, ocg.originY)
ctx.setTransform(ocg._matrix.a, ocg._matrix.b, ocg._matrix.c, ocg._matrix.d, ocg._matrix.tx, ocg._matrix.ty)
ocg._matrix.appendTransform(
ocg.x,
ocg.y,
ocg.scaleX,
ocg.scaleY,
ocg.rotation,
ocg.skewX,
ocg.skewY,
ocg.originX,
ocg.originY
)
ctx.setTransform(
ocg._matrix.a,
ocg._matrix.b,
ocg._matrix.c,
ocg._matrix.d,
ocg._matrix.tx,
ocg._matrix.ty
)
ocg.render(ctx)
ctx.clip(o.clipRuleNonzero ? 'nonzero' : 'evenodd')
}
@ -73,8 +117,25 @@ class CanvasRender extends Render {
if (oacg) {
ctx.beginPath()
oacg._matrix.initialize(1, 0, 0, 1, 0, 0)
oacg._matrix.appendTransform(oacg.x, oacg.y, oacg.scaleX, oacg.scaleY, oacg.rotation, oacg.skewX, oacg.skewY, oacg.originX, oacg.originY)
ctx.setTransform(oacg._matrix.a, oacg._matrix.b, oacg._matrix.c, oacg._matrix.d, oacg._matrix.tx, oacg._matrix.ty)
oacg._matrix.appendTransform(
oacg.x,
oacg.y,
oacg.scaleX,
oacg.scaleY,
oacg.rotation,
oacg.skewX,
oacg.skewY,
oacg.originX,
oacg.originY
)
ctx.setTransform(
oacg._matrix.a,
oacg._matrix.b,
oacg._matrix.c,
oacg._matrix.d,
oacg._matrix.tx,
oacg._matrix.ty
)
oacg.render(ctx)
ctx.clip(o.absClipRuleNonzero ? 'nonzero' : 'evenodd')
}
@ -92,7 +153,19 @@ class CanvasRender extends Render {
// debug cacheCanvas
// document.body.appendChild(o.cacheCanvas)
if (o._readyToFilter) {
o.cacheCtx.putImageData(filter(o.cacheCtx.getImageData(0, 0, o.cacheCanvas.width, o.cacheCanvas.height), o._filterName), 0, 0)
o.cacheCtx.putImageData(
filter(
o.cacheCtx.getImageData(
0,
0,
o.cacheCanvas.width,
o.cacheCanvas.height
),
o._filterName
),
0,
0
)
this._readyToFilter = false
}
@ -115,23 +188,45 @@ class CanvasRender extends Render {
this.setComplexProps(ctx, o)
o.updateFrame()
let rect = o.rect
ctx.drawImage(o.img, rect[0], rect[1], rect[2], rect[3], 0, 0, rect[2], rect[3])
ctx.drawImage(
o.img,
rect[0],
rect[1],
rect[2],
rect[3],
0,
0,
rect[2],
rect[3]
)
} else if (o instanceof Bitmap && o.rect) {
this.setComplexProps(ctx, o)
let bRect = o.rect
ctx.drawImage(o.img, bRect[0], bRect[1], bRect[2], bRect[3], 0, 0, bRect[2], bRect[3])
ctx.drawImage(
o.img,
bRect[0],
bRect[1],
bRect[2],
bRect[3],
0,
0,
bRect[2],
bRect[3]
)
} else if (o instanceof Text) {
this.setComplexProps(ctx, o)
ctx.font = o.font
ctx.fillStyle = o.color
ctx.textAlign= o.textAlign
ctx.textAlign = o.textAlign
ctx.textBaseline = o.baseline
ctx.fillText(o.text, 0, 0)
}
}
setComplexProps (ctx, o) {
o.complexCompositeOperation = ctx.globalCompositeOperation = this.getCompositeOperation(o)
setComplexProps(ctx, o) {
o.complexCompositeOperation = ctx.globalCompositeOperation = this.getCompositeOperation(
o
)
o.complexAlpha = ctx.globalAlpha = this.getAlpha(o, 1)
o.complexShadow = this.getShadow(o)
@ -143,12 +238,12 @@ class CanvasRender extends Render {
}
}
getCompositeOperation (o) {
getCompositeOperation(o) {
if (o.compositeOperation) return o.compositeOperation
if (o.parent) return this.getCompositeOperation(o.parent)
}
getAlpha (o, alpha) {
getAlpha(o, alpha) {
var result = o.alpha * alpha
if (o.parent) {
return this.getAlpha(o.parent, result)
@ -156,7 +251,7 @@ class CanvasRender extends Render {
return result
}
getShadow (o) {
getShadow(o) {
if (o.shadow) return o.shadow
if (o.parent) return this.getShadow(o.parent)
}

View File

@ -7,7 +7,7 @@ import Bitmap from '../display/bitmap.js'
import Text from '../display/text.js'
class HitRender extends Render {
constructor () {
constructor() {
super()
if (typeof wx !== 'undefined' && wx.createCanvas) {
this.canvas = wx.createCanvas()
@ -28,38 +28,38 @@ class HitRender extends Render {
this.disableEvents = ['mouseover', 'mouseout', 'mousemove', 'touchmove']
}
clear () {
clear() {
this.ctx.clearRect(0, 0, this.width, this.height)
}
hitAABB (o, evt) {
hitAABB(o, evt) {
let list = o.children.slice(0),
l = list.length
for (let i = l - 1; i >= 0; i--) {
let child = list[i]
// if (!this.isbindingEvent(child)) continue;
let path = this._hitAABB(child, evt, [], true)
let path = this._hitAABB(child, evt, [], true)
if (path.length > 0) {
let target = path[path.length - 1]
this._dispatchEvent(target, evt)
return target
}
let target = path[path.length - 1]
this._dispatchEvent(target, evt)
return target
}
}
}
_hitAABB (o, evt, path, rootCall) {
_hitAABB(o, evt, path, rootCall) {
if (o.ignoreHit || !o.isVisible()) {
return
}
}
o.initAABB()
if (o.AABB && this.checkPointInAABB(evt.stageX, evt.stageY, o.AABB)) {
// this._bubbleEvent(o, type, evt);
o.initAABB()
if (o.AABB && this.checkPointInAABB(evt.stageX, evt.stageY, o.AABB)) {
// this._bubbleEvent(o, type, evt);
o.___$push = true
path.push(o)
//return o
}
path.push(o)
//return o
}
if (o instanceof Group) {
let list = o.children.slice(0),
@ -67,7 +67,7 @@ class HitRender extends Render {
for (let i = l - 1; i >= 0; i--) {
let child = list[i]
this._hitAABB(child, evt, path)
if(child.___$push){
if (child.___$push) {
delete child.___$push
//同级只找一个就好了,所有 break
break
@ -76,12 +76,12 @@ class HitRender extends Render {
}
}
if(rootCall){
return path
}
if (rootCall) {
return path
}
}
checkPointInAABB (x, y, AABB) {
checkPointInAABB(x, y, AABB) {
let minX = AABB[0]
if (x < minX) return false
let minY = AABB[1]
@ -93,7 +93,7 @@ class HitRender extends Render {
return true
}
hitPixel (o, evt) {
hitPixel(o, evt) {
const ctx = this.ctx
ctx.clearRect(0, 0, 2, 2)
let mtx = o._hitMatrix
@ -102,7 +102,17 @@ class HitRender extends Render {
for (let i = l - 1; i >= 0; i--) {
let child = list[i]
mtx.initialize(1, 0, 0, 1, 0, 0)
mtx.appendTransform(o.x - evt.stageX, o.y - evt.stageY, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, o.originX, o.originY)
mtx.appendTransform(
o.x - evt.stageX,
o.y - evt.stageY,
o.scaleX,
o.scaleY,
o.rotation,
o.skewX,
o.skewY,
o.originX,
o.originY
)
// if (!this.checkBoundEvent(child)) continue
ctx.save()
let target = this._hitPixel(child, evt, mtx)
@ -111,25 +121,52 @@ class HitRender extends Render {
}
}
_hitPixel (o, evt, mtx) {
_hitPixel(o, evt, mtx) {
if (o.ignoreHit || !o.isVisible()) return
let ctx = this.ctx
if(o.fixed){
if (o.fixed) {
o._hitMatrix.initialize(1, 0, 0, 1, -evt.stageX, -evt.stageY)
}else if (mtx) {
} else if (mtx) {
o._hitMatrix.initialize(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty)
} else {
o._hitMatrix.initialize(1, 0, 0, 1, 0, 0)
}
mtx = o._hitMatrix
mtx.appendTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, o.originX, o.originY)
mtx.appendTransform(
o.x,
o.y,
o.scaleX,
o.scaleY,
o.rotation,
o.skewX,
o.skewY,
o.originX,
o.originY
)
const ocg = o.clipGraphics
if (ocg) {
ctx.beginPath()
ocg._matrix.copy(mtx)
ocg._matrix.appendTransform(ocg.x, ocg.y, ocg.scaleX, ocg.scaleY, ocg.rotation, ocg.skewX, ocg.skewY, ocg.originX, ocg.originY)
ctx.setTransform(ocg._matrix.a, ocg._matrix.b, ocg._matrix.c, ocg._matrix.d, ocg._matrix.tx, ocg._matrix.ty)
ocg._matrix.appendTransform(
ocg.x,
ocg.y,
ocg.scaleX,
ocg.scaleY,
ocg.rotation,
ocg.skewX,
ocg.skewY,
ocg.originX,
ocg.originY
)
ctx.setTransform(
ocg._matrix.a,
ocg._matrix.b,
ocg._matrix.c,
ocg._matrix.d,
ocg._matrix.tx,
ocg._matrix.ty
)
ocg.render(ctx)
ctx.clip(o.clipRuleNonzero ? 'nonzero' : 'evenodd')
}
@ -138,8 +175,25 @@ class HitRender extends Render {
if (oacg) {
ctx.beginPath()
oacg._matrix.initialize(1, 0, 0, 1, 0, 0)
oacg._matrix.appendTransform(oacg.x, oacg.y, oacg.scaleX, oacg.scaleY, oacg.rotation, oacg.skewX, oacg.skewY, oacg.originX, oacg.originY)
ctx.setTransform(oacg._matrix.a, oacg._matrix.b, oacg._matrix.c, oacg._matrix.d, oacg._matrix.tx, oacg._matrix.ty)
oacg._matrix.appendTransform(
oacg.x,
oacg.y,
oacg.scaleX,
oacg.scaleY,
oacg.rotation,
oacg.skewX,
oacg.skewY,
oacg.originX,
oacg.originY
)
ctx.setTransform(
oacg._matrix.a,
oacg._matrix.b,
oacg._matrix.c,
oacg._matrix.d,
oacg._matrix.tx,
oacg._matrix.ty
)
oacg.render(ctx)
ctx.clip(o.absClipRuleNonzero ? 'nonzero' : 'evenodd')
}
@ -167,36 +221,56 @@ class HitRender extends Render {
o.updateFrame()
let rect = o.rect
ctx.drawImage(o.img, rect[0], rect[1], rect[2], rect[3], 0, 0, rect[2], rect[3])
ctx.drawImage(
o.img,
rect[0],
rect[1],
rect[2],
rect[3],
0,
0,
rect[2],
rect[3]
)
} else if (o instanceof Bitmap && o.rect) {
this.setComplexProps(ctx, o)
let bRect = o.rect
ctx.drawImage(o.img, bRect[0], bRect[1], bRect[2], bRect[3], 0, 0, bRect[2], bRect[3])
ctx.drawImage(
o.img,
bRect[0],
bRect[1],
bRect[2],
bRect[3],
0,
0,
bRect[2],
bRect[3]
)
} else if (o instanceof Text) {
this.setComplexProps(ctx, o)
ctx.font = o.font
ctx.fillStyle = o.color
ctx.textAlign= o.textAlign
ctx.textAlign = o.textAlign
ctx.textBaseline = o.baseline
ctx.fillText(o.text, 0, 0)
}
}
if(o.hitBox){
if (o.hitBox) {
o.initAABB()
if (this.checkPointInAABB(evt.stageX, evt.stageY, o.AABB)) {
this._dispatchEvent(o, evt)
return o
}
}else if (ctx.getImageData(0, 0, 1, 1).data[3] > 0) {
} else if (ctx.getImageData(0, 0, 1, 1).data[3] > 0) {
this._dispatchEvent(o, evt)
return o
}
}
setComplexProps (ctx, o) {
setComplexProps(ctx, o) {
ctx.globalCompositeOperation = o.complexCompositeOperation
ctx.globalAlpha = o.complexAlpha
// The shadow does not trigger the event, so remove it
@ -208,7 +282,7 @@ class HitRender extends Render {
// }
}
_dispatchEvent (obj, evt) {
_dispatchEvent(obj, evt) {
if (this.disableEvents.indexOf(evt.type) !== -1) return
let mockEvt = new Event()
mockEvt.stageX = evt.stageX

View File

@ -1,15 +1,9 @@
class Render {
render () {
render() {}
}
renderGraphics() {}
renderGraphics () {
}
clear () {
}
clear() {}
}
export default Render

View File

@ -2,7 +2,7 @@ import CanvasRender from '../render/canvas-render'
import Group from '../display/group.js'
class Renderer {
constructor (canvasOrContext, width, height) {
constructor(canvasOrContext, width, height) {
this.renderList = []
if (arguments.length === 3) {
this.renderer = new CanvasRender(canvasOrContext, width, height)
@ -16,31 +16,31 @@ class Renderer {
this.ctx = this.renderer.ctx
}
update (stage) {
update(stage) {
this.renderer.clear(this.ctx, this.width, this.height)
this.renderer.render(this.ctx, stage)
this.ctx.draw && this.ctx.draw()
}
getHitRenderList (stage) {
getHitRenderList(stage) {
const objs = this.renderList
objs.length = 0
this.computeMatrix(stage)
return objs
}
computeMatrix (stage) {
computeMatrix(stage) {
for (var i = 0, len = stage.children.length; i < len; i++) {
this._computeMatrix(stage.children[i])
}
}
initComplex (o) {
initComplex(o) {
o.complexCompositeOperation = this._getCompositeOperation(o)
o.complexAlpha = this._getAlpha(o, 1)
}
_computeMatrix (o, mtx) {
_computeMatrix(o, mtx) {
if (!o.isVisible()) {
return
}
@ -50,7 +50,17 @@ class Renderer {
o._matrix.initialize(1, 0, 0, 1, 0, 0)
}
o._matrix.appendTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, o.originX, o.originY)
o._matrix.appendTransform(
o.x,
o.y,
o.scaleX,
o.scaleY,
o.rotation,
o.skewX,
o.skewY,
o.originX,
o.originY
)
if (o instanceof Group) {
var list = o.children,
@ -73,12 +83,12 @@ class Renderer {
}
}
_getCompositeOperation (o) {
_getCompositeOperation(o) {
if (o.compositeOperation) return o.compositeOperation
if (o.parent) return this._getCompositeOperation(o.parent)
}
_getAlpha (o, alpha) {
_getAlpha(o, alpha) {
var result = o.alpha * alpha
if (o.parent) {
return this._getAlpha(o.parent, result)
@ -86,11 +96,11 @@ class Renderer {
return result
}
isInStage (o) {
isInStage(o) {
return this.collisionBetweenAABB(o.AABB, this.stage.AABB)
}
collisionBetweenAABB (AABB1, AABB2) {
collisionBetweenAABB(AABB1, AABB2) {
var maxX = AABB1[0] + AABB1[2]
if (maxX < AABB2[0]) return false
var minX = AABB1[0]

View File

@ -1,4 +1,3 @@
import Graphics from '../display/graphics.js'
import Render from './render.js'
import Event from '../base/event.js'
@ -8,7 +7,7 @@ import Text from '../display/text.js'
import Group from '../display/group'
class WxHitRender extends Render {
constructor (ctx, component, canvasId) {
constructor(ctx, component, canvasId) {
super()
this.ctx = ctx
@ -19,7 +18,7 @@ class WxHitRender extends Render {
this.disableEvents = ['mouseover', 'mouseout', 'mousemove', 'touchmove']
}
clear () {
clear() {
this.ctx.clearRect(0, 0, 2, 2)
}
@ -36,35 +35,34 @@ class WxHitRender extends Render {
// }
// }
hitAABB (o, evt) {
hitAABB(o, evt) {
let list = o.children.slice(0),
l = list.length
for (let i = l - 1; i >= 0; i--) {
let child = list[i]
// if (!this.isbindingEvent(child)) continue;
let path = this._hitAABB(child, evt, [], true)
let path = this._hitAABB(child, evt, [], true)
if (path.length > 0) {
let target = path[path.length - 1]
this._dispatchEvent(target, evt)
return target
}
let target = path[path.length - 1]
this._dispatchEvent(target, evt)
return target
}
}
}
_hitAABB (o, evt, path, rootCall) {
_hitAABB(o, evt, path, rootCall) {
if (o.ignoreHit || !o.isVisible()) {
return
}
}
o.initAABB()
if (o.AABB && this.checkPointInAABB(evt.stageX, evt.stageY, o.AABB)) {
// this._bubbleEvent(o, type, evt);
o.initAABB()
if (o.AABB && this.checkPointInAABB(evt.stageX, evt.stageY, o.AABB)) {
// this._bubbleEvent(o, type, evt);
o.___$push = true
path.push(o)
//return o
}
path.push(o)
//return o
}
if (o instanceof Group) {
let list = o.children.slice(0),
@ -72,7 +70,7 @@ class WxHitRender extends Render {
for (let i = l - 1; i >= 0; i--) {
let child = list[i]
this._hitAABB(child, evt, path)
if(child.___$push){
if (child.___$push) {
delete child.___$push
//同级只找一个就好了,所有 break
break
@ -81,12 +79,12 @@ class WxHitRender extends Render {
}
}
if(rootCall){
return path
}
if (rootCall) {
return path
}
}
checkPointInAABB (x, y, AABB) {
checkPointInAABB(x, y, AABB) {
let minX = AABB[0]
if (x < minX) return false
let minY = AABB[1]
@ -98,12 +96,22 @@ class WxHitRender extends Render {
return true
}
hit (list, evt, cb, current) {
hit(list, evt, cb, current) {
const ctx = this.ctx
const obj = list[current]
const mtx = obj._hitMatrix.initialize(1, 0, 0, 1, 0, 0)
ctx.save()
mtx.appendTransform(obj.x - evt.stageX, obj.y - evt.stageY, obj.scaleX, obj.scaleY, obj.rotation, obj.skewX, obj.skewY, obj.originX, obj.originY)
mtx.appendTransform(
obj.x - evt.stageX,
obj.y - evt.stageY,
obj.scaleX,
obj.scaleY,
obj.rotation,
obj.skewX,
obj.skewY,
obj.originX,
obj.originY
)
ctx.globalCompositeOperation = obj.complexCompositeOperation
ctx.globalAlpha = obj.complexAlpha
ctx.setTransform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty)
@ -112,38 +120,63 @@ class WxHitRender extends Render {
} else if (obj instanceof Sprite && obj.rect) {
obj.updateFrame()
const rect = obj.rect
ctx.drawImage(obj.img, rect[0], rect[1], rect[2], rect[3], 0, 0, rect[2], rect[3])
ctx.drawImage(
obj.img,
rect[0],
rect[1],
rect[2],
rect[3],
0,
0,
rect[2],
rect[3]
)
} else if (obj instanceof Bitmap && obj.rect) {
const bRect = obj.rect
ctx.drawImage(obj.img, bRect[0], bRect[1], bRect[2], bRect[3], 0, 0, bRect[2], bRect[3])
ctx.drawImage(
obj.img,
bRect[0],
bRect[1],
bRect[2],
bRect[3],
0,
0,
bRect[2],
bRect[3]
)
} else if (obj instanceof Text) {
ctx.font = obj.font
ctx.fillStyle = obj.color
ctx.textAlign= obj.textAlign
ctx.textAlign = obj.textAlign
ctx.fillText(obj.text, 0, 0)
}
ctx.restore()
current--
ctx.draw(false, () => {
wx.canvasGetImageData({
canvasId: this._hitCanvasId,
x: 0,
y: 0,
width: 1,
height: 1,
success: (res) => {
if (res.data[3] > 1) {
this._dispatchEvent(obj, evt)
cb(obj)
} else {
if (current > -1) { this.hit(list, evt, cb, current) }
wx.canvasGetImageData(
{
canvasId: this._hitCanvasId,
x: 0,
y: 0,
width: 1,
height: 1,
success: res => {
if (res.data[3] > 1) {
this._dispatchEvent(obj, evt)
cb(obj)
} else {
if (current > -1) {
this.hit(list, evt, cb, current)
}
}
}
}
}, this._component)
},
this._component
)
})
}
_dispatchEvent (obj, evt) {
_dispatchEvent(obj, evt) {
if (this.disableEvents.indexOf(evt.type) !== -1) return
let mockEvt = new Event()
mockEvt.stageX = evt.stageX

View File

@ -1,15 +1,26 @@
import cax, { html, SVG } from './cax'
function renderSVG(vdom, canvas, scope) {
const stage = new cax.Stage(vdom.props.width, vdom.props.height, canvas, scope)
const stage = new cax.Stage(
vdom.props.width,
vdom.props.height,
canvas,
scope
)
const svg = new SVG(vdom)
stage.add(svg)
stage.update()
return { renderSVG, stage }
triggerAddedStage(svg)
return svg.children[0]
}
export {
renderSVG,
html
}
function triggerAddedStage(svg) {
svg.addedStage && svg.addedStage()
svg.children &&
svg.children.forEach(child => {
triggerAddedStage(child)
})
}
export { renderSVG, html }

View File

@ -0,0 +1,46 @@
import pathTransition from '../pasition/index'
import { toSVGString } from '../common/util'
export function animate(obj, option) {
const valueList = option.values.split(';').filter(item => item.trim() !== '')
let index = 0,
count = 0,
stage
const len = valueList.length
const duration = (parseFloat(option.dur) / len) * 1000
function _animate() {
const nextIndex = index + 1 === len ? 0 : index + 1
if (index + 1 === len) count++
pathTransition.animate({
from: valueList[index],
to: valueList[nextIndex],
duration: duration,
easing: function(v) {
return v
},
begin: function() {
stage = obj.stage
},
progress: function(shapes, percent) {
obj.d = toSVGString(shapes)
stage.update()
},
end: function(shapes) {
index = nextIndex
if (option.repeatCount === 'indefinite') {
_animate()
} else if (count < Number(option.repeatCount)) {
_animate()
}
}
})
}
if (obj.stage) {
_animate()
} else {
obj.addedStage = () => {
_animate()
}
}
}

View File

@ -4,12 +4,14 @@ import { transform } from './parse-transform'
import { parseEvent } from './parse-event'
export function circle(props) {
const options = Object.assign({
r: 0,
cx: 0,
cy: 0
}, props)
const options = Object.assign(
{
r: 0,
cx: 0,
cy: 0
},
props
)
const circle = new Circle(Number(options.r), parseStyle(props))
circle.x = Number(options.cx)
@ -18,5 +20,4 @@ export function circle(props) {
transform(props, circle)
parseEvent(props, circle)
return circle
}
}

View File

@ -4,19 +4,24 @@ import { transform } from './parse-transform'
import { parseEvent } from './parse-event'
export function ellipse(props) {
const options = Object.assign(
{
rx: 0,
ry: 0,
cx: 0,
cy: 0
},
props
)
const options = Object.assign({
rx: 0,
ry: 0,
cx: 0,
cy: 0
}, props)
const ellipse = new Ellipse(Number(options.rx)*2, Number(options.ry)*2, parseStyle(props))
const ellipse = new Ellipse(
Number(options.rx) * 2,
Number(options.ry) * 2,
parseStyle(props)
)
ellipse.x = Number(options.cx)
ellipse.y = Number(options.cy)
transform(props, ellipse)
parseEvent(props, ellipse)
return ellipse
}
}

View File

@ -3,13 +3,15 @@ import { transform } from './parse-transform'
import { parseEvent } from './parse-event'
export function group(props) {
const options = Object.assign({
width: 0,
height: 0,
x: 0,
y: 0
}, props)
const options = Object.assign(
{
width: 0,
height: 0,
x: 0,
y: 0
},
props
)
const obj = new Group()
obj.x = Number(options.x)
@ -17,7 +19,6 @@ export function group(props) {
transform(props, obj)
parseEvent(props, obj)
return obj
}
return obj
}

View File

@ -1,8 +1,92 @@
const htm = function(){var n=function(e,t,r,u){for(var o=1;o<t.length;o++){var f=t[o++],p="number"==typeof f?r[f]:f;1===t[o]?u[0]=p:2===t[o]?(u[1]=u[1]||{})[t[++o]]=p:3===t[o]?u[1]=Object.assign(u[1]||{},p):u.push(t[o]?e.apply(null,n(e,p,r,["",null])):p)}return u},e=function(n){for(var e,t,r=1,u="",o="",f=[0],p=function(n){1===r&&(n||(u=u.replace(/^\s*\n\s*|\s*\n\s*$/g,"")))?f.push(n||u,0):3===r&&(n||u)?(f.push(n||u,1),r=2):2===r&&"..."===u&&n?f.push(n,3):2===r&&u&&!n?f.push(!0,2,u):4===r&&t&&(f.push(n||u,2,t),t=""),u=""},s=0;s<n.length;s++){s&&(1===r&&p(),p(s));for(var i=0;i<n[s].length;i++)e=n[s][i],1===r?"<"===e?(p(),f=[f],r=3):u+=e:o?e===o?o="":u+=e:'"'===e||"'"===e?o=e:">"===e?(p(),r=1):r&&("="===e?(r=4,t=u,u=""):"/"===e?(p(),3===r&&(f=f[0]),r=f,(f=f[0]).push(r,4),r=0):" "===e||"\t"===e||"\n"===e||"\r"===e?(p(),r=2):u+=e)}return p(),f},t="function"==typeof Map,r=t?new Map:{},u=t?function(n){var t=r.get(n);return t||r.set(n,t=e(n)),t}:function(n){for(var t="",u=0;u<n.length;u++)t+=n[u].length+"-"+n[u];return r[t]||(r[t]=e(n))};return function(e){var t=n(this,u(e),arguments,[]);return t.length>1?t:t[0]}}()
const htm = (function() {
var n = function(e, t, r, u) {
for (var o = 1; o < t.length; o++) {
var f = t[o++],
p = 'number' == typeof f ? r[f] : f
1 === t[o]
? (u[0] = p)
: 2 === t[o]
? ((u[1] = u[1] || {})[t[++o]] = p)
: 3 === t[o]
? (u[1] = Object.assign(u[1] || {}, p))
: u.push(t[o] ? e.apply(null, n(e, p, r, ['', null])) : p)
}
return u
},
e = function(n) {
for (
var e,
t,
r = 1,
u = '',
o = '',
f = [0],
p = function(n) {
1 === r && (n || (u = u.replace(/^\s*\n\s*|\s*\n\s*$/g, '')))
? f.push(n || u, 0)
: 3 === r && (n || u)
? (f.push(n || u, 1), (r = 2))
: 2 === r && '...' === u && n
? f.push(n, 3)
: 2 === r && u && !n
? f.push(!0, 2, u)
: 4 === r && t && (f.push(n || u, 2, t), (t = '')),
(u = '')
},
s = 0;
s < n.length;
s++
) {
s && (1 === r && p(), p(s))
for (var i = 0; i < n[s].length; i++)
(e = n[s][i]),
1 === r
? '<' === e
? (p(), (f = [f]), (r = 3))
: (u += e)
: o
? e === o
? (o = '')
: (u += e)
: '"' === e || "'" === e
? (o = e)
: '>' === e
? (p(), (r = 1))
: r &&
('=' === e
? ((r = 4), (t = u), (u = ''))
: '/' === e
? (p(),
3 === r && (f = f[0]),
(r = f),
(f = f[0]).push(r, 4),
(r = 0))
: ' ' === e || '\t' === e || '\n' === e || '\r' === e
? (p(), (r = 2))
: (u += e))
}
return p(), f
},
t = 'function' == typeof Map,
r = t ? new Map() : {},
u = t
? function(n) {
var t = r.get(n)
return t || r.set(n, (t = e(n))), t
}
: function(n) {
for (var t = '', u = 0; u < n.length; u++)
t += n[u].length + '-' + n[u]
return r[t] || (r[t] = e(n))
}
return function(e) {
var t = n(this, u(e), arguments, [])
return t.length > 1 ? t : t[0]
}
})()
function h(type, props, ...children) {
return { type, props, children };
return { type, props, children }
}
export default htm.bind(h);
export default htm.bind(h)

View File

@ -6,7 +6,9 @@ import { line } from './line'
import { polyline } from './polyline'
import { polygon } from './polygon'
import { path } from './path'
import { pasition } from './pasition'
import { group } from './group'
import { animate } from './animate'
class SVG extends Group {
constructor(vdom) {
@ -14,10 +16,13 @@ class SVG extends Group {
this.vdom = vdom
const root = new Group()
const options = Object.assign({
x: 0,
y: 0
}, vdom.props)
const options = Object.assign(
{
x: 0,
y: 0
},
vdom.props
)
this.vdom.children.forEach(vdomChild => {
this.generate(root, vdomChild)
@ -27,7 +32,6 @@ class SVG extends Group {
root.y = Number(options.y)
this.add(root)
}
generate(parent, vdomChild) {
@ -57,7 +61,19 @@ class SVG extends Group {
break
case 'path':
parent.add(path(vdomChild.props))
const obj = path(vdomChild.props)
parent.add(obj)
if (
vdomChild.children &&
vdomChild.children[0] &&
vdomChild.children[0].type === 'animate'
) {
animate(obj, vdomChild.children[0].props)
}
break
case 'pasition':
parent.add(pasition(vdomChild.props))
break
case 'g':

View File

@ -4,10 +4,14 @@ import { transform } from './parse-transform'
import { parseEvent } from './parse-event'
export function line(props) {
const obj = new Line(Number(props.x1), Number(props.y1), Number(props.x2), Number(props.y2), parseStyle(props))
const obj = new Line(
Number(props.x1),
Number(props.y1),
Number(props.x2),
Number(props.y2),
parseStyle(props)
)
transform(props, obj)
parseEvent(props, obj)
return obj
}
}

View File

@ -1,18 +1,25 @@
export function parseEvent(props, obj) {
if(!props) return
const tapHandler = props.bindtap || props.bindTap || props.onTap || props.ontap || props.onclick || props.onClick || props.bindclick || props.bindClick
if (tapHandler) {
if (!props) return
const tapHandler =
props.bindtap ||
props.bindTap ||
props.onTap ||
props.ontap ||
props.onclick ||
props.onClick ||
props.bindclick ||
props.bindClick
if (tapHandler) {
let _x = null,
_y = null
obj.on('touchstart', (evt) => {
obj.on('touchstart', evt => {
_x = evt.stageX
_y = evt.stageY
})
obj.on('touchend', (evt) => {
obj.on('touchend', evt => {
if (_x !== null) {
if (Math.abs(evt.stageX - _x) < 20 && Math.abs(evt.stageY - _y) < 20) {
tapHandler(evt)

View File

@ -1,19 +1,28 @@
//https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute
const map = {
'stroke': 'strokeStyle',
'fill': 'fillStyle',
stroke: 'strokeStyle',
fill: 'fillStyle',
'stroke-width': 'lineWidth'
}
const attrs = ['stroke', 'fill', 'stroke-width']
export function parseStyle(props) {
let style = {}
const cssText = props.style
if (!cssText) return
if (props['stroke-width']) {
style.lineWidth = props['stroke-width']
}
if (props['stroke']) {
style.strokeStyle = props['stroke']
}
if (props['fill']) {
style.fillStyle = props['fill']
}
if (!cssText) return style
let cssTxt = cssText.replace(/\/\*(.|\s)*?\*\//g, ' ').replace(/\s+/g, ' ')
let style = {},
[a, b, rule] = cssTxt.match(/ ?(.*?) ?{([^}]*)}/) || [a, b, cssTxt]
let [a, b, rule] = cssTxt.match(/ ?(.*?) ?{([^}]*)}/) || [a, b, cssTxt]
//let cssToJs = s => s.replace(/\W+\w/g, match => match.slice(-1).toUpperCase())
let properties = rule

View File

@ -2,23 +2,23 @@ import mt from '../render/base/matrix-transform'
import Matrix2D from '../render/base/matrix2d'
function parse(a) {
a = a.replace(/,/g,' ').replace(/\s+/g,',')
const data = {};
a = a.replace(/,/g, ' ').replace(/\s+/g, ',')
const data = {}
const order = []
for (let i in a = a.match(/(\w+\((\-?\d+\.?\d*e?\-?\d*,?)+\))+/g)) {
const c = a[i].match(/[\w\.\-]+/g);
for (let i in (a = a.match(/(\w+\((\-?\d+\.?\d*e?\-?\d*,?)+\))+/g))) {
const c = a[i].match(/[\w\.\-]+/g)
const key = c.shift()
order.push(key)
data[key] = c;
data[key] = c
}
return {
order: order,
data: data
};
}
}
export function transform(props, target){
if(!props) return
export function transform(props, target) {
if (!props) return
if (props.transform) {
const obj = parse(props.transform)
@ -26,11 +26,10 @@ export function transform(props, target){
obj.order.forEach(prop => {
if (prop === 'rotate') {
obj.data[prop][0] *= Math.PI / 180
if(obj.data[prop].length>1){
target.originX = obj.data[prop][1]*-1
target.originY = obj.data[prop][2]*-1
if (obj.data[prop].length > 1) {
target.originX = obj.data[prop][1] * -1
target.originY = obj.data[prop][2] * -1
}
}
args.push(mt[prop].apply(null, obj.data[prop]))
})
@ -40,7 +39,7 @@ export function transform(props, target){
const t = {}
Matrix2D.decompose(mts.a, mts.b, mts.c, mts.d, mts.e, mts.f, t)
target.rotation = t.rotation * 180 / Math.PI
target.rotation = (t.rotation * 180) / Math.PI
target.x += parseFloat(t.x)
target.y += t.y
@ -51,8 +50,8 @@ export function transform(props, target){
target.skewY = t.skewY
}
if(props.width && props.height){
if (props.width && props.height) {
target.width = parseFloat(props.width)
target.height = parseFloat(props.height)
}
}
}

View File

@ -0,0 +1,65 @@
import Path from '../render/display/shape/path'
import { parseStyle } from './parse-style'
import { transform } from './parse-transform'
import { parseEvent } from './parse-event'
import pathTransition from '../pasition/index'
import color from '../common/color'
import { toSVGString } from '../common/util'
export function pasition(props) {
const lerp = color.lerp
const obj = new Path(props.from, parseStyle(props))
const fs = props['from-stroke']
const ts = props['to-stroke']
const ff = props['from-fill']
const tf = props['to-fill']
if (fs) {
obj.option.strokeStyle = fs
}
if (ff) {
obj.option.fillStyle = ff
}
obj.pasitionTo = props.to
obj.pasitionFrom = props.from
transform(props, obj)
parseEvent(props, obj)
let stage,
isFrom = true,
animating = false
obj.toggle = () => {
if (animating) return
pathTransition.animate({
from: isFrom ? props.from : props.to,
to: isFrom ? props.to : props.from,
duration:
typeof props.duration !== 'undefined' ? Number(props.duration) : 600,
easing: function(v) {
return v
},
begin: function() {
stage = obj.stage
animating = true
},
progress: function(shapes, percent) {
obj.d = toSVGString(shapes)
percent *= 100
if (isFrom) {
fs && (obj.option.strokeStyle = lerp(fs, ts, percent))
ff && (obj.option.fillStyle = lerp(ff, tf, percent))
} else {
fs && (obj.option.strokeStyle = lerp(ts, fs, percent))
ff && (obj.option.fillStyle = lerp(tf, ff, percent))
}
stage.update()
//
},
end: function(shapes) {
isFrom = !isFrom
animating = false
}
})
}
return obj
}

View File

@ -8,4 +8,4 @@ export function path(props) {
transform(props, obj)
parseEvent(props, obj)
return obj
}
}

View File

@ -4,9 +4,12 @@ import { transform } from './parse-transform'
import { parseEvent } from './parse-event'
export function polygon(props) {
const points = props.points.split(/\s+|,/).filter(item => item!=='').map(item=>Number(item))
const points = props.points
.split(/\s+|,/)
.filter(item => item !== '')
.map(item => Number(item))
const obj = new Polygon(points, parseStyle(props))
transform(props, obj)
parseEvent(props, obj)
return obj
}
}

View File

@ -9,4 +9,4 @@ export function polyline(props) {
transform(props, obj)
parseEvent(props, obj)
return obj
}
}

View File

@ -4,21 +4,26 @@ import { transform } from './parse-transform'
import { parseEvent } from './parse-event'
export function rect(props) {
const options = Object.assign(
{
width: 0,
height: 0,
x: 0,
y: 0
},
props
)
const options = Object.assign({
width: 0,
height: 0,
x: 0,
y: 0
}, props)
const rect = new Rect(Number(options.width), Number(options.height), parseStyle(props))
const rect = new Rect(
Number(options.width),
Number(options.height),
parseStyle(props)
)
rect.x = Number(options.x)
rect.y = Number(options.y)
transform(props, rect)
parseEvent(props, rect)
return rect
}
return rect
}