fixes for NodeJS env

This commit is contained in:
Anton Lavrenov 2017-10-11 12:17:54 +04:00
parent 980d9a5db6
commit 8488175474
13 changed files with 453 additions and 415 deletions

522
.eslintrc
View File

@ -1,307 +1,219 @@
{ {
"extends": "eslint:recommended", "extends": "eslint:recommended",
"env": { "env": {
"browser": true, "browser": true,
"node": true "node": true
}, },
"rules": { "rules": {
"no-alert": 0, "no-alert": 0,
"no-array-constructor": 2, "no-array-constructor": 2,
"no-bitwise": 0, "no-bitwise": 0,
"no-caller": 2, "no-caller": 2,
"no-catch-shadow": 2, "no-catch-shadow": 2,
"comma-dangle": 2, "comma-dangle": 2,
"no-underscore-dangle": 0, "no-underscore-dangle": 0,
"no-cond-assign": 2, "no-cond-assign": 2,
"no-console": 0, "no-console": 0,
"no-constant-condition": 0, "no-constant-condition": 0,
"no-continue": 0, "no-continue": 0,
"no-control-regex": 2, "no-control-regex": 2,
"no-debugger": 2, "no-debugger": 2,
"no-delete-var": 2, "no-delete-var": 2,
"no-div-regex": 0, "no-div-regex": 0,
"no-dupe-keys": 2, "no-dupe-keys": 2,
"no-dupe-args": 2, "no-dupe-args": 2,
"no-duplicate-case": 2, "no-duplicate-case": 2,
"no-else-return": 0, "no-else-return": 0,
"no-empty": 2, "no-empty": 2,
"no-empty-class": 0, "no-empty-class": 0,
"no-empty-character-class": 2, "no-empty-character-class": 2,
"no-labels": 2, "no-labels": 2,
"no-eq-null": 2, "no-eq-null": 2,
"no-eval": 2, "no-eval": 2,
"no-ex-assign": 2, "no-ex-assign": 2,
"no-extend-native": 2, "no-extend-native": 2,
"no-extra-bind": 2, "no-extra-bind": 2,
"no-extra-boolean-cast": 2, "no-extra-boolean-cast": 2,
"no-extra-parens": 0, "no-extra-parens": 0,
"no-extra-semi": 2, "no-extra-semi": 2,
"no-fallthrough": 2, "no-fallthrough": 2,
"no-floating-decimal": 0, "no-floating-decimal": 0,
"no-func-assign": 2, "no-func-assign": 2,
"no-implied-eval": 2, "no-implied-eval": 2,
"no-inline-comments": 0, "no-inline-comments": 0,
"no-inner-declarations": [ "no-inner-declarations": [2, "functions"],
2, "no-invalid-regexp": 2,
"functions" "no-irregular-whitespace": 2,
], "no-iterator": 2,
"no-invalid-regexp": 2, "no-label-var": 2,
"no-irregular-whitespace": 2, "no-lone-blocks": 2,
"no-iterator": 2, "no-lonely-if": 0,
"no-label-var": 2, "no-loop-func": 2,
"no-lone-blocks": 2, "no-mixed-requires": [1, false],
"no-lonely-if": 0, "no-mixed-spaces-and-tabs": [2, false],
"no-loop-func": 2, "linebreak-style": [1, "unix"],
"no-mixed-requires": [ "no-multi-spaces": 2,
1, "no-multi-str": 2,
false "no-multiple-empty-lines": [
], 1,
"no-mixed-spaces-and-tabs": [ {
2, "max": 3
false }
], ],
"linebreak-style": [ "no-native-reassign": 2,
1, "no-negated-in-lhs": 2,
"unix" "no-nested-ternary": 0,
], "no-new": 2,
"no-multi-spaces": 2, "no-new-func": 2,
"no-multi-str": 2, "no-new-object": 2,
"no-multiple-empty-lines": [ "no-new-require": 0,
1, "no-new-wrappers": 2,
{ "no-obj-calls": 2,
"max": 3 "no-octal": 2,
} "no-octal-escape": 2,
], "no-param-reassign": 0,
"no-native-reassign": 2, "no-path-concat": 0,
"no-negated-in-lhs": 2, "no-plusplus": 0,
"no-nested-ternary": 0, "no-process-env": 0,
"no-new": 2, "no-process-exit": 2,
"no-new-func": 2, "no-proto": 2,
"no-new-object": 2, "no-redeclare": 2,
"no-new-require": 0, "no-regex-spaces": 2,
"no-new-wrappers": 2, "no-reserved-keys": 0,
"no-obj-calls": 2, "no-restricted-modules": 0,
"no-octal": 2, "no-return-assign": 0,
"no-octal-escape": 2, "no-script-url": 2,
"no-param-reassign": 0, "no-self-compare": 0,
"no-path-concat": 0, "no-sequences": 2,
"no-plusplus": 0, "no-shadow": 2,
"no-process-env": 0, "no-shadow-restricted-names": 2,
"no-process-exit": 2, "no-spaced-func": 2,
"no-proto": 2, "no-sparse-arrays": 2,
"no-redeclare": 2, "no-sync": 0,
"no-regex-spaces": 2, "no-ternary": 0,
"no-reserved-keys": 0, "no-trailing-spaces": 2,
"no-restricted-modules": 0, "no-throw-literal": 1,
"no-return-assign": 0, "no-undef": 2,
"no-script-url": 2, "no-undef-init": 2,
"no-self-compare": 0, "no-undefined": 0,
"no-sequences": 2, "no-unneeded-ternary": 2,
"no-shadow": 2, "no-unreachable": 2,
"no-shadow-restricted-names": 2, "no-unused-expressions": 2,
"no-spaced-func": 2, "no-unused-vars": [
"no-sparse-arrays": 2, 2,
"no-sync": 0, {
"no-ternary": 0, "vars": "all",
"no-trailing-spaces": 2, "args": "after-used"
"no-throw-literal": 1, }
"no-undef": 2, ],
"no-undef-init": 2, "no-use-before-define": 2,
"no-undefined": 0, "no-void": 0,
"no-unneeded-ternary": 2, "no-var": 0,
"no-unreachable": 2, "prefer-const": 0,
"no-unused-expressions": 2, "no-warning-comments": [
"no-unused-vars": [ 0,
2, {
{ "terms": ["todo", "fixme", "xxx"],
"vars": "all", "location": "start"
"args": "after-used" }
} ],
], "no-with": 2,
"no-use-before-define": 2, "accessor-pairs": 0,
"no-void": 0, "block-scoped-var": 0,
"no-var": 0, "brace-style": [0, "1tbs"],
"prefer-const": 0, "camelcase": 0,
"no-warning-comments": [ "comma-spacing": 2,
0, "comma-style": 0,
{ "complexity": [1, 11],
"terms": [ "computed-property-spacing": [0, "never"],
"todo", "consistent-return": 1,
"fixme", "consistent-this": [0, "that"],
"xxx" "curly": [2, "all"],
], "default-case": 0,
"location": "start" "dot-location": 0,
} "dot-notation": [
], 2,
"no-with": 2, {
"accessor-pairs": 0, "allowKeywords": true
"block-scoped-var": 0, }
"brace-style": [ ],
0, "eol-last": 0,
"1tbs" "eqeqeq": 2,
], "func-names": 0,
"camelcase": 0, "func-style": [1, "declaration"],
"comma-spacing": 2, "generator-star": 0,
"comma-style": 0, "generator-star-spacing": 0,
"complexity": [ "guard-for-in": 1,
1, "handle-callback-err": 2,
11 "indent": 0,
], "key-spacing": [
"computed-property-spacing": [ 2,
0, {
"never" "beforeColon": false,
], "afterColon": true
"consistent-return": 1, }
"consistent-this": [ ],
0, "lines-around-comment": 0,
"that" "max-depth": [2, 5],
], "max-len": [2, 320, 4],
"curly": [ "max-nested-callbacks": [2, 2],
2, "max-params": [1, 8],
"all" "max-statements": [1, 20],
], "new-cap": 0,
"default-case": 0, "new-parens": 2,
"dot-location": 0, "newline-after-var": 0,
"dot-notation": [ "object-curly-spacing": [0, "never"],
2, "object-shorthand": 0,
{ "one-var": 0,
"allowKeywords": true "operator-assignment": [0, "always"],
} "operator-linebreak": 0,
], "padded-blocks": 0,
"eol-last": 0, "quote-props": 0,
"eqeqeq": 2, "quotes": [2, "single"],
"func-names": 0, "radix": 0,
"func-style": [ "semi": 2,
1, "semi-spacing": [
"declaration" 2,
], {
"generator-star": 0, "before": false,
"generator-star-spacing": 0, "after": true
"guard-for-in": 1, }
"handle-callback-err": 2, ],
"indent": 0, "sort-vars": 0,
"key-spacing": [ "space-after-function-name": [0, "never"],
2, "space-after-keywords": [0, "always"],
{ "space-before-blocks": [0, "always"],
"beforeColon": false, "space-before-function-paren": [0, "always"],
"afterColon": true "space-before-function-parentheses": [0, "always"],
} "space-in-brackets": [0, "never"],
], "space-in-parens": [0, "never"],
"lines-around-comment": 0, "max-statements": [1, 30],
"max-depth": [ "space-infix-ops": 2,
2, "keyword-spacing": 0,
5 "space-unary-ops": [
], 2,
"max-len": [ {
2, "words": true,
320, "nonwords": false
4 }
], ],
"max-nested-callbacks": [ "spaced-comment": 0,
2, "spaced-line-comment": [0, "always"],
2 "strict": [2, "function"],
], "use-isnan": 2,
"max-params": [ "valid-jsdoc": 0,
1, "valid-typeof": 2,
8 "vars-on-top": 0,
], "wrap-iife": 0,
"max-statements": [ "wrap-regex": 0,
1, "yoda": [2, "never"]
20 },
], "globals": {
"new-cap": 0, "Konva": false,
"new-parens": 2, "define": false,
"newline-after-var": 0, "test": false,
"object-curly-spacing": [ "assert": false,
0, "addStage": false,
"never" "suite": false
], }
"object-shorthand": 0,
"one-var": 0,
"operator-assignment": [
0,
"always"
],
"operator-linebreak": 0,
"padded-blocks": 0,
"quote-props": 0,
"quotes": [
2,
"single"
],
"radix": 0,
"semi": 2,
"semi-spacing": [
2,
{
"before": false,
"after": true
}
],
"sort-vars": 0,
"space-after-function-name": [
0,
"never"
],
"space-after-keywords": [
0,
"always"
],
"space-before-blocks": [
0,
"always"
],
"space-before-function-paren": [
0,
"always"
],
"space-before-function-parentheses": [
0,
"always"
],
"space-in-brackets": [
0,
"never"
],
"space-in-parens": [
0,
"never"
],
"space-infix-ops": 2,
"keyword-spacing": 0,
"space-unary-ops": [
2,
{
"words": true,
"nonwords": false
}
],
"spaced-comment": 0,
"spaced-line-comment": [
0,
"always"
],
"strict": [
2,
"function"
],
"use-isnan": 2,
"valid-jsdoc": 0,
"valid-typeof": 2,
"vars-on-top": 0,
"wrap-iife": 0,
"wrap-regex": 0,
"yoda": [
2,
"never"
]
},
"globals": {
"Konva": false,
"define": false,
"test": false,
"assert": false,
"addStage": false,
"suite": false
}
} }

1
.gitignore vendored
View File

@ -9,6 +9,7 @@ homedocs
jsdoc-template jsdoc-template
api api
test/sandbox.html test/sandbox.html
package-lock.json
*.zip *.zip
# Numerous always-ignore extensions # Numerous always-ignore extensions

View File

@ -4,6 +4,11 @@ This project adheres to [Semantic Versioning](http://semver.org/).
## [Not released][Not released] ## [Not released][Not released]
## [1.7.1][2017-10-11]
### Changed
- Konva for browser env and Konva for nodejs env are separate packages now. You can use `konva-node` for NodeJS env.
## [1.7.0][2017-10-08] ## [1.7.0][2017-10-08]
### Fixed ### Fixed

22
konva-node/index.js Normal file
View File

@ -0,0 +1,22 @@
var Konva = require('konva-dev');
var Canvas = require('canvas');
Konva.window = {
Image: Canvas.Image,
devicePixelRatio: 1
};
Konva.document = {
createElement: function() {},
documentElement: {
addEventListener: function() {}
}
};
// Konva.window = new JSDOM(
// '<!DOCTYPE html><html><head></head><body></body></html>'
// ).window;
// Konva.document = Konva.window.document;
// Konva.window.Image = Canvas.Image;
Konva._nodeCanvas = Canvas;
module.exports = Konva;

31
konva-node/package.json Normal file
View File

@ -0,0 +1,31 @@
{
"name": "konva-node",
"version": "0.5.0",
"description": "Konva framework for NodeJS env",
"main": "index.js",
"files": [
"index.js"
],
"typings": "./node_modules/konva/konva.d.ts",
"scripts": {},
"keywords": [
"canvas",
"animations",
"graphic",
"html5"
],
"author": "Anton Lavrenov",
"bugs": {
"url": "https://github.com/konvajs/konva/issues"
},
"homepage": "http://konvajs.github.io/",
"repository": {
"type": "git",
"url": "git://github.com/konvajs/konva.git"
},
"license": "MIT",
"dependencies": {
"canvas": "^1.6.7",
"konva": "^1.7.0"
}
}

View File

@ -1,4 +1,10 @@
var fs = require('fs'), Konva = require('../dist/konva-dev'); var fs = require('fs');
// relative path here
// but you will need just require('konva-node');
var Konva = require('../konva-node');
// console.log(Konva.Util.c);
// Create stage. Container parameter is not required in NodeJS. // Create stage. Container parameter is not required in NodeJS.
var stage = new Konva.Stage({ var stage = new Konva.Stage({
@ -13,7 +19,7 @@ var rect = new Konva.Rect({
height: 100, height: 100,
x: 50, x: 50,
y: 50, y: 50,
fill: 'green' fill: 'white'
}); });
var text = new Konva.Text({ var text = new Konva.Text({
text: 'Generated inside node js', text: 'Generated inside node js',

View File

@ -1,19 +1,27 @@
(function() { (function() {
'use strict'; 'use strict';
// calculate pixel ratio // calculate pixel ratio
var canvas = Konva.Util.createCanvasElement(),
context = canvas.getContext('2d'), var _pixelRatio;
_pixelRatio = (function() { function getDevicePixelRatio() {
var devicePixelRatio = Konva.window.devicePixelRatio || 1, if (_pixelRatio) {
backingStoreRatio = return _pixelRatio;
context.webkitBackingStorePixelRatio || }
context.mozBackingStorePixelRatio || var canvas = Konva.Util.createCanvasElement(),
context.msBackingStorePixelRatio || context = canvas.getContext('2d'),
context.oBackingStorePixelRatio || _pixelRatio = (function() {
context.backingStorePixelRatio || var devicePixelRatio = Konva.window.devicePixelRatio || 1,
1; backingStoreRatio =
return devicePixelRatio / backingStoreRatio; context.webkitBackingStorePixelRatio ||
})(); context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio ||
1;
return devicePixelRatio / backingStoreRatio;
})();
return _pixelRatio;
}
/** /**
* Canvas Renderer constructor * Canvas Renderer constructor
@ -39,7 +47,8 @@
init: function(config) { init: function(config) {
var conf = config || {}; var conf = config || {};
var pixelRatio = conf.pixelRatio || Konva.pixelRatio || _pixelRatio; var pixelRatio =
conf.pixelRatio || Konva.pixelRatio || getDevicePixelRatio();
this.pixelRatio = pixelRatio; this.pixelRatio = pixelRatio;
this._canvas = Konva.Util.createCanvasElement(); this._canvas = Konva.Util.createCanvasElement();
@ -102,7 +111,8 @@
this.width = this._canvas.width = width * this.pixelRatio; this.width = this._canvas.width = width * this.pixelRatio;
this._canvas.style.width = width + 'px'; this._canvas.style.width = width + 'px';
var pixelRatio = this.pixelRatio, _context = this.getContext()._context; var pixelRatio = this.pixelRatio,
_context = this.getContext()._context;
_context.scale(pixelRatio, pixelRatio); _context.scale(pixelRatio, pixelRatio);
}, },
/** /**
@ -115,7 +125,8 @@
// take into account pixel ratio // take into account pixel ratio
this.height = this._canvas.height = height * this.pixelRatio; this.height = this._canvas.height = height * this.pixelRatio;
this._canvas.style.height = height + 'px'; this._canvas.style.height = height + 'px';
var pixelRatio = this.pixelRatio, _context = this.getContext()._context; var pixelRatio = this.pixelRatio,
_context = this.getContext()._context;
_context.scale(pixelRatio, pixelRatio); _context.scale(pixelRatio, pixelRatio);
}, },
/** /**
@ -173,7 +184,8 @@
Konva.SceneCanvas = function(config) { Konva.SceneCanvas = function(config) {
var conf = config || {}; var conf = config || {};
var width = conf.width || 0, height = conf.height || 0; var width = conf.width || 0,
height = conf.height || 0;
Konva.Canvas.call(this, conf); Konva.Canvas.call(this, conf);
this.context = new Konva.SceneContext(this); this.context = new Konva.SceneContext(this);
@ -184,7 +196,8 @@
Konva.HitCanvas = function(config) { Konva.HitCanvas = function(config) {
var conf = config || {}; var conf = config || {};
var width = conf.width || 0, height = conf.height || 0; var width = conf.width || 0,
height = conf.height || 0;
Konva.Canvas.call(this, conf); Konva.Canvas.call(this, conf);
this.context = new Konva.HitContext(this); this.context = new Konva.HitContext(this);

View File

@ -17,7 +17,8 @@
// methods // methods
_drag: function(evt) { _drag: function(evt) {
var dd = Konva.DD, node = dd.node; var dd = Konva.DD,
node = dd.node;
if (node) { if (node) {
if (!dd.isDragging) { if (!dd.isDragging) {
var pos = node.getStage().getPointerPosition(); var pos = node.getStage().getPointerPosition();
@ -65,7 +66,9 @@
} }
}, },
_endDragBefore: function(evt) { _endDragBefore: function(evt) {
var dd = Konva.DD, node = dd.node, layer; var dd = Konva.DD,
node = dd.node,
layer;
if (node) { if (node) {
layer = node.getLayer(); layer = node.getLayer();
@ -172,7 +175,8 @@
* @memberof Konva.Node.prototype * @memberof Konva.Node.prototype
*/ */
Konva.Node.prototype.stopDrag = function() { Konva.Node.prototype.stopDrag = function() {
var dd = Konva.DD, evt = {}; var dd = Konva.DD,
evt = {};
dd._endDragBefore(evt); dd._endDragBefore(evt);
dd._endDragAfter(evt); dd._endDragAfter(evt);
}; };
@ -310,13 +314,15 @@
* node.draggable(false); * node.draggable(false);
*/ */
var html = Konva.document.documentElement; if (Konva.isBrowser) {
html.addEventListener('mouseup', Konva.DD._endDragBefore, true); var html = Konva.document.documentElement;
html.addEventListener('touchend', Konva.DD._endDragBefore, true); html.addEventListener('mouseup', Konva.DD._endDragBefore, true);
html.addEventListener('touchend', Konva.DD._endDragBefore, true);
html.addEventListener('mousemove', Konva.DD._drag); html.addEventListener('mousemove', Konva.DD._drag);
html.addEventListener('touchmove', Konva.DD._drag); html.addEventListener('touchmove', Konva.DD._drag);
html.addEventListener('mouseup', Konva.DD._endDragAfter, false); html.addEventListener('mouseup', Konva.DD._endDragAfter, false);
html.addEventListener('touchend', Konva.DD._endDragAfter, false); html.addEventListener('touchend', Konva.DD._endDragAfter, false);
}
})(); })();

View File

@ -28,7 +28,7 @@
*/ */
// runtime check for already included Konva // runtime check for already included Konva
(function(global) { (function() {
'use strict'; 'use strict';
/** /**
* @namespace Konva * @namespace Konva
@ -49,6 +49,10 @@
listenClickTap: false, listenClickTap: false,
inDblClickWindow: false, inDblClickWindow: false,
isBrowser:
typeof window !== 'undefined' &&
{}.toString.call(window) === '[object Window]',
// configurations // configurations
enableTrace: false, enableTrace: false,
traceArrMax: 100, traceArrMax: 100,
@ -196,12 +200,14 @@
_parseUA: function(userAgent) { _parseUA: function(userAgent) {
var ua = userAgent.toLowerCase(), var ua = userAgent.toLowerCase(),
// jQuery UA regex // jQuery UA regex
match = /(chrome)[ /]([\w.]+)/.exec(ua) || match =
/(webkit)[ /]([\w.]+)/.exec(ua) || /(chrome)[ /]([\w.]+)/.exec(ua) ||
/(opera)(?:.*version|)[ /]([\w.]+)/.exec(ua) || /(webkit)[ /]([\w.]+)/.exec(ua) ||
/(msie) ([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ /]([\w.]+)/.exec(ua) ||
(ua.indexOf('compatible') < 0 && /(msie) ([\w.]+)/.exec(ua) ||
/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua)) || [], (ua.indexOf('compatible') < 0 &&
/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua)) ||
[],
// adding mobile flag as well // adding mobile flag as well
mobile = !!userAgent.match( mobile = !!userAgent.match(
/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i /Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i
@ -221,9 +227,10 @@
UA: undefined UA: undefined
}; };
var glob = typeof global !== 'undefined' var glob =
? global typeof global !== 'undefined'
: typeof window !== 'undefined' ? global
: typeof window !== 'undefined'
? window ? window
: typeof WorkerGlobalScope !== 'undefined' ? self : {}; : typeof WorkerGlobalScope !== 'undefined' ? self : {};
@ -239,25 +246,6 @@
Konva.global = glob; Konva.global = glob;
if (typeof exports === 'object') { if (typeof exports === 'object') {
// runtime-check for browserify and nw.js (node-webkit)
if (glob.window && glob.window.document) {
Konva.document = glob.window.document;
Konva.window = glob.window;
} else {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like enviroments that support module.exports,
// like Node.
var Canvas = require('canvas');
var JSDOM = require('jsdom').JSDOM;
Konva.window = new JSDOM(
'<!DOCTYPE html><html><head></head><body></body></html>'
).window;
Konva.document = Konva.window.document;
Konva.window.Image = Canvas.Image;
Konva._nodeCanvas = Canvas;
Konva.isNode = true;
}
module.exports = Konva; module.exports = Konva;
return; return;
} else if (typeof define === 'function' && define.amd) { } else if (typeof define === 'function' && define.amd) {
@ -268,4 +256,4 @@
} }
Konva.document = document; Konva.document = document;
Konva.window = window; Konva.window = window;
})(typeof global !== 'undefined' ? global : window); })();

View File

@ -177,7 +177,9 @@
* @memberof Konva.Stage.prototype * @memberof Konva.Stage.prototype
*/ */
clear: function() { clear: function() {
var layers = this.children, len = layers.length, n; var layers = this.children,
len = layers.length,
n;
for (n = 0; n < len; n++) { for (n = 0; n < len; n++) {
layers[n].clear(); layers[n].clear();
@ -386,7 +388,10 @@
// draw layer and append canvas to container // draw layer and append canvas to container
layer.draw(); layer.draw();
this.content.appendChild(layer.canvas._canvas);
if (Konva.isBrowser) {
this.content.appendChild(layer.canvas._canvas);
}
// chainable // chainable
return this; return this;
@ -406,6 +411,9 @@
return this.getChildren(); return this.getChildren();
}, },
_bindContentEvents: function() { _bindContentEvents: function() {
if (!Konva.isBrowser) {
return;
}
for (var n = 0; n < eventsLength; n++) { for (var n = 0; n < eventsLength; n++) {
addEvent(this, EVENTS[n]); addEvent(this, EVENTS[n]);
} }
@ -660,7 +668,8 @@
}, },
_touchmove: function(evt) { _touchmove: function(evt) {
this._setPointerPosition(evt); this._setPointerPosition(evt);
var dd = Konva.DD, shape; var dd = Konva.DD,
shape;
if (!Konva.isDragging()) { if (!Konva.isDragging()) {
shape = this.getIntersection(this.getPointerPosition()); shape = this.getIntersection(this.getPointerPosition());
if (shape && shape.isListening()) { if (shape && shape.isListening()) {
@ -692,7 +701,9 @@
this._fire(CONTENT_WHEEL, { evt: evt }); this._fire(CONTENT_WHEEL, { evt: evt });
}, },
_setPointerPosition: function(evt) { _setPointerPosition: function(evt) {
var contentPosition = this._getContentPosition(), x = null, y = null; var contentPosition = this._getContentPosition(),
x = null,
y = null;
evt = evt ? evt : window.event; evt = evt ? evt : window.event;
// touch events // touch events
@ -726,14 +737,18 @@
}; };
}, },
_buildDOM: function() { _buildDOM: function() {
// the buffer canvas pixel ratio must be 1 because it is used as an
// intermediate canvas before copying the result onto a scene canvas.
// not setting it to 1 will result in an over compensation
this.bufferCanvas = new Konva.SceneCanvas();
this.bufferHitCanvas = new Konva.HitCanvas({ pixelRatio: 1 });
if (!Konva.isBrowser) {
return;
}
var container = this.getContainer(); var container = this.getContainer();
if (!container) { if (!container) {
if (Konva.Util.isBrowser()) { throw 'Stage has no container. A container is required.';
throw 'Stage has no container. A container is required.';
} else {
// automatically create element for jsdom in nodejs env
container = Konva.document.createElement(DIV);
}
} }
// clear content inside container // clear content inside container
container.innerHTML = EMPTY_STRING; container.innerHTML = EMPTY_STRING;
@ -743,18 +758,16 @@
this.content.style.position = RELATIVE; this.content.style.position = RELATIVE;
this.content.className = KONVA_CONTENT; this.content.className = KONVA_CONTENT;
this.content.setAttribute('role', 'presentation'); this.content.setAttribute('role', 'presentation');
container.appendChild(this.content);
// the buffer canvas pixel ratio must be 1 because it is used as an container.appendChild(this.content);
// intermediate canvas before copying the result onto a scene canvas.
// not setting it to 1 will result in an over compensation
this.bufferCanvas = new Konva.SceneCanvas();
this.bufferHitCanvas = new Konva.HitCanvas({ pixelRatio: 1 });
this._resizeDOM(); this._resizeDOM();
}, },
_onContent: function(typesStr, handler) { _onContent: function(typesStr, handler) {
var types = typesStr.split(SPACE), len = types.length, n, baseEvent; var types = typesStr.split(SPACE),
len = types.length,
n,
baseEvent;
for (n = 0; n < len; n++) { for (n = 0; n < len; n++) {
baseEvent = types[n]; baseEvent = types[n];

View File

@ -8,7 +8,9 @@
* @memberof Konva * @memberof Konva
*/ */
Konva.Collection = function() { Konva.Collection = function() {
var args = [].slice.call(arguments), length = args.length, i = 0; var args = [].slice.call(arguments),
length = args.length,
i = 0;
this.length = length; this.length = length;
for (; i < length; i++) { for (; i < length; i++) {
@ -40,7 +42,9 @@
* @memberof Konva.Collection.prototype * @memberof Konva.Collection.prototype
*/ */
Konva.Collection.prototype.toArray = function() { Konva.Collection.prototype.toArray = function() {
var arr = [], len = this.length, n; var arr = [],
len = this.length,
n;
for (n = 0; n < len; n++) { for (n = 0; n < len; n++) {
arr.push(this[n]); arr.push(this[n]);
@ -54,7 +58,9 @@
* @param {Array} arr * @param {Array} arr
*/ */
Konva.Collection.toCollection = function(arr) { Konva.Collection.toCollection = function(arr) {
var collection = new Konva.Collection(), len = arr.length, n; var collection = new Konva.Collection(),
len = arr.length,
n;
for (n = 0; n < len; n++) { for (n = 0; n < len; n++) {
collection.push(arr[n]); collection.push(arr[n]);
@ -65,7 +71,8 @@
// map one method by it's name // map one method by it's name
Konva.Collection._mapMethod = function(methodName) { Konva.Collection._mapMethod = function(methodName) {
Konva.Collection.prototype[methodName] = function() { Konva.Collection.prototype[methodName] = function() {
var len = this.length, i; var len = this.length,
i;
var args = [].slice.call(arguments); var args = [].slice.call(arguments);
for (i = 0; i < len; i++) { for (i = 0; i < len; i++) {
@ -520,7 +527,8 @@
* other utils * other utils
*/ */
_hasMethods: function(obj) { _hasMethods: function(obj) {
var names = [], key; var names = [],
key;
for (key in obj) { for (key in obj) {
if (!obj.hasOwnProperty(key)) { if (!obj.hasOwnProperty(key)) {
@ -544,18 +552,15 @@
); );
}, },
createCanvasElement: function() { createCanvasElement: function() {
var canvas = Konva.isNode var canvas = Konva.isBrowser
? new Konva._nodeCanvas() ? Konva.document.createElement('canvas')
: Konva.document.createElement('canvas'); : new Konva._nodeCanvas();
// on some environments canvas.style is readonly // on some environments canvas.style is readonly
try { try {
canvas.style = canvas.style || {}; canvas.style = canvas.style || {};
} catch (e) {} } catch (e) {}
return canvas; return canvas;
}, },
isBrowser: function() {
return typeof exports !== 'object';
},
_isInDocument: function(el) { _isInDocument: function(el) {
while ((el = el.parentNode)) { while ((el = el.parentNode)) {
if (el == Konva.document) { if (el == Konva.document) {
@ -565,7 +570,11 @@
return false; return false;
}, },
_simplifyArray: function(arr) { _simplifyArray: function(arr) {
var retArr = [], len = arr.length, util = Konva.Util, n, val; var retArr = [],
len = arr.length,
util = Konva.Util,
n,
val;
for (n = 0; n < len; n++) { for (n = 0; n < len; n++) {
val = arr[n]; val = arr[n];
@ -866,7 +875,10 @@
return [p1x, p1y, p2x, p2y]; return [p1x, p1y, p2x, p2y];
}, },
_expandPoints: function(p, tension) { _expandPoints: function(p, tension) {
var len = p.length, allPoints = [], n, cp; var len = p.length,
allPoints = [],
n,
cp;
for (n = 2; n < len - 2; n += 2) { for (n = 2; n < len - 2; n += 2) {
cp = Konva.Util._getControlPoints( cp = Konva.Util._getControlPoints(
@ -940,7 +952,9 @@
pt.x, pt.x,
pt.y pt.y
); );
var px = proj[0], py = proj[1], pdist = proj[2]; var px = proj[0],
py = proj[1],
pdist = proj[2];
if (pdist < dist) { if (pdist < dist) {
pc.x = px; pc.x = px;
pc.y = py; pc.y = py;
@ -950,7 +964,9 @@
return pc; return pc;
}, },
_prepareArrayForTween: function(startArray, endArray, isClosed) { _prepareArrayForTween: function(startArray, endArray, isClosed) {
var n, start = [], end = []; var n,
start = [],
end = [];
if (startArray.length > endArray.length) { if (startArray.length > endArray.length) {
var temp = endArray; var temp = endArray;
endArray = startArray; endArray = startArray;

View File

@ -32,18 +32,24 @@
a = 0; a = 0;
// Find the largest radius // Find the largest radius
var rad, rMax = Math.sqrt(xMid * xMid + yMid * yMid); var rad,
rMax = Math.sqrt(xMid * xMid + yMid * yMid);
x = xSize - xMid; x = xSize - xMid;
y = ySize - yMid; y = ySize - yMid;
rad = Math.sqrt(x * x + y * y); rad = Math.sqrt(x * x + y * y);
rMax = rad > rMax ? rad : rMax; rMax = rad > rMax ? rad : rMax;
// We'll be uisng y as the radius, and x as the angle (theta=t) // We'll be uisng y as the radius, and x as the angle (theta=t)
var rSize = ySize, tSize = xSize, radius, theta; var rSize = ySize,
tSize = xSize,
radius,
theta;
// We want to cover all angles (0-360) and we need to convert to // We want to cover all angles (0-360) and we need to convert to
// radians (*PI/180) // radians (*PI/180)
var conversion = 360 / tSize * Math.PI / 180, sin, cos; var conversion = 360 / tSize * Math.PI / 180,
sin,
cos;
// var x1, x2, x1i, x2i, y1, y2, y1i, y2i, scale; // var x1, x2, x1i, x2i, y1, y2, y1i, y2i, scale;
@ -105,7 +111,8 @@
a = 0; a = 0;
// Find the largest radius // Find the largest radius
var rad, rMax = Math.sqrt(xMid * xMid + yMid * yMid); var rad,
rMax = Math.sqrt(xMid * xMid + yMid * yMid);
x = xSize - xMid; x = xSize - xMid;
y = ySize - yMid; y = ySize - yMid;
rad = Math.sqrt(x * x + y * y); rad = Math.sqrt(x * x + y * y);
@ -154,7 +161,6 @@
//Konva.Filters.FromPolar = Konva.Util._FilterWrapDoubleBuffer(FromPolar); //Konva.Filters.FromPolar = Konva.Util._FilterWrapDoubleBuffer(FromPolar);
// create a temporary canvas for working - shared between multiple calls // create a temporary canvas for working - shared between multiple calls
var tempCanvas = Konva.Util.createCanvasElement();
/* /*
* Kaleidoscope Filter. * Kaleidoscope Filter.
@ -169,7 +175,8 @@
* node.kaleidoscopeAngle(45); * node.kaleidoscopeAngle(45);
*/ */
Konva.Filters.Kaleidoscope = function(imageData) { Konva.Filters.Kaleidoscope = function(imageData) {
var xSize = imageData.width, ySize = imageData.height; var xSize = imageData.width,
ySize = imageData.height;
var x, y, xoff, i, r, g, b, a, srcPos, dstPos; var x, y, xoff, i, r, g, b, a, srcPos, dstPos;
var power = Math.round(this.kaleidoscopePower()); var power = Math.round(this.kaleidoscopePower());
@ -181,6 +188,7 @@
} }
// Work with our shared buffer canvas // Work with our shared buffer canvas
var tempCanvas = Konva.Util.createCanvasElement();
tempCanvas.width = xSize; tempCanvas.width = xSize;
tempCanvas.height = ySize; tempCanvas.height = ySize;
var scratchData = tempCanvas var scratchData = tempCanvas
@ -206,7 +214,9 @@
// Copy the offset region to 0 // Copy the offset region to 0
// Depending on the size of filter and location of the offset we may need // Depending on the size of filter and location of the offset we may need
// to copy the section backwards to prevent it from rewriting itself // to copy the section backwards to prevent it from rewriting itself
var xStart = 0, xEnd = sectionSize, xDelta = 1; var xStart = 0,
xEnd = sectionSize,
xDelta = 1;
if (offset + minSectionSize > xSize) { if (offset + minSectionSize > xSize) {
xStart = sectionSize; xStart = sectionSize;
xEnd = 0; xEnd = 0;

View File

@ -37,8 +37,15 @@
'letterSpacing' 'letterSpacing'
], ],
// cached variables // cached variables
attrChangeListLen = ATTR_CHANGE_LIST.length, attrChangeListLen = ATTR_CHANGE_LIST.length;
var dummyContext;
function getDummyContext() {
if (dummyContext) {
return dummyContext;
}
dummyContext = Konva.Util.createCanvasElement().getContext(CONTEXT_2D); dummyContext = Konva.Util.createCanvasElement().getContext(CONTEXT_2D);
return dummyContext;
}
/** /**
* Text constructor * Text constructor
@ -140,7 +147,9 @@
// draw text lines // draw text lines
for (n = 0; n < textArrLen; n++) { for (n = 0; n < textArrLen; n++) {
var obj = textArr[n], text = obj.text, width = obj.width; var obj = textArr[n],
text = obj.text,
width = obj.width;
// horizontal alignment // horizontal alignment
context.save(); context.save();
@ -202,7 +211,8 @@
context.restore(); context.restore();
}, },
_hitFunc: function(context) { _hitFunc: function(context) {
var width = this.getWidth(), height = this.getHeight(); var width = this.getWidth(),
height = this.getHeight();
context.beginPath(); context.beginPath();
context.rect(0, 0, width, height); context.rect(0, 0, width, height);
@ -245,7 +255,7 @@
this.attrs.height === AUTO || this.attrs.height === undefined; this.attrs.height === AUTO || this.attrs.height === undefined;
return isAuto return isAuto
? this.getTextHeight() * this.textArr.length * this.getLineHeight() + ? this.getTextHeight() * this.textArr.length * this.getLineHeight() +
this.getPadding() * 2 this.getPadding() * 2
: this.attrs.height; : this.attrs.height;
}, },
/** /**
@ -267,7 +277,9 @@
return this.textHeight; return this.textHeight;
}, },
_getTextSize: function(text) { _getTextSize: function(text) {
var _context = dummyContext, fontSize = this.getFontSize(), metrics; var _context = getDummyContext(),
fontSize = this.getFontSize(),
metrics;
_context.save(); _context.save();
_context.font = this._getContextFont(); _context.font = this._getContextFont();
@ -314,7 +326,7 @@
var latterSpacing = this.getLetterSpacing(); var latterSpacing = this.getLetterSpacing();
var length = text.length; var length = text.length;
return ( return (
dummyContext.measureText(text).width + getDummyContext().measureText(text).width +
(length ? latterSpacing * (length - 1) : 0) (length ? latterSpacing * (length - 1) : 0)
); );
}, },
@ -336,8 +348,8 @@
wrapAtWord = wrap !== CHAR && shouldWrap; wrapAtWord = wrap !== CHAR && shouldWrap;
this.textArr = []; this.textArr = [];
dummyContext.save(); getDummyContext().save();
dummyContext.font = this._getContextFont(); getDummyContext().font = this._getContextFont();
for (var i = 0, max = lines.length; i < max; ++i) { for (var i = 0, max = lines.length; i < max; ++i) {
var line = lines[i]; var line = lines[i];
@ -352,7 +364,10 @@
* use binary search to find the longest substring that * use binary search to find the longest substring that
* that would fit in the specified width * that would fit in the specified width
*/ */
var low = 0, high = line.length, match = '', matchWidth = 0; var low = 0,
high = line.length,
match = '',
matchWidth = 0;
while (low < high) { while (low < high) {
var mid = (low + high) >>> 1, var mid = (low + high) >>> 1,
substr = line.slice(0, mid + 1), substr = line.slice(0, mid + 1),
@ -425,7 +440,7 @@
break; break;
} }
} }
dummyContext.restore(); getDummyContext().restore();
this.textHeight = fontSize; this.textHeight = fontSize;
// var maxTextWidth = 0; // var maxTextWidth = 0;
// for(var j = 0; j < this.textArr.length; j++) { // for(var j = 0; j < this.textArr.length; j++) {