mirror of
https://github.com/niklasvh/html2canvas.git
synced 2023-08-10 21:13:10 +03:00
Library rewrite
This commit is contained in:
parent
b92d8cba24
commit
441d349948
.babelrc.eslintrc.flowconfig.gitignore.gitmodules.jshintrc.travis.ymlGruntfile.js
flow-typed
package.jsonsrc
BezierCurve.jsBounds.jsCanvasRenderer.jsColor.jsFeature.jsImageLoader.jsLength.jsLogger.jsNodeContainer.jsNodeParser.jsSize.jsStackingContext.jsTextBounds.jsTextContainer.jsUtil.jsVector.jsclone.jscolor.jscore.jsdummyimagecontainer.jsfabricfont.jsfontmetrics.jsframecontainer.jsgradientcontainer.jsimagecontainer.jsimageloader.jsindex.jslineargradientcontainer.jslog.jsnodecontainer.jsnodeparser.js
parsing
background.jsborder.jsborderRadius.jsdisplay.jsfloat.jsfont.jsletterSpacing.jspadding.jsposition.jstextDecoration.jstextTransform.jstransform.jszIndex.js
proxy.jsproxyimagecontainer.jspseudoelementcontainer.jsrenderer.jsrenderers
stackingcontext.jssupport.jssvgcontainer.jssvgnodecontainer.jstextcontainer.jsutils.jswebkitgradientcontainer.jsxhr.jstests
webpack.config.js
3
.babelrc
Normal file
3
.babelrc
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"presets": ["es2015", "flow"]
|
||||||
|
}
|
15
.eslintrc
Normal file
15
.eslintrc
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"parser": "babel-eslint",
|
||||||
|
"plugins": [
|
||||||
|
"prettier"
|
||||||
|
],
|
||||||
|
"rules": {
|
||||||
|
"prettier/prettier": ["error", {
|
||||||
|
"singleQuote": true,
|
||||||
|
"bracketSpacing": false,
|
||||||
|
"parser": "flow",
|
||||||
|
"tabWidth": 4,
|
||||||
|
"printWidth": 100
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
}
|
6
.flowconfig
Normal file
6
.flowconfig
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
[ignore]
|
||||||
|
[include]
|
||||||
|
[libs]
|
||||||
|
./flow-typed
|
||||||
|
[options]
|
||||||
|
[lints]
|
1
.gitignore
vendored
1
.gitignore
vendored
@ -1,3 +1,4 @@
|
|||||||
|
/dist
|
||||||
/nbproject/
|
/nbproject/
|
||||||
image.jpg
|
image.jpg
|
||||||
/.project
|
/.project
|
||||||
|
3
.gitmodules
vendored
3
.gitmodules
vendored
@ -1,3 +0,0 @@
|
|||||||
[submodule "src/fabric"]
|
|
||||||
path = src/fabric
|
|
||||||
url = https://github.com/kangax/fabric.js.git
|
|
19
.jshintrc
19
.jshintrc
@ -1,19 +0,0 @@
|
|||||||
{
|
|
||||||
"curly": true,
|
|
||||||
"eqeqeq": true,
|
|
||||||
"immed": true,
|
|
||||||
"latedef": false,
|
|
||||||
"newcap": true,
|
|
||||||
"noarg": true,
|
|
||||||
"sub": true,
|
|
||||||
"undef": true,
|
|
||||||
"boss": true,
|
|
||||||
"eqnull": true,
|
|
||||||
"browser": true,
|
|
||||||
"node": true,
|
|
||||||
"indent": 4,
|
|
||||||
"globals": {
|
|
||||||
"jQuery": true
|
|
||||||
},
|
|
||||||
"predef": ["Promise", "define"]
|
|
||||||
}
|
|
@ -8,9 +8,6 @@ env:
|
|||||||
- secure: YI+YbTOGf2x4fPMKW+KhJiZWswoXT6xOKGwLfsQsVwmFX1LerJouil5D5iYOQuL4FE3pNaoJSNakIsokJQuGKJMmnPc8rdhMZuBJBk6MRghurE2Xe9qBHfuUBPlfD61nARESm4WDcyMwM0QVYaOKeY6aIpZ91qbUbyc60EEx3C4=
|
- secure: YI+YbTOGf2x4fPMKW+KhJiZWswoXT6xOKGwLfsQsVwmFX1LerJouil5D5iYOQuL4FE3pNaoJSNakIsokJQuGKJMmnPc8rdhMZuBJBk6MRghurE2Xe9qBHfuUBPlfD61nARESm4WDcyMwM0QVYaOKeY6aIpZ91qbUbyc60EEx3C4=
|
||||||
addons:
|
addons:
|
||||||
sauce_connect: true
|
sauce_connect: true
|
||||||
before_script:
|
|
||||||
- npm install -g grunt-cli
|
|
||||||
- npm install -g uglify-js
|
|
||||||
notifications:
|
notifications:
|
||||||
webhooks:
|
webhooks:
|
||||||
urls:
|
urls:
|
||||||
|
216
Gruntfile.js
216
Gruntfile.js
@ -1,216 +0,0 @@
|
|||||||
/*global module:false*/
|
|
||||||
var _ = require('lodash'), path = require('path');
|
|
||||||
var proxy = require('html2canvas-proxy');
|
|
||||||
|
|
||||||
module.exports = function(grunt) {
|
|
||||||
|
|
||||||
var meta = {
|
|
||||||
banner: '/*\n <%= pkg.title || pkg.name %> <%= pkg.version %>' +
|
|
||||||
'<%= pkg.homepage ? " <" + pkg.homepage + ">" : "" %>' + '\n' +
|
|
||||||
' Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>' +
|
|
||||||
'\n\n Released under <%= _.pluck(pkg.licenses, "type").join(", ") %> License\n*/\n'
|
|
||||||
};
|
|
||||||
|
|
||||||
var browsers = {
|
|
||||||
chrome: {
|
|
||||||
browserName: "chrome",
|
|
||||||
platform: "Windows 7",
|
|
||||||
version: "39"
|
|
||||||
},
|
|
||||||
firefox: {
|
|
||||||
browserName: "firefox",
|
|
||||||
version: "15",
|
|
||||||
platform: "Windows 7"
|
|
||||||
},
|
|
||||||
ie9: {
|
|
||||||
browserName: "internet explorer",
|
|
||||||
version: "9",
|
|
||||||
platform: "Windows 7"
|
|
||||||
},
|
|
||||||
ie10: {
|
|
||||||
browserName: "internet explorer",
|
|
||||||
version: "10",
|
|
||||||
platform: "Windows 8"
|
|
||||||
},
|
|
||||||
ie11: {
|
|
||||||
browserName: "internet explorer",
|
|
||||||
version: "11",
|
|
||||||
platform: "Windows 8.1"
|
|
||||||
},
|
|
||||||
chromeOSX:{
|
|
||||||
browserName: "chrome",
|
|
||||||
platform: "OS X 10.8",
|
|
||||||
version: "39"
|
|
||||||
}
|
|
||||||
};
|
|
||||||
grunt.initConfig({
|
|
||||||
|
|
||||||
pkg: grunt.file.readJSON('package.json'),
|
|
||||||
|
|
||||||
browserify: {
|
|
||||||
dist: {
|
|
||||||
src: ['src/core.js'],
|
|
||||||
dest: 'dist/<%= pkg.name %>.js',
|
|
||||||
options: {
|
|
||||||
browserifyOptions: {
|
|
||||||
standalone: 'html2canvas'
|
|
||||||
},
|
|
||||||
banner: meta.banner,
|
|
||||||
plugin: [
|
|
||||||
[ "browserify-derequire" ]
|
|
||||||
]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
svg: {
|
|
||||||
src: [
|
|
||||||
'src/fabric/dist/fabric.js'
|
|
||||||
],
|
|
||||||
dest: 'dist/<%= pkg.name %>.svg.js',
|
|
||||||
options:{
|
|
||||||
browserifyOptions: {
|
|
||||||
standalone: 'html2canvas.svg'
|
|
||||||
},
|
|
||||||
banner: meta.banner,
|
|
||||||
plugin: [
|
|
||||||
[ "browserify-derequire" ]
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
connect: {
|
|
||||||
server: {
|
|
||||||
options: {
|
|
||||||
port: 8080,
|
|
||||||
base: './',
|
|
||||||
keepalive: true
|
|
||||||
}
|
|
||||||
},
|
|
||||||
altServer: {
|
|
||||||
options: {
|
|
||||||
port: 8083,
|
|
||||||
base: './'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
cors: {
|
|
||||||
options: {
|
|
||||||
port: 8081,
|
|
||||||
base: './',
|
|
||||||
middleware: function(connect, options) {
|
|
||||||
return [
|
|
||||||
function(req, res, next) {
|
|
||||||
if (req.url !== '/tests/assets/image2.jpg') {
|
|
||||||
next();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
||||||
res.end(require("fs").readFileSync('tests/assets/image2.jpg'));
|
|
||||||
}
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
proxy: {
|
|
||||||
options: {
|
|
||||||
port: 8082,
|
|
||||||
middleware: function(connect, options) {
|
|
||||||
return [
|
|
||||||
function(req, res, next) {
|
|
||||||
res.jsonp = function(content) {
|
|
||||||
res.end(req.query.callback + "(" + JSON.stringify(content) + ")");
|
|
||||||
};
|
|
||||||
next();
|
|
||||||
},
|
|
||||||
proxy()
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
ci: {
|
|
||||||
options: {
|
|
||||||
port: 8080,
|
|
||||||
base: './'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
execute: {
|
|
||||||
fabric: {
|
|
||||||
options: {
|
|
||||||
args: ['modules=' + ['text','serialization',
|
|
||||||
'parser', 'gradient', 'pattern', 'shadow', 'freedrawing',
|
|
||||||
'image_filters', 'serialization'].join(","), 'no-es5-compat', 'dest=' + path.resolve(__dirname, 'src/fabric/dist/') + '/']
|
|
||||||
},
|
|
||||||
src: ['src/fabric/build.js']
|
|
||||||
}
|
|
||||||
},
|
|
||||||
uglify: {
|
|
||||||
dist: {
|
|
||||||
src: ['<%= browserify.dist.dest %>'],
|
|
||||||
dest: 'dist/<%= pkg.name %>.min.js'
|
|
||||||
},
|
|
||||||
svg: {
|
|
||||||
src: ['<%= browserify.svg.dest %>'],
|
|
||||||
dest: 'dist/<%= pkg.name %>.svg.min.js'
|
|
||||||
},
|
|
||||||
options: {
|
|
||||||
banner: meta.banner
|
|
||||||
}
|
|
||||||
},
|
|
||||||
watch: {
|
|
||||||
files: ['src/**/*', '!src/fabric/**/*'],
|
|
||||||
tasks: ['jshint', 'build']
|
|
||||||
},
|
|
||||||
jshint: {
|
|
||||||
all: ['src/*.js', 'src/renderers/*.js'],
|
|
||||||
options: grunt.file.readJSON('./.jshintrc')
|
|
||||||
},
|
|
||||||
mochacli: {
|
|
||||||
options: {
|
|
||||||
reporter: 'spec'
|
|
||||||
},
|
|
||||||
all: ['tests/node/*.js']
|
|
||||||
},
|
|
||||||
mocha_phantomjs: {
|
|
||||||
all: ['tests/mocha/**/*.html']
|
|
||||||
},
|
|
||||||
mocha_webdriver: browsers,
|
|
||||||
webdriver: browsers
|
|
||||||
});
|
|
||||||
|
|
||||||
grunt.registerTask('webdriver', 'Browser render tests', function(browser, test) {
|
|
||||||
var selenium = require("./tests/selenium.js");
|
|
||||||
var done = this.async();
|
|
||||||
var browsers = (browser) ? [grunt.config.get(this.name + "." + browser)] : _.values(grunt.config.get(this.name));
|
|
||||||
selenium.tests(browsers, test).catch(function() {
|
|
||||||
done(false);
|
|
||||||
}).finally(function() {
|
|
||||||
console.log("Done");
|
|
||||||
done();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
grunt.registerTask('mocha_webdriver', 'Browser mocha tests', function(browser, test) {
|
|
||||||
var selenium = require("./tests/mocha/selenium.js");
|
|
||||||
var done = this.async();
|
|
||||||
var browsers = (browser) ? [grunt.config.get(this.name + "." + browser)] : _.values(grunt.config.get(this.name));
|
|
||||||
selenium.tests(browsers, test).catch(function() {
|
|
||||||
done(false);
|
|
||||||
}).finally(function() {
|
|
||||||
done();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
grunt.loadNpmTasks('grunt-browserify');
|
|
||||||
grunt.loadNpmTasks('grunt-mocha-phantomjs');
|
|
||||||
grunt.loadNpmTasks('grunt-contrib-watch');
|
|
||||||
grunt.loadNpmTasks('grunt-contrib-uglify');
|
|
||||||
grunt.loadNpmTasks('grunt-contrib-jshint');
|
|
||||||
grunt.loadNpmTasks('grunt-contrib-connect');
|
|
||||||
grunt.loadNpmTasks('grunt-execute');
|
|
||||||
grunt.loadNpmTasks('grunt-mocha-cli');
|
|
||||||
|
|
||||||
grunt.registerTask('server', ['connect:cors', 'connect:proxy', 'connect:altServer', 'connect:server']);
|
|
||||||
grunt.registerTask('build', ['execute', 'browserify', 'uglify']);
|
|
||||||
grunt.registerTask('default', ['jshint', 'build', 'mochacli', 'connect:altServer', 'mocha_phantomjs']);
|
|
||||||
grunt.registerTask('travis', ['jshint', 'build', 'connect:altServer', 'connect:ci', 'connect:proxy', 'connect:cors', 'mocha_phantomjs', 'webdriver']);
|
|
||||||
|
|
||||||
};
|
|
1
flow-typed/myLibDef.js
vendored
Normal file
1
flow-typed/myLibDef.js
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
declare var __DEV__: boolean;
|
49
package.json
49
package.json
@ -3,7 +3,7 @@
|
|||||||
"name": "html2canvas",
|
"name": "html2canvas",
|
||||||
"description": "Screenshots with JavaScript",
|
"description": "Screenshots with JavaScript",
|
||||||
"main": "dist/html2canvas.js",
|
"main": "dist/html2canvas.js",
|
||||||
"version": "0.5.0-beta4",
|
"version": "1.0.0-alpha.1",
|
||||||
"author": {
|
"author": {
|
||||||
"name": "Niklas von Hertzen",
|
"name": "Niklas von Hertzen",
|
||||||
"email": "niklasvh@gmail.com",
|
"email": "niklasvh@gmail.com",
|
||||||
@ -20,32 +20,31 @@
|
|||||||
"url": "https://github.com/niklasvh/html2canvas/issues"
|
"url": "https://github.com/niklasvh/html2canvas/issues"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"base64-arraybuffer": "^0.1.5",
|
"babel-cli": "6.24.1",
|
||||||
"bluebird": "^3.0.6",
|
"babel-core": "6.25.0",
|
||||||
"browserify-derequire": "^0.9.4",
|
"babel-eslint": "7.2.3",
|
||||||
"grunt": "^0.4.5",
|
"babel-loader": "7.1.1",
|
||||||
"grunt-browserify": "^4.0.1",
|
"babel-preset-es2015": "6.24.1",
|
||||||
"grunt-cli": "^0.1.13",
|
"babel-preset-flow": "6.23.0",
|
||||||
"grunt-contrib-connect": "^0.11.2",
|
"base64-arraybuffer": "0.1.5",
|
||||||
"grunt-contrib-jshint": "^0.11.3",
|
"eslint": "4.2.0",
|
||||||
"grunt-contrib-uglify": "^0.11.0",
|
"eslint-plugin-prettier": "^2.1.2",
|
||||||
"grunt-contrib-watch": "^0.6.1",
|
"flow-bin": "0.50.0",
|
||||||
"grunt-execute": "^0.2.2",
|
"prettier": "1.5.3",
|
||||||
"grunt-mocha-cli": "^1.12.0",
|
"rimraf": "2.6.1",
|
||||||
"grunt-mocha-phantomjs": "^2.0.0",
|
"webpack": "3.4.1"
|
||||||
"html2canvas-proxy": "0.0.5",
|
|
||||||
"humanize-duration": "^2.0.1",
|
|
||||||
"lodash": "^3.10.1",
|
|
||||||
"pngjs": "^2.2.0",
|
|
||||||
"requirejs": "^2.1.20",
|
|
||||||
"sauce-connect-launcher": "^0.13.0",
|
|
||||||
"wd": "^0.4.0"
|
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "grunt travis --verbose",
|
"build": "rimraf dist/ && babel src/ -d dist/npm/",
|
||||||
"start": "grunt server",
|
"build:browser": "webpack",
|
||||||
"sauceconnect": "tests/sauceconnect.js"
|
"format": "prettier --single-quote --no-bracket-spacing --tab-width 4 --print-width 100 --write \"src/**/*.js\"",
|
||||||
|
"flow": "flow",
|
||||||
|
"lint": "eslint src/**",
|
||||||
|
"test": "npm run flow && npm run lint"
|
||||||
},
|
},
|
||||||
"homepage": "http://html2canvas.hertzen.com",
|
"homepage": "http://html2canvas.hertzen.com",
|
||||||
"license": "MIT"
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"punycode": "2.1.0"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
36
src/BezierCurve.js
Normal file
36
src/BezierCurve.js
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
import Vector from './Vector';
|
||||||
|
|
||||||
|
export default class BezierCurve {
|
||||||
|
start: Vector;
|
||||||
|
startControl: Vector;
|
||||||
|
endControl: Vector;
|
||||||
|
end: Vector;
|
||||||
|
|
||||||
|
constructor(start: Vector, startControl: Vector, endControl: Vector, end: Vector) {
|
||||||
|
this.start = start;
|
||||||
|
this.startControl = startControl;
|
||||||
|
this.endControl = endControl;
|
||||||
|
this.end = end;
|
||||||
|
}
|
||||||
|
|
||||||
|
lerp(a: Vector, b: Vector, t: number): Vector {
|
||||||
|
return new Vector(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);
|
||||||
|
}
|
||||||
|
|
||||||
|
subdivide(t: number): [BezierCurve, BezierCurve] {
|
||||||
|
const ab = this.lerp(this.start, this.startControl, t);
|
||||||
|
const bc = this.lerp(this.startControl, this.endControl, t);
|
||||||
|
const cd = this.lerp(this.endControl, this.end, t);
|
||||||
|
const abbc = this.lerp(ab, bc, t);
|
||||||
|
const bccd = this.lerp(bc, cd, t);
|
||||||
|
const dest = this.lerp(abbc, bccd, t);
|
||||||
|
return [
|
||||||
|
new BezierCurve(this.start, ab, abbc, dest),
|
||||||
|
new BezierCurve(dest, bccd, cd, this.end)
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
reverse(): BezierCurve {
|
||||||
|
return new BezierCurve(this.end, this.endControl, this.startControl, this.start);
|
||||||
|
}
|
||||||
|
}
|
278
src/Bounds.js
Normal file
278
src/Bounds.js
Normal file
@ -0,0 +1,278 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
import type {Border, BorderSide} from './parsing/border';
|
||||||
|
import type {BorderRadius} from './parsing/borderRadius';
|
||||||
|
import type {Padding} from './parsing/padding';
|
||||||
|
|
||||||
|
import Vector from './Vector';
|
||||||
|
import BezierCurve from './BezierCurve';
|
||||||
|
|
||||||
|
export type Path = Array<Vector | BezierCurve>;
|
||||||
|
|
||||||
|
const TOP = 0;
|
||||||
|
const RIGHT = 1;
|
||||||
|
const BOTTOM = 2;
|
||||||
|
const LEFT = 3;
|
||||||
|
|
||||||
|
export type BoundCurves = {
|
||||||
|
topLeftOuter: [BezierCurve, BezierCurve],
|
||||||
|
topLeftInner: [BezierCurve, BezierCurve],
|
||||||
|
topRightOuter: [BezierCurve, BezierCurve],
|
||||||
|
topRightInner: [BezierCurve, BezierCurve],
|
||||||
|
bottomRightOuter: [BezierCurve, BezierCurve],
|
||||||
|
bottomRightInner: [BezierCurve, BezierCurve],
|
||||||
|
bottomLeftOuter: [BezierCurve, BezierCurve],
|
||||||
|
bottomLeftInner: [BezierCurve, BezierCurve]
|
||||||
|
};
|
||||||
|
|
||||||
|
export class Bounds {
|
||||||
|
top: number;
|
||||||
|
left: number;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
|
||||||
|
constructor(x: number, y: number, w: number, h: number) {
|
||||||
|
this.left = x;
|
||||||
|
this.top = y;
|
||||||
|
this.width = w;
|
||||||
|
this.height = h;
|
||||||
|
}
|
||||||
|
|
||||||
|
static fromClientRect(clientRect: ClientRect): Bounds {
|
||||||
|
return new Bounds(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const parseBounds = (node: HTMLElement, isTransformed: boolean): Bounds => {
|
||||||
|
return isTransformed ? offsetBounds(node) : Bounds.fromClientRect(node.getBoundingClientRect());
|
||||||
|
};
|
||||||
|
|
||||||
|
const offsetBounds = (node: HTMLElement): Bounds => {
|
||||||
|
const parent =
|
||||||
|
node.offsetParent instanceof HTMLElement
|
||||||
|
? offsetBounds(node.offsetParent)
|
||||||
|
: {top: 0, left: 0};
|
||||||
|
|
||||||
|
return new Bounds(
|
||||||
|
node.offsetLeft + parent.left,
|
||||||
|
node.offsetTop + parent.top,
|
||||||
|
node.offsetWidth,
|
||||||
|
node.offsetHeight
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const calculatePaddingBox = (bounds: Bounds, borders: Array<Border>): Bounds => {
|
||||||
|
return new Bounds(
|
||||||
|
bounds.left + borders[LEFT].borderWidth,
|
||||||
|
bounds.top + borders[TOP].borderWidth,
|
||||||
|
bounds.width - (borders[RIGHT].borderWidth + borders[LEFT].borderWidth),
|
||||||
|
bounds.height - (borders[TOP].borderWidth + borders[BOTTOM].borderWidth)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const calculateContentBox = (
|
||||||
|
bounds: Bounds,
|
||||||
|
padding: Padding,
|
||||||
|
borders: Array<Border>
|
||||||
|
): Bounds => {
|
||||||
|
// TODO support percentage paddings
|
||||||
|
const paddingTop = padding[TOP].value;
|
||||||
|
const paddingRight = padding[RIGHT].value;
|
||||||
|
const paddingBottom = padding[BOTTOM].value;
|
||||||
|
const paddingLeft = padding[LEFT].value;
|
||||||
|
|
||||||
|
return new Bounds(
|
||||||
|
bounds.left + paddingLeft + borders[LEFT].borderWidth,
|
||||||
|
bounds.top + paddingTop + borders[TOP].borderWidth,
|
||||||
|
bounds.width -
|
||||||
|
(borders[RIGHT].borderWidth + borders[LEFT].borderWidth + paddingLeft + paddingRight),
|
||||||
|
bounds.height -
|
||||||
|
(borders[TOP].borderWidth + borders[BOTTOM].borderWidth + paddingTop + paddingBottom)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const parsePathForBorder = (curves: BoundCurves, borderSide: BorderSide): Path => {
|
||||||
|
switch (borderSide) {
|
||||||
|
case TOP:
|
||||||
|
return createPathFromCurves(
|
||||||
|
curves.topLeftOuter,
|
||||||
|
curves.topLeftInner,
|
||||||
|
curves.topRightOuter,
|
||||||
|
curves.topRightInner
|
||||||
|
);
|
||||||
|
case RIGHT:
|
||||||
|
return createPathFromCurves(
|
||||||
|
curves.topRightOuter,
|
||||||
|
curves.topRightInner,
|
||||||
|
curves.bottomRightOuter,
|
||||||
|
curves.bottomRightInner
|
||||||
|
);
|
||||||
|
case BOTTOM:
|
||||||
|
return createPathFromCurves(
|
||||||
|
curves.bottomRightOuter,
|
||||||
|
curves.bottomRightInner,
|
||||||
|
curves.bottomLeftOuter,
|
||||||
|
curves.bottomLeftInner
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
return createPathFromCurves(
|
||||||
|
curves.bottomLeftOuter,
|
||||||
|
curves.bottomLeftInner,
|
||||||
|
curves.topLeftOuter,
|
||||||
|
curves.topLeftInner
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const createPathFromCurves = (
|
||||||
|
outer1: [BezierCurve, BezierCurve],
|
||||||
|
inner1: [BezierCurve, BezierCurve],
|
||||||
|
outer2: [BezierCurve, BezierCurve],
|
||||||
|
inner2: [BezierCurve, BezierCurve]
|
||||||
|
): Path => {
|
||||||
|
const path = [];
|
||||||
|
path.push(outer1[1]);
|
||||||
|
path.push(outer2[0]);
|
||||||
|
path.push(inner2[0].reverse());
|
||||||
|
path.push(inner1[1].reverse());
|
||||||
|
|
||||||
|
return path;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const parseBoundCurves = (
|
||||||
|
bounds: Bounds,
|
||||||
|
borders: Array<Border>,
|
||||||
|
borderRadius: Array<BorderRadius>
|
||||||
|
): BoundCurves => {
|
||||||
|
// TODO support percentage borderRadius
|
||||||
|
const tlh =
|
||||||
|
borderRadius[0][0].value < bounds.width / 2 ? borderRadius[0][0].value : bounds.width / 2;
|
||||||
|
const tlv =
|
||||||
|
borderRadius[0][1].value < bounds.height / 2 ? borderRadius[0][1].value : bounds.height / 2;
|
||||||
|
const trh =
|
||||||
|
borderRadius[1][0].value < bounds.width / 2 ? borderRadius[1][0].value : bounds.width / 2;
|
||||||
|
const trv =
|
||||||
|
borderRadius[1][1].value < bounds.height / 2 ? borderRadius[1][1].value : bounds.height / 2;
|
||||||
|
const brh =
|
||||||
|
borderRadius[2][0].value < bounds.width / 2 ? borderRadius[2][0].value : bounds.width / 2;
|
||||||
|
const brv =
|
||||||
|
borderRadius[2][1].value < bounds.height / 2 ? borderRadius[2][1].value : bounds.height / 2;
|
||||||
|
const blh =
|
||||||
|
borderRadius[3][0].value < bounds.width / 2 ? borderRadius[3][0].value : bounds.width / 2;
|
||||||
|
const blv =
|
||||||
|
borderRadius[3][1].value < bounds.height / 2 ? borderRadius[3][1].value : bounds.height / 2;
|
||||||
|
|
||||||
|
const topWidth = bounds.width - trh;
|
||||||
|
const rightHeight = bounds.height - brv;
|
||||||
|
const bottomWidth = bounds.width - brh;
|
||||||
|
const leftHeight = bounds.height - blv;
|
||||||
|
|
||||||
|
return {
|
||||||
|
topLeftOuter: getCurvePoints(bounds.left, bounds.top, tlh, tlv, CORNER.TOP_LEFT).subdivide(
|
||||||
|
0.5
|
||||||
|
),
|
||||||
|
topLeftInner: getCurvePoints(
|
||||||
|
bounds.left + borders[3].borderWidth,
|
||||||
|
bounds.top + borders[0].borderWidth,
|
||||||
|
Math.max(0, tlh - borders[3].borderWidth),
|
||||||
|
Math.max(0, tlv - borders[0].borderWidth),
|
||||||
|
CORNER.TOP_LEFT
|
||||||
|
).subdivide(0.5),
|
||||||
|
topRightOuter: getCurvePoints(
|
||||||
|
bounds.left + topWidth,
|
||||||
|
bounds.top,
|
||||||
|
trh,
|
||||||
|
trv,
|
||||||
|
CORNER.TOP_RIGHT
|
||||||
|
).subdivide(0.5),
|
||||||
|
topRightInner: getCurvePoints(
|
||||||
|
bounds.left + Math.min(topWidth, bounds.width + borders[3].borderWidth),
|
||||||
|
bounds.top + borders[0].borderWidth,
|
||||||
|
topWidth > bounds.width + borders[3].borderWidth ? 0 : trh - borders[3].borderWidth,
|
||||||
|
trv - borders[0].borderWidth,
|
||||||
|
CORNER.TOP_RIGHT
|
||||||
|
).subdivide(0.5),
|
||||||
|
bottomRightOuter: getCurvePoints(
|
||||||
|
bounds.left + bottomWidth,
|
||||||
|
bounds.top + rightHeight,
|
||||||
|
brh,
|
||||||
|
brv,
|
||||||
|
CORNER.BOTTOM_RIGHT
|
||||||
|
).subdivide(0.5),
|
||||||
|
bottomRightInner: getCurvePoints(
|
||||||
|
bounds.left + Math.min(bottomWidth, bounds.width - borders[3].borderWidth),
|
||||||
|
bounds.top + Math.min(rightHeight, bounds.height + borders[0].borderWidth),
|
||||||
|
Math.max(0, brh - borders[1].borderWidth),
|
||||||
|
brv - borders[2].borderWidth,
|
||||||
|
CORNER.BOTTOM_RIGHT
|
||||||
|
).subdivide(0.5),
|
||||||
|
bottomLeftOuter: getCurvePoints(
|
||||||
|
bounds.left,
|
||||||
|
bounds.top + leftHeight,
|
||||||
|
blh,
|
||||||
|
blv,
|
||||||
|
CORNER.BOTTOM_LEFT
|
||||||
|
).subdivide(0.5),
|
||||||
|
bottomLeftInner: getCurvePoints(
|
||||||
|
bounds.left + borders[3].borderWidth,
|
||||||
|
bounds.top + leftHeight,
|
||||||
|
Math.max(0, blh - borders[3].borderWidth),
|
||||||
|
blv - borders[2].borderWidth,
|
||||||
|
CORNER.BOTTOM_LEFT
|
||||||
|
).subdivide(0.5)
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const CORNER = {
|
||||||
|
TOP_LEFT: 0,
|
||||||
|
TOP_RIGHT: 1,
|
||||||
|
BOTTOM_RIGHT: 2,
|
||||||
|
BOTTOM_LEFT: 3
|
||||||
|
};
|
||||||
|
|
||||||
|
type Corner = $Values<typeof CORNER>;
|
||||||
|
|
||||||
|
const getCurvePoints = (
|
||||||
|
x: number,
|
||||||
|
y: number,
|
||||||
|
r1: number,
|
||||||
|
r2: number,
|
||||||
|
position: Corner
|
||||||
|
): BezierCurve => {
|
||||||
|
const kappa = 4 * ((Math.sqrt(2) - 1) / 3);
|
||||||
|
const ox = r1 * kappa; // control point offset horizontal
|
||||||
|
const oy = r2 * kappa; // control point offset vertical
|
||||||
|
const xm = x + r1; // x-middle
|
||||||
|
const ym = y + r2; // y-middle
|
||||||
|
|
||||||
|
switch (position) {
|
||||||
|
case CORNER.TOP_LEFT:
|
||||||
|
return new BezierCurve(
|
||||||
|
new Vector(x, ym),
|
||||||
|
new Vector(x, ym - oy),
|
||||||
|
new Vector(xm - ox, y),
|
||||||
|
new Vector(xm, y)
|
||||||
|
);
|
||||||
|
case CORNER.TOP_RIGHT:
|
||||||
|
return new BezierCurve(
|
||||||
|
new Vector(x, y),
|
||||||
|
new Vector(x + ox, y),
|
||||||
|
new Vector(xm, ym - oy),
|
||||||
|
new Vector(xm, ym)
|
||||||
|
);
|
||||||
|
case CORNER.BOTTOM_RIGHT:
|
||||||
|
return new BezierCurve(
|
||||||
|
new Vector(xm, y),
|
||||||
|
new Vector(xm, y + oy),
|
||||||
|
new Vector(x + ox, ym),
|
||||||
|
new Vector(x, ym)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return new BezierCurve(
|
||||||
|
new Vector(xm, ym),
|
||||||
|
new Vector(xm - ox, ym),
|
||||||
|
new Vector(x, y + oy),
|
||||||
|
new Vector(x, y)
|
||||||
|
);
|
||||||
|
};
|
364
src/CanvasRenderer.js
Normal file
364
src/CanvasRenderer.js
Normal file
@ -0,0 +1,364 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
import type Color from './Color';
|
||||||
|
import type Size from './Size';
|
||||||
|
import type {Path, BoundCurves} from './Bounds';
|
||||||
|
import type {TextBounds} from './TextBounds';
|
||||||
|
import type {BackgroundImage} from './parsing/background';
|
||||||
|
import type {Border, BorderSide} from './parsing/border';
|
||||||
|
|
||||||
|
import Vector from './Vector';
|
||||||
|
import BezierCurve from './BezierCurve';
|
||||||
|
|
||||||
|
import type NodeContainer from './NodeContainer';
|
||||||
|
import type TextContainer from './TextContainer';
|
||||||
|
import type {ImageStore} from './ImageLoader';
|
||||||
|
import type StackingContext from './StackingContext';
|
||||||
|
|
||||||
|
import {
|
||||||
|
calculateBackgroundSize,
|
||||||
|
calculateBackgroundPosition,
|
||||||
|
calculateBackgroundRepeatPath
|
||||||
|
} from './parsing/background';
|
||||||
|
import {BORDER_STYLE} from './parsing/border';
|
||||||
|
import {
|
||||||
|
parseBoundCurves,
|
||||||
|
parsePathForBorder,
|
||||||
|
calculateContentBox,
|
||||||
|
calculatePaddingBox
|
||||||
|
} from './Bounds';
|
||||||
|
|
||||||
|
export type RenderOptions = {
|
||||||
|
scale: number,
|
||||||
|
backgroundColor: ?Color,
|
||||||
|
imageStore: ImageStore
|
||||||
|
};
|
||||||
|
|
||||||
|
export default class CanvasRenderer {
|
||||||
|
canvas: HTMLCanvasElement;
|
||||||
|
ctx: CanvasRenderingContext2D;
|
||||||
|
options: RenderOptions;
|
||||||
|
|
||||||
|
constructor(canvas: HTMLCanvasElement, options: RenderOptions) {
|
||||||
|
this.canvas = canvas;
|
||||||
|
this.ctx = canvas.getContext('2d');
|
||||||
|
this.options = options;
|
||||||
|
}
|
||||||
|
|
||||||
|
renderNode(container: NodeContainer) {
|
||||||
|
this.renderNodeBackgroundAndBorders(container);
|
||||||
|
this.renderNodeContent(container);
|
||||||
|
}
|
||||||
|
|
||||||
|
renderNodeContent(container: NodeContainer) {
|
||||||
|
if (container.textNodes.length) {
|
||||||
|
this.ctx.fillStyle = container.style.color.toString();
|
||||||
|
this.ctx.font = [
|
||||||
|
container.style.font.fontStyle,
|
||||||
|
container.style.font.fontVariant,
|
||||||
|
container.style.font.fontWeight,
|
||||||
|
container.style.font.fontSize,
|
||||||
|
container.style.font.fontFamily
|
||||||
|
]
|
||||||
|
.join(' ')
|
||||||
|
.split(',')[0];
|
||||||
|
container.textNodes.forEach(this.renderTextNode, this);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (container.image) {
|
||||||
|
const image = this.options.imageStore.get(container.image);
|
||||||
|
if (image) {
|
||||||
|
const contentBox = calculateContentBox(
|
||||||
|
container.bounds,
|
||||||
|
container.style.padding,
|
||||||
|
container.style.border
|
||||||
|
);
|
||||||
|
const width = typeof image.width === 'number' ? image.width : contentBox.width;
|
||||||
|
const height = typeof image.height === 'number' ? image.height : contentBox.height;
|
||||||
|
|
||||||
|
this.ctx.drawImage(
|
||||||
|
image,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
contentBox.left,
|
||||||
|
contentBox.top,
|
||||||
|
contentBox.width,
|
||||||
|
contentBox.height
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
renderNodeBackgroundAndBorders(container: NodeContainer) {
|
||||||
|
const curvePoints = parseBoundCurves(
|
||||||
|
container.bounds,
|
||||||
|
container.style.border,
|
||||||
|
container.style.borderRadius
|
||||||
|
);
|
||||||
|
|
||||||
|
this.renderBackground(container);
|
||||||
|
container.style.border.forEach((border, side) => {
|
||||||
|
this.renderBorder(border, side, curvePoints);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
renderTextNode(textContainer: TextContainer) {
|
||||||
|
textContainer.bounds.forEach(this.renderText, this);
|
||||||
|
}
|
||||||
|
|
||||||
|
renderText(text: TextBounds) {
|
||||||
|
this.ctx.fillText(text.text, text.bounds.left, text.bounds.top + text.bounds.height);
|
||||||
|
}
|
||||||
|
|
||||||
|
renderBackground(container: NodeContainer) {
|
||||||
|
if (container.bounds.height > 0 && container.bounds.width > 0) {
|
||||||
|
this.renderBackgroundColor(container);
|
||||||
|
this.renderBackgroundImage(container);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
renderBackgroundColor(container: NodeContainer) {
|
||||||
|
if (!container.style.background.backgroundColor.isTransparent()) {
|
||||||
|
this.rectangle(
|
||||||
|
container.bounds.left,
|
||||||
|
container.bounds.top,
|
||||||
|
container.bounds.width,
|
||||||
|
container.bounds.height,
|
||||||
|
container.style.background.backgroundColor
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
renderBackgroundImage(container: NodeContainer) {
|
||||||
|
container.style.background.backgroundImage.forEach(backgroundImage => {
|
||||||
|
if (backgroundImage.source.method === 'url' && backgroundImage.source.args.length) {
|
||||||
|
this.renderBackgroundRepeat(container, backgroundImage);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
renderBackgroundRepeat(container: NodeContainer, background: BackgroundImage) {
|
||||||
|
const image = this.options.imageStore.get(background.source.args[0]);
|
||||||
|
if (image) {
|
||||||
|
const bounds = container.bounds;
|
||||||
|
const paddingBox = calculatePaddingBox(bounds, container.style.border);
|
||||||
|
const size = calculateBackgroundSize(background, image, bounds);
|
||||||
|
const position = calculateBackgroundPosition(background.position, size, bounds);
|
||||||
|
const path = calculateBackgroundRepeatPath(background, position, size, paddingBox);
|
||||||
|
this.path(path);
|
||||||
|
const offsetX = Math.round(paddingBox.left + position.x);
|
||||||
|
const offsetY = Math.round(paddingBox.top + position.y);
|
||||||
|
this.ctx.fillStyle = this.ctx.createPattern(this.resizeImage(image, size), 'repeat');
|
||||||
|
this.ctx.translate(offsetX, offsetY);
|
||||||
|
this.ctx.fill();
|
||||||
|
this.ctx.translate(-offsetX, -offsetY);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
resizeImage(image: HTMLImageElement, size: Size) {
|
||||||
|
if (image.width === size.width && image.height === size.height) {
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
|
||||||
|
const canvas = document.createElement('canvas');
|
||||||
|
canvas.width = size.width;
|
||||||
|
canvas.height = size.height;
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height);
|
||||||
|
return canvas;
|
||||||
|
}
|
||||||
|
|
||||||
|
renderBorder(border: Border, side: BorderSide, curvePoints: BoundCurves) {
|
||||||
|
if (border.borderStyle !== BORDER_STYLE.NONE && !border.borderColor.isTransparent()) {
|
||||||
|
const path = parsePathForBorder(curvePoints, side);
|
||||||
|
this.path(path);
|
||||||
|
this.ctx.fillStyle = border.borderColor.toString();
|
||||||
|
this.ctx.fill();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
path(path: Path) {
|
||||||
|
this.ctx.beginPath();
|
||||||
|
path.forEach((point, index) => {
|
||||||
|
const start = point instanceof Vector ? point : point.start;
|
||||||
|
if (index === 0) {
|
||||||
|
this.ctx.moveTo(start.x, start.y);
|
||||||
|
} else {
|
||||||
|
this.ctx.lineTo(start.x, start.y);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (point instanceof BezierCurve) {
|
||||||
|
this.ctx.bezierCurveTo(
|
||||||
|
point.startControl.x,
|
||||||
|
point.startControl.y,
|
||||||
|
point.endControl.x,
|
||||||
|
point.endControl.y,
|
||||||
|
point.end.x,
|
||||||
|
point.end.y
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
this.ctx.closePath();
|
||||||
|
}
|
||||||
|
|
||||||
|
rectangle(x: number, y: number, width: number, height: number, color: Color) {
|
||||||
|
this.ctx.fillStyle = color.toString();
|
||||||
|
this.ctx.fillRect(x, y, width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
renderStack(stack: StackingContext) {
|
||||||
|
this.ctx.globalAlpha = stack.getOpacity();
|
||||||
|
const transform = stack.container.style.transform;
|
||||||
|
if (transform !== null) {
|
||||||
|
this.ctx.save();
|
||||||
|
this.ctx.translate(
|
||||||
|
stack.container.bounds.left + transform.transformOrigin[0].value,
|
||||||
|
stack.container.bounds.top + transform.transformOrigin[1].value
|
||||||
|
);
|
||||||
|
this.ctx.transform(
|
||||||
|
transform.transform[0],
|
||||||
|
transform.transform[1],
|
||||||
|
transform.transform[2],
|
||||||
|
transform.transform[3],
|
||||||
|
transform.transform[4],
|
||||||
|
transform.transform[5]
|
||||||
|
);
|
||||||
|
this.ctx.translate(
|
||||||
|
-(stack.container.bounds.left + transform.transformOrigin[0].value),
|
||||||
|
-(stack.container.bounds.top + transform.transformOrigin[1].value)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const [
|
||||||
|
negativeZIndex,
|
||||||
|
zeroOrAutoZIndexOrTransformedOrOpacity,
|
||||||
|
positiveZIndex,
|
||||||
|
nonPositionedFloats,
|
||||||
|
nonPositionedInlineLevel
|
||||||
|
] = splitStackingContexts(stack);
|
||||||
|
const [inlineLevel, nonInlineLevel] = splitDescendants(stack);
|
||||||
|
|
||||||
|
// https://www.w3.org/TR/css-position-3/#painting-order
|
||||||
|
// 1. the background and borders of the element forming the stacking context.
|
||||||
|
this.renderNodeBackgroundAndBorders(stack.container);
|
||||||
|
// 2. the child stacking contexts with negative stack levels (most negative first).
|
||||||
|
negativeZIndex.sort(sortByZIndex).forEach(this.renderStack, this);
|
||||||
|
// 3. For all its in-flow, non-positioned, block-level descendants in tree order:
|
||||||
|
this.renderNodeContent(stack.container);
|
||||||
|
nonInlineLevel.forEach(this.renderNode, this);
|
||||||
|
// 4. All non-positioned floating descendants, in tree order. For each one of these,
|
||||||
|
// treat the element as if it created a new stacking context, but any positioned descendants and descendants
|
||||||
|
// which actually create a new stacking context should be considered part of the parent stacking context,
|
||||||
|
// not this new one.
|
||||||
|
nonPositionedFloats.forEach(this.renderStack, this);
|
||||||
|
// 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
|
||||||
|
nonPositionedInlineLevel.forEach(this.renderStack, this);
|
||||||
|
inlineLevel.forEach(this.renderNode, this);
|
||||||
|
// 6. All positioned, opacity or transform descendants, in tree order that fall into the following categories:
|
||||||
|
// All positioned descendants with 'z-index: auto' or 'z-index: 0', in tree order.
|
||||||
|
// For those with 'z-index: auto', treat the element as if it created a new stacking context,
|
||||||
|
// but any positioned descendants and descendants which actually create a new stacking context should be
|
||||||
|
// considered part of the parent stacking context, not this new one. For those with 'z-index: 0',
|
||||||
|
// treat the stacking context generated atomically.
|
||||||
|
//
|
||||||
|
// All opacity descendants with opacity less than 1
|
||||||
|
//
|
||||||
|
// All transform descendants with transform other than none
|
||||||
|
zeroOrAutoZIndexOrTransformedOrOpacity.forEach(this.renderStack, this);
|
||||||
|
// 7. Stacking contexts formed by positioned descendants with z-indices greater than or equal to 1 in z-index
|
||||||
|
// order (smallest first) then tree order.
|
||||||
|
positiveZIndex.sort(sortByZIndex).forEach(this.renderStack, this);
|
||||||
|
|
||||||
|
if (transform !== null) {
|
||||||
|
this.ctx.restore();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
render(stack: StackingContext): Promise<HTMLCanvasElement> {
|
||||||
|
this.ctx.scale(this.options.scale, this.options.scale);
|
||||||
|
this.ctx.textBaseline = 'bottom';
|
||||||
|
if (this.options.backgroundColor) {
|
||||||
|
this.rectangle(
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
this.canvas.width,
|
||||||
|
this.canvas.height,
|
||||||
|
this.options.backgroundColor
|
||||||
|
);
|
||||||
|
}
|
||||||
|
this.renderStack(stack);
|
||||||
|
return Promise.resolve(this.canvas);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const splitDescendants = (stack: StackingContext): [Array<NodeContainer>, Array<NodeContainer>] => {
|
||||||
|
const inlineLevel = [];
|
||||||
|
const nonInlineLevel = [];
|
||||||
|
|
||||||
|
const length = stack.children.length;
|
||||||
|
for (let i = 0; i < length; i++) {
|
||||||
|
let child = stack.children[i];
|
||||||
|
if (child.isInlineLevel()) {
|
||||||
|
inlineLevel.push(child);
|
||||||
|
} else {
|
||||||
|
nonInlineLevel.push(child);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [inlineLevel, nonInlineLevel];
|
||||||
|
};
|
||||||
|
|
||||||
|
const splitStackingContexts = (
|
||||||
|
stack: StackingContext
|
||||||
|
): [
|
||||||
|
Array<StackingContext>,
|
||||||
|
Array<StackingContext>,
|
||||||
|
Array<StackingContext>,
|
||||||
|
Array<StackingContext>,
|
||||||
|
Array<StackingContext>
|
||||||
|
] => {
|
||||||
|
const negativeZIndex = [];
|
||||||
|
const zeroOrAutoZIndexOrTransformedOrOpacity = [];
|
||||||
|
const positiveZIndex = [];
|
||||||
|
const nonPositionedFloats = [];
|
||||||
|
const nonPositionedInlineLevel = [];
|
||||||
|
const length = stack.contexts.length;
|
||||||
|
for (let i = 0; i < length; i++) {
|
||||||
|
let child = stack.contexts[i];
|
||||||
|
if (
|
||||||
|
child.container.isPositioned() ||
|
||||||
|
child.container.style.opacity < 1 ||
|
||||||
|
child.container.isTransformed()
|
||||||
|
) {
|
||||||
|
if (child.container.style.zIndex.order < 0) {
|
||||||
|
negativeZIndex.push(child);
|
||||||
|
} else if (child.container.style.zIndex.order > 0) {
|
||||||
|
positiveZIndex.push(child);
|
||||||
|
} else {
|
||||||
|
zeroOrAutoZIndexOrTransformedOrOpacity.push(child);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (child.container.isFloating()) {
|
||||||
|
nonPositionedFloats.push(child);
|
||||||
|
} else {
|
||||||
|
nonPositionedInlineLevel.push(child);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [
|
||||||
|
negativeZIndex,
|
||||||
|
zeroOrAutoZIndexOrTransformedOrOpacity,
|
||||||
|
positiveZIndex,
|
||||||
|
nonPositionedFloats,
|
||||||
|
nonPositionedInlineLevel
|
||||||
|
];
|
||||||
|
};
|
||||||
|
|
||||||
|
const sortByZIndex = (a: StackingContext, b: StackingContext): number => {
|
||||||
|
if (a.container.style.zIndex.order > b.container.style.zIndex.order) {
|
||||||
|
return 1;
|
||||||
|
} else if (a.container.style.zIndex.order < b.container.style.zIndex.order) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
};
|
249
src/Color.js
Normal file
249
src/Color.js
Normal file
@ -0,0 +1,249 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
// http://dev.w3.org/csswg/css-color/
|
||||||
|
|
||||||
|
type ColorArray = [number, number, number, number | null];
|
||||||
|
|
||||||
|
const HEX3 = /^#([a-f0-9]{3})$/i;
|
||||||
|
const hex3 = (value: string): ColorArray | false => {
|
||||||
|
const match = value.match(HEX3);
|
||||||
|
if (match) {
|
||||||
|
return [
|
||||||
|
parseInt(match[1][0] + match[1][0], 16),
|
||||||
|
parseInt(match[1][1] + match[1][1], 16),
|
||||||
|
parseInt(match[1][2] + match[1][2], 16),
|
||||||
|
null
|
||||||
|
];
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const HEX6 = /^#([a-f0-9]{6})$/i;
|
||||||
|
const hex6 = (value: string): ColorArray | false => {
|
||||||
|
const match = value.match(HEX6);
|
||||||
|
if (match) {
|
||||||
|
return [
|
||||||
|
parseInt(match[1].substring(0, 2), 16),
|
||||||
|
parseInt(match[1].substring(2, 4), 16),
|
||||||
|
parseInt(match[1].substring(4, 6), 16),
|
||||||
|
null
|
||||||
|
];
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const RGB = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;
|
||||||
|
const rgb = (value: string): ColorArray | false => {
|
||||||
|
const match = value.match(RGB);
|
||||||
|
if (match) {
|
||||||
|
return [Number(match[1]), Number(match[2]), Number(match[3]), null];
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const RGBA = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d?\.?\d+)\s*\)$/;
|
||||||
|
const rgba = (value: string): ColorArray | false => {
|
||||||
|
const match = value.match(RGBA);
|
||||||
|
if (match && match.length > 4) {
|
||||||
|
return [Number(match[1]), Number(match[2]), Number(match[3]), Number(match[4])];
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const fromArray = (array: Array<number>): ColorArray => {
|
||||||
|
return [
|
||||||
|
Math.min(array[0], 255),
|
||||||
|
Math.min(array[1], 255),
|
||||||
|
Math.min(array[2], 255),
|
||||||
|
array.length > 3 ? array[3] : null
|
||||||
|
];
|
||||||
|
};
|
||||||
|
|
||||||
|
const namedColor = (name: string): ColorArray | false => {
|
||||||
|
const color: ColorArray | void = NAMED_COLORS[name.toLowerCase()];
|
||||||
|
return color ? color : false;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default class Color {
|
||||||
|
r: number;
|
||||||
|
g: number;
|
||||||
|
b: number;
|
||||||
|
a: number | null;
|
||||||
|
|
||||||
|
constructor(value: string | Array<number>) {
|
||||||
|
const [r, g, b, a] = Array.isArray(value)
|
||||||
|
? fromArray(value)
|
||||||
|
: hex3(value) ||
|
||||||
|
rgb(value) ||
|
||||||
|
rgba(value) ||
|
||||||
|
namedColor(value) ||
|
||||||
|
hex6(value) || [0, 0, 0, null];
|
||||||
|
this.r = r;
|
||||||
|
this.g = g;
|
||||||
|
this.b = b;
|
||||||
|
this.a = a;
|
||||||
|
}
|
||||||
|
|
||||||
|
isTransparent(): boolean {
|
||||||
|
return this.a === 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
toString(): string {
|
||||||
|
return this.a !== null && this.a !== 1
|
||||||
|
? `rgba(${this.r},${this.g},${this.b},${this.a})`
|
||||||
|
: `rgb(${this.r},${this.g},${this.b})`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const NAMED_COLORS = {
|
||||||
|
transparent: [0, 0, 0, 0],
|
||||||
|
aliceblue: [240, 248, 255, null],
|
||||||
|
antiquewhite: [250, 235, 215, null],
|
||||||
|
aqua: [0, 255, 255, null],
|
||||||
|
aquamarine: [127, 255, 212, null],
|
||||||
|
azure: [240, 255, 255, null],
|
||||||
|
beige: [245, 245, 220, null],
|
||||||
|
bisque: [255, 228, 196, null],
|
||||||
|
black: [0, 0, 0, null],
|
||||||
|
blanchedalmond: [255, 235, 205, null],
|
||||||
|
blue: [0, 0, 255, null],
|
||||||
|
blueviolet: [138, 43, 226, null],
|
||||||
|
brown: [165, 42, 42, null],
|
||||||
|
burlywood: [222, 184, 135, null],
|
||||||
|
cadetblue: [95, 158, 160, null],
|
||||||
|
chartreuse: [127, 255, 0, null],
|
||||||
|
chocolate: [210, 105, 30, null],
|
||||||
|
coral: [255, 127, 80, null],
|
||||||
|
cornflowerblue: [100, 149, 237, null],
|
||||||
|
cornsilk: [255, 248, 220, null],
|
||||||
|
crimson: [220, 20, 60, null],
|
||||||
|
cyan: [0, 255, 255, null],
|
||||||
|
darkblue: [0, 0, 139, null],
|
||||||
|
darkcyan: [0, 139, 139, null],
|
||||||
|
darkgoldenrod: [184, 134, 11, null],
|
||||||
|
darkgray: [169, 169, 169, null],
|
||||||
|
darkgreen: [0, 100, 0, null],
|
||||||
|
darkgrey: [169, 169, 169, null],
|
||||||
|
darkkhaki: [189, 183, 107, null],
|
||||||
|
darkmagenta: [139, 0, 139, null],
|
||||||
|
darkolivegreen: [85, 107, 47, null],
|
||||||
|
darkorange: [255, 140, 0, null],
|
||||||
|
darkorchid: [153, 50, 204, null],
|
||||||
|
darkred: [139, 0, 0, null],
|
||||||
|
darksalmon: [233, 150, 122, null],
|
||||||
|
darkseagreen: [143, 188, 143, null],
|
||||||
|
darkslateblue: [72, 61, 139, null],
|
||||||
|
darkslategray: [47, 79, 79, null],
|
||||||
|
darkslategrey: [47, 79, 79, null],
|
||||||
|
darkturquoise: [0, 206, 209, null],
|
||||||
|
darkviolet: [148, 0, 211, null],
|
||||||
|
deeppink: [255, 20, 147, null],
|
||||||
|
deepskyblue: [0, 191, 255, null],
|
||||||
|
dimgray: [105, 105, 105, null],
|
||||||
|
dimgrey: [105, 105, 105, null],
|
||||||
|
dodgerblue: [30, 144, 255, null],
|
||||||
|
firebrick: [178, 34, 34, null],
|
||||||
|
floralwhite: [255, 250, 240, null],
|
||||||
|
forestgreen: [34, 139, 34, null],
|
||||||
|
fuchsia: [255, 0, 255, null],
|
||||||
|
gainsboro: [220, 220, 220, null],
|
||||||
|
ghostwhite: [248, 248, 255, null],
|
||||||
|
gold: [255, 215, 0, null],
|
||||||
|
goldenrod: [218, 165, 32, null],
|
||||||
|
gray: [128, 128, 128, null],
|
||||||
|
green: [0, 128, 0, null],
|
||||||
|
greenyellow: [173, 255, 47, null],
|
||||||
|
grey: [128, 128, 128, null],
|
||||||
|
honeydew: [240, 255, 240, null],
|
||||||
|
hotpink: [255, 105, 180, null],
|
||||||
|
indianred: [205, 92, 92, null],
|
||||||
|
indigo: [75, 0, 130, null],
|
||||||
|
ivory: [255, 255, 240, null],
|
||||||
|
khaki: [240, 230, 140, null],
|
||||||
|
lavender: [230, 230, 250, null],
|
||||||
|
lavenderblush: [255, 240, 245, null],
|
||||||
|
lawngreen: [124, 252, 0, null],
|
||||||
|
lemonchiffon: [255, 250, 205, null],
|
||||||
|
lightblue: [173, 216, 230, null],
|
||||||
|
lightcoral: [240, 128, 128, null],
|
||||||
|
lightcyan: [224, 255, 255, null],
|
||||||
|
lightgoldenrodyellow: [250, 250, 210, null],
|
||||||
|
lightgray: [211, 211, 211, null],
|
||||||
|
lightgreen: [144, 238, 144, null],
|
||||||
|
lightgrey: [211, 211, 211, null],
|
||||||
|
lightpink: [255, 182, 193, null],
|
||||||
|
lightsalmon: [255, 160, 122, null],
|
||||||
|
lightseagreen: [32, 178, 170, null],
|
||||||
|
lightskyblue: [135, 206, 250, null],
|
||||||
|
lightslategray: [119, 136, 153, null],
|
||||||
|
lightslategrey: [119, 136, 153, null],
|
||||||
|
lightsteelblue: [176, 196, 222, null],
|
||||||
|
lightyellow: [255, 255, 224, null],
|
||||||
|
lime: [0, 255, 0, null],
|
||||||
|
limegreen: [50, 205, 50, null],
|
||||||
|
linen: [250, 240, 230, null],
|
||||||
|
magenta: [255, 0, 255, null],
|
||||||
|
maroon: [128, 0, 0, null],
|
||||||
|
mediumaquamarine: [102, 205, 170, null],
|
||||||
|
mediumblue: [0, 0, 205, null],
|
||||||
|
mediumorchid: [186, 85, 211, null],
|
||||||
|
mediumpurple: [147, 112, 219, null],
|
||||||
|
mediumseagreen: [60, 179, 113, null],
|
||||||
|
mediumslateblue: [123, 104, 238, null],
|
||||||
|
mediumspringgreen: [0, 250, 154, null],
|
||||||
|
mediumturquoise: [72, 209, 204, null],
|
||||||
|
mediumvioletred: [199, 21, 133, null],
|
||||||
|
midnightblue: [25, 25, 112, null],
|
||||||
|
mintcream: [245, 255, 250, null],
|
||||||
|
mistyrose: [255, 228, 225, null],
|
||||||
|
moccasin: [255, 228, 181, null],
|
||||||
|
navajowhite: [255, 222, 173, null],
|
||||||
|
navy: [0, 0, 128, null],
|
||||||
|
oldlace: [253, 245, 230, null],
|
||||||
|
olive: [128, 128, 0, null],
|
||||||
|
olivedrab: [107, 142, 35, null],
|
||||||
|
orange: [255, 165, 0, null],
|
||||||
|
orangered: [255, 69, 0, null],
|
||||||
|
orchid: [218, 112, 214, null],
|
||||||
|
palegoldenrod: [238, 232, 170, null],
|
||||||
|
palegreen: [152, 251, 152, null],
|
||||||
|
paleturquoise: [175, 238, 238, null],
|
||||||
|
palevioletred: [219, 112, 147, null],
|
||||||
|
papayawhip: [255, 239, 213, null],
|
||||||
|
peachpuff: [255, 218, 185, null],
|
||||||
|
peru: [205, 133, 63, null],
|
||||||
|
pink: [255, 192, 203, null],
|
||||||
|
plum: [221, 160, 221, null],
|
||||||
|
powderblue: [176, 224, 230, null],
|
||||||
|
purple: [128, 0, 128, null],
|
||||||
|
rebeccapurple: [102, 51, 153, null],
|
||||||
|
red: [255, 0, 0, null],
|
||||||
|
rosybrown: [188, 143, 143, null],
|
||||||
|
royalblue: [65, 105, 225, null],
|
||||||
|
saddlebrown: [139, 69, 19, null],
|
||||||
|
salmon: [250, 128, 114, null],
|
||||||
|
sandybrown: [244, 164, 96, null],
|
||||||
|
seagreen: [46, 139, 87, null],
|
||||||
|
seashell: [255, 245, 238, null],
|
||||||
|
sienna: [160, 82, 45, null],
|
||||||
|
silver: [192, 192, 192, null],
|
||||||
|
skyblue: [135, 206, 235, null],
|
||||||
|
slateblue: [106, 90, 205, null],
|
||||||
|
slategray: [112, 128, 144, null],
|
||||||
|
slategrey: [112, 128, 144, null],
|
||||||
|
snow: [255, 250, 250, null],
|
||||||
|
springgreen: [0, 255, 127, null],
|
||||||
|
steelblue: [70, 130, 180, null],
|
||||||
|
tan: [210, 180, 140, null],
|
||||||
|
teal: [0, 128, 128, null],
|
||||||
|
thistle: [216, 191, 216, null],
|
||||||
|
tomato: [255, 99, 71, null],
|
||||||
|
turquoise: [64, 224, 208, null],
|
||||||
|
violet: [238, 130, 238, null],
|
||||||
|
wheat: [245, 222, 179, null],
|
||||||
|
white: [255, 255, 255, null],
|
||||||
|
whitesmoke: [245, 245, 245, null],
|
||||||
|
yellow: [255, 255, 0, null],
|
||||||
|
yellowgreen: [154, 205, 50, null]
|
||||||
|
};
|
34
src/Feature.js
Normal file
34
src/Feature.js
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
const testRangeBounds = document => {
|
||||||
|
const TEST_HEIGHT = 123;
|
||||||
|
|
||||||
|
if (document.createRange) {
|
||||||
|
const range = document.createRange();
|
||||||
|
if (range.getBoundingClientRect) {
|
||||||
|
const testElement = document.createElement('boundtest');
|
||||||
|
testElement.style.height = `${TEST_HEIGHT}px`;
|
||||||
|
testElement.style.display = 'block';
|
||||||
|
document.body.appendChild(testElement);
|
||||||
|
|
||||||
|
range.selectNode(testElement);
|
||||||
|
const rangeBounds = range.getBoundingClientRect();
|
||||||
|
const rangeHeight = Math.round(rangeBounds.height);
|
||||||
|
document.body.removeChild(testElement);
|
||||||
|
if (rangeHeight === TEST_HEIGHT) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const FEATURES = {
|
||||||
|
get SUPPORT_RANGE_BOUNDS() {
|
||||||
|
'use strict';
|
||||||
|
const value = testRangeBounds(document);
|
||||||
|
Object.defineProperty(FEATURES, 'SUPPORT_RANGE_BOUNDS', {value});
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export default FEATURES;
|
100
src/ImageLoader.js
Normal file
100
src/ImageLoader.js
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
import type NodeContainer from './NodeContainer';
|
||||||
|
import type Options from './index';
|
||||||
|
import type Logger from './Logger';
|
||||||
|
|
||||||
|
type ImageCache = {[string]: Promise<Image>};
|
||||||
|
|
||||||
|
export default class ImageLoader {
|
||||||
|
origin: string;
|
||||||
|
options: Options;
|
||||||
|
_link: HTMLAnchorElement;
|
||||||
|
cache: ImageCache;
|
||||||
|
logger: Logger;
|
||||||
|
|
||||||
|
constructor(options: Options, logger: Logger) {
|
||||||
|
this.options = options;
|
||||||
|
this.origin = this.getOrigin(window.location.href);
|
||||||
|
this.cache = {};
|
||||||
|
this.logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
loadImage(src: string): ?string {
|
||||||
|
if (this.hasImageInCache(src)) {
|
||||||
|
return src;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.options.allowTaint === true || this.isInlineImage(src) || this.isSameOrigin(src)) {
|
||||||
|
return this.addImage(src, src);
|
||||||
|
} else if (typeof this.options.proxy === 'string' && !this.isSameOrigin(src)) {
|
||||||
|
// TODO proxy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
isInlineImage(src: string): boolean {
|
||||||
|
return /data:image\/.*;base64,/i.test(src);
|
||||||
|
}
|
||||||
|
|
||||||
|
hasImageInCache(key: string): boolean {
|
||||||
|
return typeof this.cache[key] !== 'undefined';
|
||||||
|
}
|
||||||
|
|
||||||
|
addImage(key: string, src: string): string {
|
||||||
|
if (__DEV__) {
|
||||||
|
this.logger.log(`Added image ${key.substring(0, 256)}`);
|
||||||
|
}
|
||||||
|
this.cache[key] = new Promise((resolve, reject) => {
|
||||||
|
const img = new Image();
|
||||||
|
img.onload = () => resolve(img);
|
||||||
|
img.onerror = reject;
|
||||||
|
/*
|
||||||
|
if (cors) {
|
||||||
|
img.crossOrigin = 'anonymous';
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
img.src = src;
|
||||||
|
if (img.complete === true) {
|
||||||
|
resolve(img);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
isSameOrigin(url: string): boolean {
|
||||||
|
return this.getOrigin(url) === this.origin;
|
||||||
|
}
|
||||||
|
|
||||||
|
getOrigin(url: string): string {
|
||||||
|
const link = this._link || (this._link = document.createElement('a'));
|
||||||
|
link.href = url;
|
||||||
|
link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
|
||||||
|
return link.protocol + link.hostname + link.port;
|
||||||
|
}
|
||||||
|
|
||||||
|
ready(): Promise<ImageStore> {
|
||||||
|
const keys = Object.keys(this.cache);
|
||||||
|
return Promise.all(keys.map(str => this.cache[str])).then(images => {
|
||||||
|
if (__DEV__) {
|
||||||
|
this.logger.log('Finished loading images', images);
|
||||||
|
}
|
||||||
|
return new ImageStore(keys, images);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ImageStore {
|
||||||
|
_keys: Array<string>;
|
||||||
|
_images: Array<HTMLImageElement>;
|
||||||
|
|
||||||
|
constructor(keys: Array<string>, images: Array<HTMLImageElement>) {
|
||||||
|
this._keys = keys;
|
||||||
|
this._images = images;
|
||||||
|
}
|
||||||
|
|
||||||
|
get(key: string): ?HTMLImageElement {
|
||||||
|
const index = this._keys.indexOf(key);
|
||||||
|
return index === -1 ? null : this._images[index];
|
||||||
|
}
|
||||||
|
}
|
36
src/Length.js
Normal file
36
src/Length.js
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
export const LENGTH_TYPE = {
|
||||||
|
PX: 0,
|
||||||
|
PERCENTAGE: 1
|
||||||
|
};
|
||||||
|
|
||||||
|
export type LengthType = $Values<typeof LENGTH_TYPE>;
|
||||||
|
|
||||||
|
export default class Length {
|
||||||
|
type: LengthType;
|
||||||
|
value: number;
|
||||||
|
|
||||||
|
constructor(value: string) {
|
||||||
|
this.type =
|
||||||
|
value.substr(value.length - 1) === '%' ? LENGTH_TYPE.PERCENTAGE : LENGTH_TYPE.PX;
|
||||||
|
const parsedValue = parseFloat(value);
|
||||||
|
if (__DEV__ && isNaN(parsedValue)) {
|
||||||
|
console.error(`Invalid value given for Length: "${value}"`);
|
||||||
|
}
|
||||||
|
this.value = isNaN(parsedValue) ? 0 : parsedValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
isPercentage(): boolean {
|
||||||
|
return this.type === LENGTH_TYPE.PERCENTAGE;
|
||||||
|
}
|
||||||
|
|
||||||
|
getAbsoluteValue(parentLength: number): number {
|
||||||
|
return this.isPercentage() ? parentLength * (this.value / 100) : this.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
static create(v): Length {
|
||||||
|
return new Length(v);
|
||||||
|
}
|
||||||
|
}
|
19
src/Logger.js
Normal file
19
src/Logger.js
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
export default class Logger {
|
||||||
|
start: number;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.start = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
log(...args: any) {
|
||||||
|
Function.prototype.bind
|
||||||
|
.call(window.console.log, window.console)
|
||||||
|
.apply(
|
||||||
|
window.console,
|
||||||
|
[Date.now() - this.start + 'ms', 'html2canvas:'].concat([].slice.call(args, 0))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
141
src/NodeContainer.js
Normal file
141
src/NodeContainer.js
Normal file
@ -0,0 +1,141 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
import type {Background} from './parsing/background';
|
||||||
|
import type {Border} from './parsing/border';
|
||||||
|
import type {BorderRadius} from './parsing/borderRadius';
|
||||||
|
import type {DisplayBit} from './parsing/display';
|
||||||
|
import type {Float} from './parsing/float';
|
||||||
|
import type {Font} from './parsing/font';
|
||||||
|
import type {Padding} from './parsing/padding';
|
||||||
|
import type {Position} from './parsing/position';
|
||||||
|
import type {TextTransform} from './parsing/textTransform';
|
||||||
|
import type {TextDecoration} from './parsing/textDecoration';
|
||||||
|
import type {Transform} from './parsing/transform';
|
||||||
|
import type {zIndex} from './parsing/zIndex';
|
||||||
|
|
||||||
|
import type {Bounds} from './Bounds';
|
||||||
|
import type ImageLoader from './ImageLoader';
|
||||||
|
|
||||||
|
import type TextContainer from './TextContainer';
|
||||||
|
|
||||||
|
import Color from './Color';
|
||||||
|
|
||||||
|
import {contains} from './Util';
|
||||||
|
import {parseBackground} from './parsing/background';
|
||||||
|
import {parseBorder} from './parsing/border';
|
||||||
|
import {parseBorderRadius} from './parsing/borderRadius';
|
||||||
|
import {parseDisplay, DISPLAY} from './parsing/display';
|
||||||
|
import {parseCSSFloat, FLOAT} from './parsing/float';
|
||||||
|
import {parseFont} from './parsing/font';
|
||||||
|
import {parseLetterSpacing} from './parsing/letterSpacing';
|
||||||
|
import {parsePadding} from './parsing/padding';
|
||||||
|
import {parsePosition, POSITION} from './parsing/position';
|
||||||
|
import {parseTextDecoration} from './parsing/textDecoration';
|
||||||
|
import {parseTextTransform} from './parsing/textTransform';
|
||||||
|
import {parseTransform} from './parsing/transform';
|
||||||
|
import {parseZIndex} from './parsing/zIndex';
|
||||||
|
|
||||||
|
import {parseBounds} from './Bounds';
|
||||||
|
|
||||||
|
type StyleDeclaration = {
|
||||||
|
background: Background,
|
||||||
|
border: Array<Border>,
|
||||||
|
borderRadius: Array<BorderRadius>,
|
||||||
|
color: Color,
|
||||||
|
display: DisplayBit,
|
||||||
|
float: Float,
|
||||||
|
font: Font,
|
||||||
|
letterSpacing: number,
|
||||||
|
opacity: number,
|
||||||
|
padding: Padding,
|
||||||
|
position: Position,
|
||||||
|
textDecoration: TextDecoration,
|
||||||
|
textTransform: TextTransform,
|
||||||
|
transform: Transform,
|
||||||
|
zIndex: zIndex
|
||||||
|
};
|
||||||
|
|
||||||
|
export default class NodeContainer {
|
||||||
|
name: ?string;
|
||||||
|
parent: ?NodeContainer;
|
||||||
|
style: StyleDeclaration;
|
||||||
|
textNodes: Array<TextContainer>;
|
||||||
|
bounds: Bounds;
|
||||||
|
image: ?string;
|
||||||
|
|
||||||
|
constructor(node: HTMLElement, parent: ?NodeContainer, imageLoader: ImageLoader) {
|
||||||
|
this.parent = parent;
|
||||||
|
this.textNodes = [];
|
||||||
|
const style = node.ownerDocument.defaultView.getComputedStyle(node, null);
|
||||||
|
const display = parseDisplay(style.display);
|
||||||
|
|
||||||
|
this.style = {
|
||||||
|
background: parseBackground(style, imageLoader),
|
||||||
|
border: parseBorder(style),
|
||||||
|
borderRadius: parseBorderRadius(style),
|
||||||
|
color: new Color(style.color),
|
||||||
|
display: display,
|
||||||
|
float: parseCSSFloat(style.float),
|
||||||
|
font: parseFont(style),
|
||||||
|
letterSpacing: parseLetterSpacing(style.letterSpacing),
|
||||||
|
opacity: parseFloat(style.opacity),
|
||||||
|
padding: parsePadding(style),
|
||||||
|
position: parsePosition(style.position),
|
||||||
|
textDecoration: parseTextDecoration(style),
|
||||||
|
textTransform: parseTextTransform(style.textTransform),
|
||||||
|
transform: parseTransform(style),
|
||||||
|
zIndex: parseZIndex(style.zIndex)
|
||||||
|
};
|
||||||
|
this.image =
|
||||||
|
node instanceof HTMLImageElement
|
||||||
|
? imageLoader.loadImage(node.currentSrc || node.src)
|
||||||
|
: null;
|
||||||
|
this.bounds = parseBounds(node, this.isTransformed());
|
||||||
|
if (__DEV__) {
|
||||||
|
this.name = `${node.tagName.toLowerCase()}${node.id
|
||||||
|
? `#${node.id}`
|
||||||
|
: ''}${node.className.split(' ').map(s => (s.length ? `.${s}` : '')).join('')}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
isInFlow(): boolean {
|
||||||
|
return this.isRootElement() && !this.isFloating() && !this.isAbsolutelyPositioned();
|
||||||
|
}
|
||||||
|
isVisible(): boolean {
|
||||||
|
return !contains(this.style.display, DISPLAY.NONE) && this.style.opacity > 0;
|
||||||
|
}
|
||||||
|
isAbsolutelyPositioned(): boolean {
|
||||||
|
return this.style.position !== POSITION.STATIC && this.style.position !== POSITION.RELATIVE;
|
||||||
|
}
|
||||||
|
isPositioned(): boolean {
|
||||||
|
return this.style.position !== POSITION.STATIC;
|
||||||
|
}
|
||||||
|
isFloating(): boolean {
|
||||||
|
return this.style.float !== FLOAT.NONE;
|
||||||
|
}
|
||||||
|
isRootElement(): boolean {
|
||||||
|
return this.parent === null;
|
||||||
|
}
|
||||||
|
isTransformed(): boolean {
|
||||||
|
return this.style.transform !== null;
|
||||||
|
}
|
||||||
|
isPositionedWithZIndex(): boolean {
|
||||||
|
return this.isPositioned() && !this.style.zIndex.auto;
|
||||||
|
}
|
||||||
|
isInlineLevel(): boolean {
|
||||||
|
return (
|
||||||
|
contains(this.style.display, DISPLAY.INLINE) ||
|
||||||
|
contains(this.style.display, DISPLAY.INLINE_BLOCK) ||
|
||||||
|
contains(this.style.display, DISPLAY.INLINE_FLEX) ||
|
||||||
|
contains(this.style.display, DISPLAY.INLINE_GRID) ||
|
||||||
|
contains(this.style.display, DISPLAY.INLINE_LIST_ITEM) ||
|
||||||
|
contains(this.style.display, DISPLAY.INLINE_TABLE)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
isInlineBlockOrInlineTable(): boolean {
|
||||||
|
return (
|
||||||
|
contains(this.style.display, DISPLAY.INLINE_BLOCK) ||
|
||||||
|
contains(this.style.display, DISPLAY.INLINE_TABLE)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
95
src/NodeParser.js
Normal file
95
src/NodeParser.js
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
import type ImageLoader from './ImageLoader';
|
||||||
|
import type Logger from './Logger';
|
||||||
|
import StackingContext from './StackingContext';
|
||||||
|
import NodeContainer from './NodeContainer';
|
||||||
|
import TextContainer from './TextContainer';
|
||||||
|
|
||||||
|
export const NodeParser = (
|
||||||
|
node: HTMLElement,
|
||||||
|
imageLoader: ImageLoader,
|
||||||
|
logger: Logger
|
||||||
|
): StackingContext => {
|
||||||
|
const container = new NodeContainer(node, null, imageLoader);
|
||||||
|
const stack = new StackingContext(container, null, true);
|
||||||
|
|
||||||
|
if (__DEV__) {
|
||||||
|
logger.log(`Starting node parsing`);
|
||||||
|
}
|
||||||
|
|
||||||
|
parseNodeTree(node, container, stack, imageLoader);
|
||||||
|
|
||||||
|
if (__DEV__) {
|
||||||
|
logger.log(`Finished parsing node tree`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return stack;
|
||||||
|
};
|
||||||
|
|
||||||
|
const IGNORED_NODE_NAMES = ['SCRIPT', 'HEAD', 'TITLE', 'OBJECT', 'BR', 'OPTION'];
|
||||||
|
|
||||||
|
const parseNodeTree = (
|
||||||
|
node: HTMLElement,
|
||||||
|
parent: NodeContainer,
|
||||||
|
stack: StackingContext,
|
||||||
|
imageLoader: ImageLoader
|
||||||
|
): void => {
|
||||||
|
node.childNodes.forEach((childNode: Node) => {
|
||||||
|
if (childNode instanceof Text) {
|
||||||
|
if (childNode.data.trim().length > 0) {
|
||||||
|
parent.textNodes.push(new TextContainer(childNode, parent));
|
||||||
|
}
|
||||||
|
} else if (childNode instanceof HTMLElement) {
|
||||||
|
if (IGNORED_NODE_NAMES.indexOf(childNode.nodeName) === -1) {
|
||||||
|
const container = new NodeContainer(childNode, parent, imageLoader);
|
||||||
|
if (container.isVisible()) {
|
||||||
|
const treatAsRealStackingContext = createsRealStackingContext(
|
||||||
|
container,
|
||||||
|
childNode
|
||||||
|
);
|
||||||
|
if (treatAsRealStackingContext || createsStackingContext(container)) {
|
||||||
|
// for treatAsRealStackingContext:false, any positioned descendants and descendants
|
||||||
|
// which actually create a new stacking context should be considered part of the parent stacking context
|
||||||
|
const parentStack =
|
||||||
|
treatAsRealStackingContext || container.isPositioned()
|
||||||
|
? stack.getRealParentStackingContext()
|
||||||
|
: stack;
|
||||||
|
const childStack = new StackingContext(
|
||||||
|
container,
|
||||||
|
parentStack,
|
||||||
|
treatAsRealStackingContext
|
||||||
|
);
|
||||||
|
parentStack.contexts.push(childStack);
|
||||||
|
parseNodeTree(childNode, container, childStack, imageLoader);
|
||||||
|
} else {
|
||||||
|
stack.children.push(container);
|
||||||
|
parseNodeTree(childNode, container, stack, imageLoader);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const createsRealStackingContext = (container: NodeContainer, node: HTMLElement): boolean => {
|
||||||
|
return (
|
||||||
|
container.isRootElement() ||
|
||||||
|
container.isPositionedWithZIndex() ||
|
||||||
|
container.style.opacity < 1 ||
|
||||||
|
container.isTransformed() ||
|
||||||
|
isBodyWithTransparentRoot(container, node)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const createsStackingContext = (container: NodeContainer): boolean => {
|
||||||
|
return container.isPositioned() || container.isFloating();
|
||||||
|
};
|
||||||
|
|
||||||
|
const isBodyWithTransparentRoot = (container: NodeContainer, node: HTMLElement): boolean => {
|
||||||
|
return (
|
||||||
|
node.nodeName === 'BODY' &&
|
||||||
|
container.parent instanceof NodeContainer &&
|
||||||
|
container.parent.style.background.backgroundColor.isTransparent()
|
||||||
|
);
|
||||||
|
};
|
12
src/Size.js
Normal file
12
src/Size.js
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
export default class Size {
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
|
||||||
|
constructor(width: number, height: number) {
|
||||||
|
this.width = width;
|
||||||
|
this.height = height;
|
||||||
|
}
|
||||||
|
}
|
37
src/StackingContext.js
Normal file
37
src/StackingContext.js
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
import NodeContainer from './NodeContainer';
|
||||||
|
import {POSITION} from './parsing/position';
|
||||||
|
|
||||||
|
export default class StackingContext {
|
||||||
|
container: NodeContainer;
|
||||||
|
parent: ?StackingContext;
|
||||||
|
contexts: Array<StackingContext>;
|
||||||
|
children: Array<NodeContainer>;
|
||||||
|
treatAsRealStackingContext: boolean;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
container: NodeContainer,
|
||||||
|
parent: ?StackingContext,
|
||||||
|
treatAsRealStackingContext: boolean
|
||||||
|
) {
|
||||||
|
this.container = container;
|
||||||
|
this.parent = parent;
|
||||||
|
this.contexts = [];
|
||||||
|
this.children = [];
|
||||||
|
this.treatAsRealStackingContext = treatAsRealStackingContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
getOpacity(): number {
|
||||||
|
return this.parent
|
||||||
|
? this.container.style.opacity * this.parent.getOpacity()
|
||||||
|
: this.container.style.opacity;
|
||||||
|
}
|
||||||
|
|
||||||
|
getRealParentStackingContext(): StackingContext {
|
||||||
|
return !this.parent || this.treatAsRealStackingContext
|
||||||
|
? this
|
||||||
|
: this.parent.getRealParentStackingContext();
|
||||||
|
}
|
||||||
|
}
|
102
src/TextBounds.js
Normal file
102
src/TextBounds.js
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
import {ucs2} from 'punycode';
|
||||||
|
import type TextContainer from './TextContainer';
|
||||||
|
import {Bounds} from './Bounds';
|
||||||
|
import {TEXT_DECORATION} from './parsing/textDecoration';
|
||||||
|
|
||||||
|
import FEATURES from './Feature';
|
||||||
|
|
||||||
|
const UNICODE = /[^\u0000-\u00ff]/;
|
||||||
|
|
||||||
|
const hasUnicodeCharacters = (text: string): boolean => UNICODE.test(text);
|
||||||
|
|
||||||
|
const encodeCodePoint = (codePoint: number): string => ucs2.encode([codePoint]);
|
||||||
|
|
||||||
|
export class TextBounds {
|
||||||
|
text: string;
|
||||||
|
bounds: Bounds;
|
||||||
|
|
||||||
|
constructor(text: string, bounds: Bounds) {
|
||||||
|
this.text = text;
|
||||||
|
this.bounds = bounds;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const parseTextBounds = (textContainer: TextContainer, node: Text): Array<TextBounds> => {
|
||||||
|
const codePoints = ucs2.decode(textContainer.text);
|
||||||
|
const letterRendering =
|
||||||
|
textContainer.parent.style.letterSpacing !== 0 || hasUnicodeCharacters(textContainer.text);
|
||||||
|
const textList = letterRendering ? codePoints.map(encodeCodePoint) : splitWords(codePoints);
|
||||||
|
const length = textList.length;
|
||||||
|
const textBounds = [];
|
||||||
|
let offset = 0;
|
||||||
|
for (let i = 0; i < length; i++) {
|
||||||
|
let text = textList[i];
|
||||||
|
if (
|
||||||
|
textContainer.parent.style.textDecoration !== TEXT_DECORATION.NONE ||
|
||||||
|
text.trim().length > 0
|
||||||
|
) {
|
||||||
|
if (FEATURES.SUPPORT_RANGE_BOUNDS) {
|
||||||
|
textBounds.push(new TextBounds(text, getRangeBounds(node, offset, text.length)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
offset += text.length;
|
||||||
|
}
|
||||||
|
return textBounds;
|
||||||
|
|
||||||
|
/*
|
||||||
|
else if (container.node && typeof container.node.data === 'string') {
|
||||||
|
var replacementNode = container.node.splitText(text.length);
|
||||||
|
var bounds = this.getWrapperBounds(container.node, container.parent.hasTransform());
|
||||||
|
container.node = replacementNode;
|
||||||
|
return bounds;
|
||||||
|
}*/
|
||||||
|
};
|
||||||
|
|
||||||
|
const getRangeBounds = (node: Text, offset: number, length: number): Bounds => {
|
||||||
|
const range = node.ownerDocument.createRange();
|
||||||
|
range.setStart(node, offset);
|
||||||
|
range.setEnd(node, offset + length);
|
||||||
|
return Bounds.fromClientRect(range.getBoundingClientRect());
|
||||||
|
};
|
||||||
|
|
||||||
|
const splitWords = (codePoints: Array<number>): Array<string> => {
|
||||||
|
const words = [];
|
||||||
|
let i = 0;
|
||||||
|
let onWordBoundary = false;
|
||||||
|
let word;
|
||||||
|
while (codePoints.length) {
|
||||||
|
if (isWordBoundary(codePoints[i]) === onWordBoundary) {
|
||||||
|
word = codePoints.splice(0, i);
|
||||||
|
if (word.length) {
|
||||||
|
words.push(ucs2.encode(word));
|
||||||
|
}
|
||||||
|
onWordBoundary = !onWordBoundary;
|
||||||
|
i = 0;
|
||||||
|
} else {
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (i >= codePoints.length) {
|
||||||
|
word = codePoints.splice(0, i);
|
||||||
|
if (word.length) {
|
||||||
|
words.push(ucs2.encode(word));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return words;
|
||||||
|
};
|
||||||
|
|
||||||
|
const isWordBoundary = (characterCode: number): boolean => {
|
||||||
|
return (
|
||||||
|
[
|
||||||
|
32, // <space>
|
||||||
|
13, // \r
|
||||||
|
10, // \n
|
||||||
|
9, // \t
|
||||||
|
45 // -
|
||||||
|
].indexOf(characterCode) !== -1
|
||||||
|
);
|
||||||
|
};
|
43
src/TextContainer.js
Normal file
43
src/TextContainer.js
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
import type NodeContainer from './NodeContainer';
|
||||||
|
import type {TextTransform} from './parsing/textTransform';
|
||||||
|
import type {TextBounds} from './TextBounds';
|
||||||
|
import {TEXT_TRANSFORM} from './parsing/textTransform';
|
||||||
|
import {parseTextBounds} from './TextBounds';
|
||||||
|
|
||||||
|
export default class TextContainer {
|
||||||
|
text: string;
|
||||||
|
parent: NodeContainer;
|
||||||
|
bounds: Array<TextBounds>;
|
||||||
|
|
||||||
|
constructor(node: Text, parent: NodeContainer) {
|
||||||
|
this.text = transform(node.data, parent.style.textTransform);
|
||||||
|
this.parent = parent;
|
||||||
|
this.bounds = parseTextBounds(this, node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const CAPITALIZE = /(^|\s|:|-|\(|\))([a-z])/g;
|
||||||
|
|
||||||
|
const transform = (text: string, transform: TextTransform) => {
|
||||||
|
switch (transform) {
|
||||||
|
case TEXT_TRANSFORM.LOWERCASE:
|
||||||
|
return text.toLowerCase();
|
||||||
|
case TEXT_TRANSFORM.CAPITALIZE:
|
||||||
|
return text.replace(CAPITALIZE, capitalize);
|
||||||
|
case TEXT_TRANSFORM.UPPERCASE:
|
||||||
|
return text.toUpperCase();
|
||||||
|
default:
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
function capitalize(m, p1, p2) {
|
||||||
|
if (m.length > 0) {
|
||||||
|
return p1 + p2.toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
return m;
|
||||||
|
}
|
4
src/Util.js
Normal file
4
src/Util.js
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
export const contains = (bit: number, value: number): boolean => (bit & value) !== 0;
|
20
src/Vector.js
Normal file
20
src/Vector.js
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
export default class Vector {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
|
||||||
|
constructor(x: number, y: number) {
|
||||||
|
this.x = x;
|
||||||
|
this.y = y;
|
||||||
|
if (__DEV__) {
|
||||||
|
if (isNaN(x)) {
|
||||||
|
console.error(`Invalid x value given for Vector`);
|
||||||
|
}
|
||||||
|
if (isNaN(y)) {
|
||||||
|
console.error(`Invalid y value given for Vector`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
104
src/clone.js
104
src/clone.js
@ -1,104 +0,0 @@
|
|||||||
var log = require('./log');
|
|
||||||
|
|
||||||
function restoreOwnerScroll(ownerDocument, x, y) {
|
|
||||||
if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
|
|
||||||
ownerDocument.defaultView.scrollTo(x, y);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function cloneCanvasContents(canvas, clonedCanvas) {
|
|
||||||
try {
|
|
||||||
if (clonedCanvas) {
|
|
||||||
clonedCanvas.width = canvas.width;
|
|
||||||
clonedCanvas.height = canvas.height;
|
|
||||||
clonedCanvas.getContext("2d").putImageData(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height), 0, 0);
|
|
||||||
}
|
|
||||||
} catch(e) {
|
|
||||||
log("Unable to copy canvas content from", canvas, e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function cloneNode(node, javascriptEnabled) {
|
|
||||||
var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
|
|
||||||
|
|
||||||
var child = node.firstChild;
|
|
||||||
while(child) {
|
|
||||||
if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
|
|
||||||
clone.appendChild(cloneNode(child, javascriptEnabled));
|
|
||||||
}
|
|
||||||
child = child.nextSibling;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.nodeType === 1) {
|
|
||||||
clone._scrollTop = node.scrollTop;
|
|
||||||
clone._scrollLeft = node.scrollLeft;
|
|
||||||
if (node.nodeName === "CANVAS") {
|
|
||||||
cloneCanvasContents(node, clone);
|
|
||||||
} else if (node.nodeName === "TEXTAREA" || node.nodeName === "SELECT") {
|
|
||||||
clone.value = node.value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return clone;
|
|
||||||
}
|
|
||||||
|
|
||||||
function initNode(node) {
|
|
||||||
if (node.nodeType === 1) {
|
|
||||||
node.scrollTop = node._scrollTop;
|
|
||||||
node.scrollLeft = node._scrollLeft;
|
|
||||||
|
|
||||||
var child = node.firstChild;
|
|
||||||
while(child) {
|
|
||||||
initNode(child);
|
|
||||||
child = child.nextSibling;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = function(ownerDocument, containerDocument, width, height, options, x ,y) {
|
|
||||||
var documentElement = cloneNode(ownerDocument.documentElement, options.javascriptEnabled);
|
|
||||||
var container = containerDocument.createElement("iframe");
|
|
||||||
|
|
||||||
container.className = "html2canvas-container";
|
|
||||||
container.style.visibility = "hidden";
|
|
||||||
container.style.position = "fixed";
|
|
||||||
container.style.left = "-10000px";
|
|
||||||
container.style.top = "0px";
|
|
||||||
container.style.border = "0";
|
|
||||||
container.width = width;
|
|
||||||
container.height = height;
|
|
||||||
container.scrolling = "no"; // ios won't scroll without it
|
|
||||||
containerDocument.body.appendChild(container);
|
|
||||||
|
|
||||||
return new Promise(function(resolve) {
|
|
||||||
var documentClone = container.contentWindow.document;
|
|
||||||
|
|
||||||
/* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
|
|
||||||
if window url is about:blank, we can assign the url to current by writing onto the document
|
|
||||||
*/
|
|
||||||
container.contentWindow.onload = container.onload = function() {
|
|
||||||
var interval = setInterval(function() {
|
|
||||||
if (documentClone.body.childNodes.length > 0) {
|
|
||||||
initNode(documentClone.documentElement);
|
|
||||||
clearInterval(interval);
|
|
||||||
if (options.type === "view") {
|
|
||||||
container.contentWindow.scrollTo(x, y);
|
|
||||||
if ((/(iPad|iPhone|iPod)/g).test(navigator.userAgent) && (container.contentWindow.scrollY !== y || container.contentWindow.scrollX !== x)) {
|
|
||||||
documentClone.documentElement.style.top = (-y) + "px";
|
|
||||||
documentClone.documentElement.style.left = (-x) + "px";
|
|
||||||
documentClone.documentElement.style.position = 'absolute';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
resolve(container);
|
|
||||||
}
|
|
||||||
}, 50);
|
|
||||||
};
|
|
||||||
|
|
||||||
documentClone.open();
|
|
||||||
documentClone.write("<!DOCTYPE html><html></html>");
|
|
||||||
// Chrome scrolls the parent document for some reason after the write to the cloned window???
|
|
||||||
restoreOwnerScroll(ownerDocument, x, y);
|
|
||||||
documentClone.replaceChild(documentClone.adoptNode(documentElement), documentClone.documentElement);
|
|
||||||
documentClone.close();
|
|
||||||
});
|
|
||||||
};
|
|
272
src/color.js
272
src/color.js
@ -1,272 +0,0 @@
|
|||||||
// http://dev.w3.org/csswg/css-color/
|
|
||||||
|
|
||||||
function Color(value) {
|
|
||||||
this.r = 0;
|
|
||||||
this.g = 0;
|
|
||||||
this.b = 0;
|
|
||||||
this.a = null;
|
|
||||||
var result = this.fromArray(value) ||
|
|
||||||
this.namedColor(value) ||
|
|
||||||
this.rgb(value) ||
|
|
||||||
this.rgba(value) ||
|
|
||||||
this.hex6(value) ||
|
|
||||||
this.hex3(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
Color.prototype.darken = function(amount) {
|
|
||||||
var a = 1 - amount;
|
|
||||||
return new Color([
|
|
||||||
Math.round(this.r * a),
|
|
||||||
Math.round(this.g * a),
|
|
||||||
Math.round(this.b * a),
|
|
||||||
this.a
|
|
||||||
]);
|
|
||||||
};
|
|
||||||
|
|
||||||
Color.prototype.isTransparent = function() {
|
|
||||||
return this.a === 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
Color.prototype.isBlack = function() {
|
|
||||||
return this.r === 0 && this.g === 0 && this.b === 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
Color.prototype.fromArray = function(array) {
|
|
||||||
if (Array.isArray(array)) {
|
|
||||||
this.r = Math.min(array[0], 255);
|
|
||||||
this.g = Math.min(array[1], 255);
|
|
||||||
this.b = Math.min(array[2], 255);
|
|
||||||
if (array.length > 3) {
|
|
||||||
this.a = array[3];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (Array.isArray(array));
|
|
||||||
};
|
|
||||||
|
|
||||||
var _hex3 = /^#([a-f0-9]{3})$/i;
|
|
||||||
|
|
||||||
Color.prototype.hex3 = function(value) {
|
|
||||||
var match = null;
|
|
||||||
if ((match = value.match(_hex3)) !== null) {
|
|
||||||
this.r = parseInt(match[1][0] + match[1][0], 16);
|
|
||||||
this.g = parseInt(match[1][1] + match[1][1], 16);
|
|
||||||
this.b = parseInt(match[1][2] + match[1][2], 16);
|
|
||||||
}
|
|
||||||
return match !== null;
|
|
||||||
};
|
|
||||||
|
|
||||||
var _hex6 = /^#([a-f0-9]{6})$/i;
|
|
||||||
|
|
||||||
Color.prototype.hex6 = function(value) {
|
|
||||||
var match = null;
|
|
||||||
if ((match = value.match(_hex6)) !== null) {
|
|
||||||
this.r = parseInt(match[1].substring(0, 2), 16);
|
|
||||||
this.g = parseInt(match[1].substring(2, 4), 16);
|
|
||||||
this.b = parseInt(match[1].substring(4, 6), 16);
|
|
||||||
}
|
|
||||||
return match !== null;
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
var _rgb = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;
|
|
||||||
|
|
||||||
Color.prototype.rgb = function(value) {
|
|
||||||
var match = null;
|
|
||||||
if ((match = value.match(_rgb)) !== null) {
|
|
||||||
this.r = Number(match[1]);
|
|
||||||
this.g = Number(match[2]);
|
|
||||||
this.b = Number(match[3]);
|
|
||||||
}
|
|
||||||
return match !== null;
|
|
||||||
};
|
|
||||||
|
|
||||||
var _rgba = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d?\.?\d+)\s*\)$/;
|
|
||||||
|
|
||||||
Color.prototype.rgba = function(value) {
|
|
||||||
var match = null;
|
|
||||||
if ((match = value.match(_rgba)) !== null) {
|
|
||||||
this.r = Number(match[1]);
|
|
||||||
this.g = Number(match[2]);
|
|
||||||
this.b = Number(match[3]);
|
|
||||||
this.a = Number(match[4]);
|
|
||||||
}
|
|
||||||
return match !== null;
|
|
||||||
};
|
|
||||||
|
|
||||||
Color.prototype.toString = function() {
|
|
||||||
return this.a !== null && this.a !== 1 ?
|
|
||||||
"rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" :
|
|
||||||
"rgb(" + [this.r, this.g, this.b].join(",") + ")";
|
|
||||||
};
|
|
||||||
|
|
||||||
Color.prototype.namedColor = function(value) {
|
|
||||||
value = value.toLowerCase();
|
|
||||||
var color = colors[value];
|
|
||||||
if (color) {
|
|
||||||
this.r = color[0];
|
|
||||||
this.g = color[1];
|
|
||||||
this.b = color[2];
|
|
||||||
} else if (value === "transparent") {
|
|
||||||
this.r = this.g = this.b = this.a = 0;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return !!color;
|
|
||||||
};
|
|
||||||
|
|
||||||
Color.prototype.isColor = true;
|
|
||||||
|
|
||||||
// JSON.stringify([].slice.call($$('.named-color-table tr'), 1).map(function(row) { return [row.childNodes[3].textContent, row.childNodes[5].textContent.trim().split(",").map(Number)] }).reduce(function(data, row) {data[row[0]] = row[1]; return data}, {}))
|
|
||||||
var colors = {
|
|
||||||
"aliceblue": [240, 248, 255],
|
|
||||||
"antiquewhite": [250, 235, 215],
|
|
||||||
"aqua": [0, 255, 255],
|
|
||||||
"aquamarine": [127, 255, 212],
|
|
||||||
"azure": [240, 255, 255],
|
|
||||||
"beige": [245, 245, 220],
|
|
||||||
"bisque": [255, 228, 196],
|
|
||||||
"black": [0, 0, 0],
|
|
||||||
"blanchedalmond": [255, 235, 205],
|
|
||||||
"blue": [0, 0, 255],
|
|
||||||
"blueviolet": [138, 43, 226],
|
|
||||||
"brown": [165, 42, 42],
|
|
||||||
"burlywood": [222, 184, 135],
|
|
||||||
"cadetblue": [95, 158, 160],
|
|
||||||
"chartreuse": [127, 255, 0],
|
|
||||||
"chocolate": [210, 105, 30],
|
|
||||||
"coral": [255, 127, 80],
|
|
||||||
"cornflowerblue": [100, 149, 237],
|
|
||||||
"cornsilk": [255, 248, 220],
|
|
||||||
"crimson": [220, 20, 60],
|
|
||||||
"cyan": [0, 255, 255],
|
|
||||||
"darkblue": [0, 0, 139],
|
|
||||||
"darkcyan": [0, 139, 139],
|
|
||||||
"darkgoldenrod": [184, 134, 11],
|
|
||||||
"darkgray": [169, 169, 169],
|
|
||||||
"darkgreen": [0, 100, 0],
|
|
||||||
"darkgrey": [169, 169, 169],
|
|
||||||
"darkkhaki": [189, 183, 107],
|
|
||||||
"darkmagenta": [139, 0, 139],
|
|
||||||
"darkolivegreen": [85, 107, 47],
|
|
||||||
"darkorange": [255, 140, 0],
|
|
||||||
"darkorchid": [153, 50, 204],
|
|
||||||
"darkred": [139, 0, 0],
|
|
||||||
"darksalmon": [233, 150, 122],
|
|
||||||
"darkseagreen": [143, 188, 143],
|
|
||||||
"darkslateblue": [72, 61, 139],
|
|
||||||
"darkslategray": [47, 79, 79],
|
|
||||||
"darkslategrey": [47, 79, 79],
|
|
||||||
"darkturquoise": [0, 206, 209],
|
|
||||||
"darkviolet": [148, 0, 211],
|
|
||||||
"deeppink": [255, 20, 147],
|
|
||||||
"deepskyblue": [0, 191, 255],
|
|
||||||
"dimgray": [105, 105, 105],
|
|
||||||
"dimgrey": [105, 105, 105],
|
|
||||||
"dodgerblue": [30, 144, 255],
|
|
||||||
"firebrick": [178, 34, 34],
|
|
||||||
"floralwhite": [255, 250, 240],
|
|
||||||
"forestgreen": [34, 139, 34],
|
|
||||||
"fuchsia": [255, 0, 255],
|
|
||||||
"gainsboro": [220, 220, 220],
|
|
||||||
"ghostwhite": [248, 248, 255],
|
|
||||||
"gold": [255, 215, 0],
|
|
||||||
"goldenrod": [218, 165, 32],
|
|
||||||
"gray": [128, 128, 128],
|
|
||||||
"green": [0, 128, 0],
|
|
||||||
"greenyellow": [173, 255, 47],
|
|
||||||
"grey": [128, 128, 128],
|
|
||||||
"honeydew": [240, 255, 240],
|
|
||||||
"hotpink": [255, 105, 180],
|
|
||||||
"indianred": [205, 92, 92],
|
|
||||||
"indigo": [75, 0, 130],
|
|
||||||
"ivory": [255, 255, 240],
|
|
||||||
"khaki": [240, 230, 140],
|
|
||||||
"lavender": [230, 230, 250],
|
|
||||||
"lavenderblush": [255, 240, 245],
|
|
||||||
"lawngreen": [124, 252, 0],
|
|
||||||
"lemonchiffon": [255, 250, 205],
|
|
||||||
"lightblue": [173, 216, 230],
|
|
||||||
"lightcoral": [240, 128, 128],
|
|
||||||
"lightcyan": [224, 255, 255],
|
|
||||||
"lightgoldenrodyellow": [250, 250, 210],
|
|
||||||
"lightgray": [211, 211, 211],
|
|
||||||
"lightgreen": [144, 238, 144],
|
|
||||||
"lightgrey": [211, 211, 211],
|
|
||||||
"lightpink": [255, 182, 193],
|
|
||||||
"lightsalmon": [255, 160, 122],
|
|
||||||
"lightseagreen": [32, 178, 170],
|
|
||||||
"lightskyblue": [135, 206, 250],
|
|
||||||
"lightslategray": [119, 136, 153],
|
|
||||||
"lightslategrey": [119, 136, 153],
|
|
||||||
"lightsteelblue": [176, 196, 222],
|
|
||||||
"lightyellow": [255, 255, 224],
|
|
||||||
"lime": [0, 255, 0],
|
|
||||||
"limegreen": [50, 205, 50],
|
|
||||||
"linen": [250, 240, 230],
|
|
||||||
"magenta": [255, 0, 255],
|
|
||||||
"maroon": [128, 0, 0],
|
|
||||||
"mediumaquamarine": [102, 205, 170],
|
|
||||||
"mediumblue": [0, 0, 205],
|
|
||||||
"mediumorchid": [186, 85, 211],
|
|
||||||
"mediumpurple": [147, 112, 219],
|
|
||||||
"mediumseagreen": [60, 179, 113],
|
|
||||||
"mediumslateblue": [123, 104, 238],
|
|
||||||
"mediumspringgreen": [0, 250, 154],
|
|
||||||
"mediumturquoise": [72, 209, 204],
|
|
||||||
"mediumvioletred": [199, 21, 133],
|
|
||||||
"midnightblue": [25, 25, 112],
|
|
||||||
"mintcream": [245, 255, 250],
|
|
||||||
"mistyrose": [255, 228, 225],
|
|
||||||
"moccasin": [255, 228, 181],
|
|
||||||
"navajowhite": [255, 222, 173],
|
|
||||||
"navy": [0, 0, 128],
|
|
||||||
"oldlace": [253, 245, 230],
|
|
||||||
"olive": [128, 128, 0],
|
|
||||||
"olivedrab": [107, 142, 35],
|
|
||||||
"orange": [255, 165, 0],
|
|
||||||
"orangered": [255, 69, 0],
|
|
||||||
"orchid": [218, 112, 214],
|
|
||||||
"palegoldenrod": [238, 232, 170],
|
|
||||||
"palegreen": [152, 251, 152],
|
|
||||||
"paleturquoise": [175, 238, 238],
|
|
||||||
"palevioletred": [219, 112, 147],
|
|
||||||
"papayawhip": [255, 239, 213],
|
|
||||||
"peachpuff": [255, 218, 185],
|
|
||||||
"peru": [205, 133, 63],
|
|
||||||
"pink": [255, 192, 203],
|
|
||||||
"plum": [221, 160, 221],
|
|
||||||
"powderblue": [176, 224, 230],
|
|
||||||
"purple": [128, 0, 128],
|
|
||||||
"rebeccapurple": [102, 51, 153],
|
|
||||||
"red": [255, 0, 0],
|
|
||||||
"rosybrown": [188, 143, 143],
|
|
||||||
"royalblue": [65, 105, 225],
|
|
||||||
"saddlebrown": [139, 69, 19],
|
|
||||||
"salmon": [250, 128, 114],
|
|
||||||
"sandybrown": [244, 164, 96],
|
|
||||||
"seagreen": [46, 139, 87],
|
|
||||||
"seashell": [255, 245, 238],
|
|
||||||
"sienna": [160, 82, 45],
|
|
||||||
"silver": [192, 192, 192],
|
|
||||||
"skyblue": [135, 206, 235],
|
|
||||||
"slateblue": [106, 90, 205],
|
|
||||||
"slategray": [112, 128, 144],
|
|
||||||
"slategrey": [112, 128, 144],
|
|
||||||
"snow": [255, 250, 250],
|
|
||||||
"springgreen": [0, 255, 127],
|
|
||||||
"steelblue": [70, 130, 180],
|
|
||||||
"tan": [210, 180, 140],
|
|
||||||
"teal": [0, 128, 128],
|
|
||||||
"thistle": [216, 191, 216],
|
|
||||||
"tomato": [255, 99, 71],
|
|
||||||
"turquoise": [64, 224, 208],
|
|
||||||
"violet": [238, 130, 238],
|
|
||||||
"wheat": [245, 222, 179],
|
|
||||||
"white": [255, 255, 255],
|
|
||||||
"whitesmoke": [245, 245, 245],
|
|
||||||
"yellow": [255, 255, 0],
|
|
||||||
"yellowgreen": [154, 205, 50]
|
|
||||||
};
|
|
||||||
|
|
||||||
module.exports = Color;
|
|
155
src/core.js
155
src/core.js
@ -1,155 +0,0 @@
|
|||||||
var Support = require('./support');
|
|
||||||
var CanvasRenderer = require('./renderers/canvas');
|
|
||||||
var ImageLoader = require('./imageloader');
|
|
||||||
var NodeParser = require('./nodeparser');
|
|
||||||
var NodeContainer = require('./nodecontainer');
|
|
||||||
var log = require('./log');
|
|
||||||
var utils = require('./utils');
|
|
||||||
var createWindowClone = require('./clone');
|
|
||||||
var loadUrlDocument = require('./proxy').loadUrlDocument;
|
|
||||||
var getBounds = utils.getBounds;
|
|
||||||
|
|
||||||
var html2canvasNodeAttribute = "data-html2canvas-node";
|
|
||||||
var html2canvasCloneIndex = 0;
|
|
||||||
|
|
||||||
function html2canvas(nodeList, options) {
|
|
||||||
var index = html2canvasCloneIndex++;
|
|
||||||
options = options || {};
|
|
||||||
if (options.logging) {
|
|
||||||
log.options.logging = true;
|
|
||||||
log.options.start = Date.now();
|
|
||||||
}
|
|
||||||
|
|
||||||
options.async = typeof(options.async) === "undefined" ? true : options.async;
|
|
||||||
options.allowTaint = typeof(options.allowTaint) === "undefined" ? false : options.allowTaint;
|
|
||||||
options.removeContainer = typeof(options.removeContainer) === "undefined" ? true : options.removeContainer;
|
|
||||||
options.javascriptEnabled = typeof(options.javascriptEnabled) === "undefined" ? false : options.javascriptEnabled;
|
|
||||||
options.imageTimeout = typeof(options.imageTimeout) === "undefined" ? 10000 : options.imageTimeout;
|
|
||||||
options.renderer = typeof(options.renderer) === "function" ? options.renderer : CanvasRenderer;
|
|
||||||
options.strict = !!options.strict;
|
|
||||||
|
|
||||||
if (typeof(nodeList) === "string") {
|
|
||||||
if (typeof(options.proxy) !== "string") {
|
|
||||||
return Promise.reject("Proxy must be used when rendering url");
|
|
||||||
}
|
|
||||||
var width = options.width != null ? options.width : window.innerWidth;
|
|
||||||
var height = options.height != null ? options.height : window.innerHeight;
|
|
||||||
return loadUrlDocument(absoluteUrl(nodeList), options.proxy, document, width, height, options).then(function(container) {
|
|
||||||
return renderWindow(container.contentWindow.document.documentElement, container, options, width, height);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
var node = ((nodeList === undefined) ? [document.documentElement] : ((nodeList.length) ? nodeList : [nodeList]))[0];
|
|
||||||
node.setAttribute(html2canvasNodeAttribute + index, index);
|
|
||||||
return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) {
|
|
||||||
if (typeof(options.onrendered) === "function") {
|
|
||||||
log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
|
|
||||||
options.onrendered(canvas);
|
|
||||||
}
|
|
||||||
return canvas;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
html2canvas.CanvasRenderer = CanvasRenderer;
|
|
||||||
html2canvas.NodeContainer = NodeContainer;
|
|
||||||
html2canvas.log = log;
|
|
||||||
html2canvas.utils = utils;
|
|
||||||
|
|
||||||
var html2canvasExport = (typeof(document) === "undefined" || typeof(Object.create) !== "function" || typeof(document.createElement("canvas").getContext) !== "function") ? function() {
|
|
||||||
return Promise.reject("No canvas support");
|
|
||||||
} : html2canvas;
|
|
||||||
|
|
||||||
module.exports = html2canvasExport;
|
|
||||||
|
|
||||||
if (typeof(define) === 'function' && define.amd) {
|
|
||||||
define('html2canvas', [], function() {
|
|
||||||
return html2canvasExport;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderDocument(document, options, windowWidth, windowHeight, html2canvasIndex) {
|
|
||||||
return createWindowClone(document, document, windowWidth, windowHeight, options, document.defaultView.pageXOffset, document.defaultView.pageYOffset).then(function(container) {
|
|
||||||
log("Document cloned");
|
|
||||||
var attributeName = html2canvasNodeAttribute + html2canvasIndex;
|
|
||||||
var selector = "[" + attributeName + "='" + html2canvasIndex + "']";
|
|
||||||
document.querySelector(selector).removeAttribute(attributeName);
|
|
||||||
var clonedWindow = container.contentWindow;
|
|
||||||
var node = clonedWindow.document.querySelector(selector);
|
|
||||||
var oncloneHandler = (typeof(options.onclone) === "function") ? Promise.resolve(options.onclone(clonedWindow.document)) : Promise.resolve(true);
|
|
||||||
return oncloneHandler.then(function() {
|
|
||||||
return renderWindow(node, container, options, windowWidth, windowHeight);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderWindow(node, container, options, windowWidth, windowHeight) {
|
|
||||||
var clonedWindow = container.contentWindow;
|
|
||||||
var support = new Support(clonedWindow.document);
|
|
||||||
var imageLoader = new ImageLoader(options, support);
|
|
||||||
var bounds = getBounds(node);
|
|
||||||
var width = options.type === "view" ? windowWidth : documentWidth(clonedWindow.document);
|
|
||||||
var height = options.type === "view" ? windowHeight : documentHeight(clonedWindow.document);
|
|
||||||
var renderer = new options.renderer(width, height, imageLoader, options, document);
|
|
||||||
var parser = new NodeParser(node, renderer, support, imageLoader, options);
|
|
||||||
return parser.ready.then(function() {
|
|
||||||
log("Finished rendering");
|
|
||||||
var canvas;
|
|
||||||
|
|
||||||
if (options.type === "view") {
|
|
||||||
canvas = crop(renderer.canvas, {width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0});
|
|
||||||
} else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) {
|
|
||||||
canvas = renderer.canvas;
|
|
||||||
} else {
|
|
||||||
canvas = crop(renderer.canvas, {width: options.width != null ? options.width : bounds.width, height: options.height != null ? options.height : bounds.height, top: bounds.top, left: bounds.left, x: 0, y: 0});
|
|
||||||
}
|
|
||||||
|
|
||||||
cleanupContainer(container, options);
|
|
||||||
return canvas;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function cleanupContainer(container, options) {
|
|
||||||
if (options.removeContainer) {
|
|
||||||
container.parentNode.removeChild(container);
|
|
||||||
log("Cleaned up container");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function crop(canvas, bounds) {
|
|
||||||
var croppedCanvas = document.createElement("canvas");
|
|
||||||
var x1 = Math.min(canvas.width - 1, Math.max(0, bounds.left));
|
|
||||||
var x2 = Math.min(canvas.width, Math.max(1, bounds.left + bounds.width));
|
|
||||||
var y1 = Math.min(canvas.height - 1, Math.max(0, bounds.top));
|
|
||||||
var y2 = Math.min(canvas.height, Math.max(1, bounds.top + bounds.height));
|
|
||||||
croppedCanvas.width = bounds.width;
|
|
||||||
croppedCanvas.height = bounds.height;
|
|
||||||
var width = x2-x1;
|
|
||||||
var height = y2-y1;
|
|
||||||
log("Cropping canvas at:", "left:", bounds.left, "top:", bounds.top, "width:", width, "height:", height);
|
|
||||||
log("Resulting crop with width", bounds.width, "and height", bounds.height, "with x", x1, "and y", y1);
|
|
||||||
croppedCanvas.getContext("2d").drawImage(canvas, x1, y1, width, height, bounds.x, bounds.y, width, height);
|
|
||||||
return croppedCanvas;
|
|
||||||
}
|
|
||||||
|
|
||||||
function documentWidth (doc) {
|
|
||||||
return Math.max(
|
|
||||||
Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth),
|
|
||||||
Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth),
|
|
||||||
Math.max(doc.body.clientWidth, doc.documentElement.clientWidth)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function documentHeight (doc) {
|
|
||||||
return Math.max(
|
|
||||||
Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight),
|
|
||||||
Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight),
|
|
||||||
Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function absoluteUrl(url) {
|
|
||||||
var link = document.createElement("a");
|
|
||||||
link.href = url;
|
|
||||||
link.href = link.href;
|
|
||||||
return link;
|
|
||||||
}
|
|
@ -1,22 +0,0 @@
|
|||||||
var log = require('./log');
|
|
||||||
var smallImage = require('./utils').smallImage;
|
|
||||||
|
|
||||||
function DummyImageContainer(src) {
|
|
||||||
this.src = src;
|
|
||||||
log("DummyImageContainer for", src);
|
|
||||||
if (!this.promise || !this.image) {
|
|
||||||
log("Initiating DummyImageContainer");
|
|
||||||
DummyImageContainer.prototype.image = new Image();
|
|
||||||
var image = this.image;
|
|
||||||
DummyImageContainer.prototype.promise = new Promise(function(resolve, reject) {
|
|
||||||
image.onload = resolve;
|
|
||||||
image.onerror = reject;
|
|
||||||
image.src = smallImage();
|
|
||||||
if (image.complete === true) {
|
|
||||||
resolve(image);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = DummyImageContainer;
|
|
@ -1 +0,0 @@
|
|||||||
Subproject commit 791c74a82ef0d838fd0bd81bf942f8630a9a4a8f
|
|
52
src/font.js
52
src/font.js
@ -1,52 +0,0 @@
|
|||||||
var smallImage = require('./utils').smallImage;
|
|
||||||
|
|
||||||
function Font(family, size) {
|
|
||||||
var container = document.createElement('div'),
|
|
||||||
img = document.createElement('img'),
|
|
||||||
span = document.createElement('span'),
|
|
||||||
sampleText = 'Hidden Text',
|
|
||||||
baseline,
|
|
||||||
middle;
|
|
||||||
|
|
||||||
container.style.visibility = "hidden";
|
|
||||||
container.style.fontFamily = family;
|
|
||||||
container.style.fontSize = size;
|
|
||||||
container.style.margin = 0;
|
|
||||||
container.style.padding = 0;
|
|
||||||
|
|
||||||
document.body.appendChild(container);
|
|
||||||
|
|
||||||
img.src = smallImage();
|
|
||||||
img.width = 1;
|
|
||||||
img.height = 1;
|
|
||||||
|
|
||||||
img.style.margin = 0;
|
|
||||||
img.style.padding = 0;
|
|
||||||
img.style.verticalAlign = "baseline";
|
|
||||||
|
|
||||||
span.style.fontFamily = family;
|
|
||||||
span.style.fontSize = size;
|
|
||||||
span.style.margin = 0;
|
|
||||||
span.style.padding = 0;
|
|
||||||
|
|
||||||
span.appendChild(document.createTextNode(sampleText));
|
|
||||||
container.appendChild(span);
|
|
||||||
container.appendChild(img);
|
|
||||||
baseline = (img.offsetTop - span.offsetTop) + 1;
|
|
||||||
|
|
||||||
container.removeChild(span);
|
|
||||||
container.appendChild(document.createTextNode(sampleText));
|
|
||||||
|
|
||||||
container.style.lineHeight = "normal";
|
|
||||||
img.style.verticalAlign = "super";
|
|
||||||
|
|
||||||
middle = (img.offsetTop-container.offsetTop) + 1;
|
|
||||||
|
|
||||||
document.body.removeChild(container);
|
|
||||||
|
|
||||||
this.baseline = baseline;
|
|
||||||
this.lineWidth = 1;
|
|
||||||
this.middle = middle;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = Font;
|
|
@ -1,14 +0,0 @@
|
|||||||
var Font = require('./font');
|
|
||||||
|
|
||||||
function FontMetrics() {
|
|
||||||
this.data = {};
|
|
||||||
}
|
|
||||||
|
|
||||||
FontMetrics.prototype.getMetrics = function(family, size) {
|
|
||||||
if (this.data[family + "-" + size] === undefined) {
|
|
||||||
this.data[family + "-" + size] = new Font(family, size);
|
|
||||||
}
|
|
||||||
return this.data[family + "-" + size];
|
|
||||||
};
|
|
||||||
|
|
||||||
module.exports = FontMetrics;
|
|
@ -1,31 +0,0 @@
|
|||||||
var utils = require('./utils');
|
|
||||||
var getBounds = utils.getBounds;
|
|
||||||
var loadUrlDocument = require('./proxy').loadUrlDocument;
|
|
||||||
|
|
||||||
function FrameContainer(container, sameOrigin, options) {
|
|
||||||
this.image = null;
|
|
||||||
this.src = container;
|
|
||||||
var self = this;
|
|
||||||
var bounds = getBounds(container);
|
|
||||||
this.promise = (!sameOrigin ? this.proxyLoad(options.proxy, bounds, options) : new Promise(function(resolve) {
|
|
||||||
if (container.contentWindow.document.URL === "about:blank" || container.contentWindow.document.documentElement == null) {
|
|
||||||
container.contentWindow.onload = container.onload = function() {
|
|
||||||
resolve(container);
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
resolve(container);
|
|
||||||
}
|
|
||||||
})).then(function(container) {
|
|
||||||
var html2canvas = require('./core');
|
|
||||||
return html2canvas(container.contentWindow.document.documentElement, {type: 'view', width: container.width, height: container.height, proxy: options.proxy, javascriptEnabled: options.javascriptEnabled, removeContainer: options.removeContainer, allowTaint: options.allowTaint, imageTimeout: options.imageTimeout / 2});
|
|
||||||
}).then(function(canvas) {
|
|
||||||
return self.image = canvas;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
FrameContainer.prototype.proxyLoad = function(proxy, bounds, options) {
|
|
||||||
var container = this.src;
|
|
||||||
return loadUrlDocument(container.src, proxy, container.ownerDocument, bounds.width, bounds.height, options);
|
|
||||||
};
|
|
||||||
|
|
||||||
module.exports = FrameContainer;
|
|
@ -1,21 +0,0 @@
|
|||||||
function GradientContainer(imageData) {
|
|
||||||
this.src = imageData.value;
|
|
||||||
this.colorStops = [];
|
|
||||||
this.type = null;
|
|
||||||
this.x0 = 0.5;
|
|
||||||
this.y0 = 0.5;
|
|
||||||
this.x1 = 0.5;
|
|
||||||
this.y1 = 0.5;
|
|
||||||
this.promise = Promise.resolve(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
GradientContainer.TYPES = {
|
|
||||||
LINEAR: 1,
|
|
||||||
RADIAL: 2
|
|
||||||
};
|
|
||||||
|
|
||||||
// TODO: support hsl[a], negative %/length values
|
|
||||||
// TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
|
|
||||||
GradientContainer.REGEXP_COLORSTOP = /^\s*(rgba?\(\s*\d{1,3},\s*\d{1,3},\s*\d{1,3}(?:,\s*[0-9\.]+)?\s*\)|[a-z]{3,20}|#[a-f0-9]{3,6})(?:\s+(\d{1,3}(?:\.\d+)?)(%|px)?)?(?:\s|$)/i;
|
|
||||||
|
|
||||||
module.exports = GradientContainer;
|
|
@ -1,19 +0,0 @@
|
|||||||
function ImageContainer(src, cors) {
|
|
||||||
this.src = src;
|
|
||||||
this.image = new Image();
|
|
||||||
var self = this;
|
|
||||||
this.tainted = null;
|
|
||||||
this.promise = new Promise(function(resolve, reject) {
|
|
||||||
self.image.onload = resolve;
|
|
||||||
self.image.onerror = reject;
|
|
||||||
if (cors) {
|
|
||||||
self.image.crossOrigin = "anonymous";
|
|
||||||
}
|
|
||||||
self.image.src = src;
|
|
||||||
if (self.image.complete === true) {
|
|
||||||
resolve(self.image);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = ImageContainer;
|
|
@ -1,157 +0,0 @@
|
|||||||
var log = require('./log');
|
|
||||||
var ImageContainer = require('./imagecontainer');
|
|
||||||
var DummyImageContainer = require('./dummyimagecontainer');
|
|
||||||
var ProxyImageContainer = require('./proxyimagecontainer');
|
|
||||||
var FrameContainer = require('./framecontainer');
|
|
||||||
var SVGContainer = require('./svgcontainer');
|
|
||||||
var SVGNodeContainer = require('./svgnodecontainer');
|
|
||||||
var LinearGradientContainer = require('./lineargradientcontainer');
|
|
||||||
var WebkitGradientContainer = require('./webkitgradientcontainer');
|
|
||||||
var bind = require('./utils').bind;
|
|
||||||
|
|
||||||
function ImageLoader(options, support) {
|
|
||||||
this.link = null;
|
|
||||||
this.options = options;
|
|
||||||
this.support = support;
|
|
||||||
this.origin = this.getOrigin(window.location.href);
|
|
||||||
}
|
|
||||||
|
|
||||||
ImageLoader.prototype.findImages = function(nodes) {
|
|
||||||
var images = [];
|
|
||||||
nodes.reduce(function(imageNodes, container) {
|
|
||||||
switch(container.node.nodeName) {
|
|
||||||
case "IMG":
|
|
||||||
return imageNodes.concat([{
|
|
||||||
args: [container.node.src],
|
|
||||||
method: "url"
|
|
||||||
}]);
|
|
||||||
case "svg":
|
|
||||||
case "IFRAME":
|
|
||||||
return imageNodes.concat([{
|
|
||||||
args: [container.node],
|
|
||||||
method: container.node.nodeName
|
|
||||||
}]);
|
|
||||||
}
|
|
||||||
return imageNodes;
|
|
||||||
}, []).forEach(this.addImage(images, this.loadImage), this);
|
|
||||||
return images;
|
|
||||||
};
|
|
||||||
|
|
||||||
ImageLoader.prototype.findBackgroundImage = function(images, container) {
|
|
||||||
container.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(images, this.loadImage), this);
|
|
||||||
return images;
|
|
||||||
};
|
|
||||||
|
|
||||||
ImageLoader.prototype.addImage = function(images, callback) {
|
|
||||||
return function(newImage) {
|
|
||||||
newImage.args.forEach(function(image) {
|
|
||||||
if (!this.imageExists(images, image)) {
|
|
||||||
images.splice(0, 0, callback.call(this, newImage));
|
|
||||||
log('Added image #' + (images.length), typeof(image) === "string" ? image.substring(0, 100) : image);
|
|
||||||
}
|
|
||||||
}, this);
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
ImageLoader.prototype.hasImageBackground = function(imageData) {
|
|
||||||
return imageData.method !== "none";
|
|
||||||
};
|
|
||||||
|
|
||||||
ImageLoader.prototype.loadImage = function(imageData) {
|
|
||||||
if (imageData.method === "url") {
|
|
||||||
var src = imageData.args[0];
|
|
||||||
if (this.isSVG(src) && !this.support.svg && !this.options.allowTaint) {
|
|
||||||
return new SVGContainer(src);
|
|
||||||
} else if (src.match(/data:image\/.*;base64,/i)) {
|
|
||||||
return new ImageContainer(src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, ''), false);
|
|
||||||
} else if (this.isSameOrigin(src) || this.options.allowTaint === true || this.isSVG(src)) {
|
|
||||||
return new ImageContainer(src, false);
|
|
||||||
} else if (this.support.cors && !this.options.allowTaint && this.options.useCORS) {
|
|
||||||
return new ImageContainer(src, true);
|
|
||||||
} else if (this.options.proxy) {
|
|
||||||
return new ProxyImageContainer(src, this.options.proxy);
|
|
||||||
} else {
|
|
||||||
return new DummyImageContainer(src);
|
|
||||||
}
|
|
||||||
} else if (imageData.method === "linear-gradient") {
|
|
||||||
return new LinearGradientContainer(imageData);
|
|
||||||
} else if (imageData.method === "gradient") {
|
|
||||||
return new WebkitGradientContainer(imageData);
|
|
||||||
} else if (imageData.method === "svg") {
|
|
||||||
return new SVGNodeContainer(imageData.args[0], this.support.svg);
|
|
||||||
} else if (imageData.method === "IFRAME") {
|
|
||||||
return new FrameContainer(imageData.args[0], this.isSameOrigin(imageData.args[0].src), this.options);
|
|
||||||
} else {
|
|
||||||
return new DummyImageContainer(imageData);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
ImageLoader.prototype.isSVG = function(src) {
|
|
||||||
return src.substring(src.length - 3).toLowerCase() === "svg" || SVGContainer.prototype.isInline(src);
|
|
||||||
};
|
|
||||||
|
|
||||||
ImageLoader.prototype.imageExists = function(images, src) {
|
|
||||||
return images.some(function(image) {
|
|
||||||
return image.src === src;
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
ImageLoader.prototype.isSameOrigin = function(url) {
|
|
||||||
return (this.getOrigin(url) === this.origin);
|
|
||||||
};
|
|
||||||
|
|
||||||
ImageLoader.prototype.getOrigin = function(url) {
|
|
||||||
var link = this.link || (this.link = document.createElement("a"));
|
|
||||||
link.href = url;
|
|
||||||
link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
|
|
||||||
return link.protocol + link.hostname + link.port;
|
|
||||||
};
|
|
||||||
|
|
||||||
ImageLoader.prototype.getPromise = function(container) {
|
|
||||||
return this.timeout(container, this.options.imageTimeout)['catch'](function() {
|
|
||||||
var dummy = new DummyImageContainer(container.src);
|
|
||||||
return dummy.promise.then(function(image) {
|
|
||||||
container.image = image;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
ImageLoader.prototype.get = function(src) {
|
|
||||||
var found = null;
|
|
||||||
return this.images.some(function(img) {
|
|
||||||
return (found = img).src === src;
|
|
||||||
}) ? found : null;
|
|
||||||
};
|
|
||||||
|
|
||||||
ImageLoader.prototype.fetch = function(nodes) {
|
|
||||||
this.images = nodes.reduce(bind(this.findBackgroundImage, this), this.findImages(nodes));
|
|
||||||
this.images.forEach(function(image, index) {
|
|
||||||
image.promise.then(function() {
|
|
||||||
log("Succesfully loaded image #"+ (index+1), image);
|
|
||||||
}, function(e) {
|
|
||||||
log("Failed loading image #"+ (index+1), image, e);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
this.ready = Promise.all(this.images.map(this.getPromise, this));
|
|
||||||
log("Finished searching images");
|
|
||||||
return this;
|
|
||||||
};
|
|
||||||
|
|
||||||
ImageLoader.prototype.timeout = function(container, timeout) {
|
|
||||||
var timer;
|
|
||||||
var promise = Promise.race([container.promise, new Promise(function(res, reject) {
|
|
||||||
timer = setTimeout(function() {
|
|
||||||
log("Timed out loading image", container);
|
|
||||||
reject(container);
|
|
||||||
}, timeout);
|
|
||||||
})]).then(function(container) {
|
|
||||||
clearTimeout(timer);
|
|
||||||
return container;
|
|
||||||
});
|
|
||||||
promise['catch'](function() {
|
|
||||||
clearTimeout(timer);
|
|
||||||
});
|
|
||||||
return promise;
|
|
||||||
};
|
|
||||||
|
|
||||||
module.exports = ImageLoader;
|
|
49
src/index.js
Normal file
49
src/index.js
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
import {NodeParser} from './NodeParser';
|
||||||
|
import CanvasRenderer from './CanvasRenderer';
|
||||||
|
import Logger from './Logger';
|
||||||
|
import ImageLoader from './ImageLoader';
|
||||||
|
import Color from './Color';
|
||||||
|
|
||||||
|
export type Options = {
|
||||||
|
async: boolean,
|
||||||
|
imageTimeout: number,
|
||||||
|
renderer: Function,
|
||||||
|
proxy: string,
|
||||||
|
canvas: HTMLCanvasElement,
|
||||||
|
allowTaint: true
|
||||||
|
};
|
||||||
|
|
||||||
|
const html2canvas = (element: HTMLElement, options: Options): Promise<HTMLCanvasElement> => {
|
||||||
|
const logger = new Logger();
|
||||||
|
const imageLoader = new ImageLoader(options, logger);
|
||||||
|
const stack = NodeParser(element, imageLoader, logger);
|
||||||
|
const canvas = document.createElement('canvas');
|
||||||
|
|
||||||
|
const scale = window.devicePixelRatio;
|
||||||
|
const width = window.innerWidth;
|
||||||
|
const height = window.innerHeight;
|
||||||
|
canvas.width = Math.floor(width * scale);
|
||||||
|
canvas.height = Math.floor(height * scale);
|
||||||
|
canvas.style.width = `${width}px`;
|
||||||
|
canvas.style.height = `${height}px`;
|
||||||
|
|
||||||
|
// http://www.w3.org/TR/css3-background/#special-backgrounds
|
||||||
|
const backgroundColor =
|
||||||
|
element === element.ownerDocument.documentElement
|
||||||
|
? stack.container.style.background.backgroundColor.isTransparent()
|
||||||
|
? element.ownerDocument.body instanceof HTMLElement
|
||||||
|
? new Color(getComputedStyle(element.ownerDocument.body).backgroundColor)
|
||||||
|
: null
|
||||||
|
: stack.container.style.background.backgroundColor
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return imageLoader.ready().then(imageStore => {
|
||||||
|
const renderer = new CanvasRenderer(canvas, {scale, backgroundColor, imageStore});
|
||||||
|
return renderer.render(stack);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = html2canvas;
|
@ -1,102 +0,0 @@
|
|||||||
var GradientContainer = require('./gradientcontainer');
|
|
||||||
var Color = require('./color');
|
|
||||||
|
|
||||||
function LinearGradientContainer(imageData) {
|
|
||||||
GradientContainer.apply(this, arguments);
|
|
||||||
this.type = GradientContainer.TYPES.LINEAR;
|
|
||||||
|
|
||||||
var hasDirection = LinearGradientContainer.REGEXP_DIRECTION.test( imageData.args[0] ) ||
|
|
||||||
!GradientContainer.REGEXP_COLORSTOP.test( imageData.args[0] );
|
|
||||||
|
|
||||||
if (hasDirection) {
|
|
||||||
imageData.args[0].split(/\s+/).reverse().forEach(function(position, index) {
|
|
||||||
switch(position) {
|
|
||||||
case "left":
|
|
||||||
this.x0 = 0;
|
|
||||||
this.x1 = 1;
|
|
||||||
break;
|
|
||||||
case "top":
|
|
||||||
this.y0 = 0;
|
|
||||||
this.y1 = 1;
|
|
||||||
break;
|
|
||||||
case "right":
|
|
||||||
this.x0 = 1;
|
|
||||||
this.x1 = 0;
|
|
||||||
break;
|
|
||||||
case "bottom":
|
|
||||||
this.y0 = 1;
|
|
||||||
this.y1 = 0;
|
|
||||||
break;
|
|
||||||
case "to":
|
|
||||||
var y0 = this.y0;
|
|
||||||
var x0 = this.x0;
|
|
||||||
this.y0 = this.y1;
|
|
||||||
this.x0 = this.x1;
|
|
||||||
this.x1 = x0;
|
|
||||||
this.y1 = y0;
|
|
||||||
break;
|
|
||||||
case "center":
|
|
||||||
break; // centered by default
|
|
||||||
// Firefox internally converts position keywords to percentages:
|
|
||||||
// http://www.w3.org/TR/2010/WD-CSS2-20101207/colors.html#propdef-background-position
|
|
||||||
default: // percentage or absolute length
|
|
||||||
// TODO: support absolute start point positions (e.g., use bounds to convert px to a ratio)
|
|
||||||
var ratio = parseFloat(position, 10) * 1e-2;
|
|
||||||
if (isNaN(ratio)) { // invalid or unhandled value
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if (index === 0) {
|
|
||||||
this.y0 = ratio;
|
|
||||||
this.y1 = 1 - this.y0;
|
|
||||||
} else {
|
|
||||||
this.x0 = ratio;
|
|
||||||
this.x1 = 1 - this.x0;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}, this);
|
|
||||||
} else {
|
|
||||||
this.y0 = 0;
|
|
||||||
this.y1 = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.colorStops = imageData.args.slice(hasDirection ? 1 : 0).map(function(colorStop) {
|
|
||||||
var colorStopMatch = colorStop.match(GradientContainer.REGEXP_COLORSTOP);
|
|
||||||
var value = +colorStopMatch[2];
|
|
||||||
var unit = value === 0 ? "%" : colorStopMatch[3]; // treat "0" as "0%"
|
|
||||||
return {
|
|
||||||
color: new Color(colorStopMatch[1]),
|
|
||||||
// TODO: support absolute stop positions (e.g., compute gradient line length & convert px to ratio)
|
|
||||||
stop: unit === "%" ? value / 100 : null
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
if (this.colorStops[0].stop === null) {
|
|
||||||
this.colorStops[0].stop = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.colorStops[this.colorStops.length - 1].stop === null) {
|
|
||||||
this.colorStops[this.colorStops.length - 1].stop = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// calculates and fills-in explicit stop positions when omitted from rule
|
|
||||||
this.colorStops.forEach(function(colorStop, index) {
|
|
||||||
if (colorStop.stop === null) {
|
|
||||||
this.colorStops.slice(index).some(function(find, count) {
|
|
||||||
if (find.stop !== null) {
|
|
||||||
colorStop.stop = ((find.stop - this.colorStops[index - 1].stop) / (count + 1)) + this.colorStops[index - 1].stop;
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}, this);
|
|
||||||
}
|
|
||||||
}, this);
|
|
||||||
}
|
|
||||||
|
|
||||||
LinearGradientContainer.prototype = Object.create(GradientContainer.prototype);
|
|
||||||
|
|
||||||
// TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
|
|
||||||
LinearGradientContainer.REGEXP_DIRECTION = /^\s*(?:to|left|right|top|bottom|center|\d{1,3}(?:\.\d+)?%?)(?:\s|$)/i;
|
|
||||||
|
|
||||||
module.exports = LinearGradientContainer;
|
|
@ -1,8 +0,0 @@
|
|||||||
var logger = function() {
|
|
||||||
if (logger.options.logging && window.console && window.console.log) {
|
|
||||||
Function.prototype.bind.call(window.console.log, (window.console)).apply(window.console, [(Date.now() - logger.options.start) + "ms", "html2canvas:"].concat([].slice.call(arguments, 0)));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
logger.options = {logging: false};
|
|
||||||
module.exports = logger;
|
|
@ -1,296 +0,0 @@
|
|||||||
var Color = require('./color');
|
|
||||||
var utils = require('./utils');
|
|
||||||
var getBounds = utils.getBounds;
|
|
||||||
var parseBackgrounds = utils.parseBackgrounds;
|
|
||||||
var offsetBounds = utils.offsetBounds;
|
|
||||||
|
|
||||||
function NodeContainer(node, parent) {
|
|
||||||
this.node = node;
|
|
||||||
this.parent = parent;
|
|
||||||
this.stack = null;
|
|
||||||
this.bounds = null;
|
|
||||||
this.borders = null;
|
|
||||||
this.clip = [];
|
|
||||||
this.backgroundClip = [];
|
|
||||||
this.offsetBounds = null;
|
|
||||||
this.visible = null;
|
|
||||||
this.computedStyles = null;
|
|
||||||
this.colors = {};
|
|
||||||
this.styles = {};
|
|
||||||
this.backgroundImages = null;
|
|
||||||
this.transformData = null;
|
|
||||||
this.transformMatrix = null;
|
|
||||||
this.isPseudoElement = false;
|
|
||||||
this.opacity = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
NodeContainer.prototype.cloneTo = function(stack) {
|
|
||||||
stack.visible = this.visible;
|
|
||||||
stack.borders = this.borders;
|
|
||||||
stack.bounds = this.bounds;
|
|
||||||
stack.clip = this.clip;
|
|
||||||
stack.backgroundClip = this.backgroundClip;
|
|
||||||
stack.computedStyles = this.computedStyles;
|
|
||||||
stack.styles = this.styles;
|
|
||||||
stack.backgroundImages = this.backgroundImages;
|
|
||||||
stack.opacity = this.opacity;
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.getOpacity = function() {
|
|
||||||
return this.opacity === null ? (this.opacity = this.cssFloat('opacity')) : this.opacity;
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.assignStack = function(stack) {
|
|
||||||
this.stack = stack;
|
|
||||||
stack.children.push(this);
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.isElementVisible = function() {
|
|
||||||
return this.node.nodeType === Node.TEXT_NODE ? this.parent.visible : (
|
|
||||||
this.css('display') !== "none" &&
|
|
||||||
this.css('visibility') !== "hidden" &&
|
|
||||||
!this.node.hasAttribute("data-html2canvas-ignore") &&
|
|
||||||
(this.node.nodeName !== "INPUT" || this.node.getAttribute("type") !== "hidden")
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.css = function(attribute) {
|
|
||||||
if (!this.computedStyles) {
|
|
||||||
this.computedStyles = this.isPseudoElement ? this.parent.computedStyle(this.before ? ":before" : ":after") : this.computedStyle(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.styles[attribute] || (this.styles[attribute] = this.computedStyles[attribute]);
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.prefixedCss = function(attribute) {
|
|
||||||
var prefixes = ["webkit", "moz", "ms", "o"];
|
|
||||||
var value = this.css(attribute);
|
|
||||||
if (value === undefined) {
|
|
||||||
prefixes.some(function(prefix) {
|
|
||||||
value = this.css(prefix + attribute.substr(0, 1).toUpperCase() + attribute.substr(1));
|
|
||||||
return value !== undefined;
|
|
||||||
}, this);
|
|
||||||
}
|
|
||||||
return value === undefined ? null : value;
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.computedStyle = function(type) {
|
|
||||||
return this.node.ownerDocument.defaultView.getComputedStyle(this.node, type);
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.cssInt = function(attribute) {
|
|
||||||
var value = parseInt(this.css(attribute), 10);
|
|
||||||
return (isNaN(value)) ? 0 : value; // borders in old IE are throwing 'medium' for demo.html
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.color = function(attribute) {
|
|
||||||
return this.colors[attribute] || (this.colors[attribute] = new Color(this.css(attribute)));
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.cssFloat = function(attribute) {
|
|
||||||
var value = parseFloat(this.css(attribute));
|
|
||||||
return (isNaN(value)) ? 0 : value;
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.fontWeight = function() {
|
|
||||||
var weight = this.css("fontWeight");
|
|
||||||
switch(parseInt(weight, 10)){
|
|
||||||
case 401:
|
|
||||||
weight = "bold";
|
|
||||||
break;
|
|
||||||
case 400:
|
|
||||||
weight = "normal";
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
return weight;
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.parseClip = function() {
|
|
||||||
var matches = this.css('clip').match(this.CLIP);
|
|
||||||
if (matches) {
|
|
||||||
return {
|
|
||||||
top: parseInt(matches[1], 10),
|
|
||||||
right: parseInt(matches[2], 10),
|
|
||||||
bottom: parseInt(matches[3], 10),
|
|
||||||
left: parseInt(matches[4], 10)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.parseBackgroundImages = function() {
|
|
||||||
return this.backgroundImages || (this.backgroundImages = parseBackgrounds(this.css("backgroundImage")));
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.cssList = function(property, index) {
|
|
||||||
var value = (this.css(property) || '').split(',');
|
|
||||||
value = value[index || 0] || value[0] || 'auto';
|
|
||||||
value = value.trim().split(' ');
|
|
||||||
if (value.length === 1) {
|
|
||||||
value = [value[0], isPercentage(value[0]) ? 'auto' : value[0]];
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.parseBackgroundSize = function(bounds, image, index) {
|
|
||||||
var size = this.cssList("backgroundSize", index);
|
|
||||||
var width, height;
|
|
||||||
|
|
||||||
if (isPercentage(size[0])) {
|
|
||||||
width = bounds.width * parseFloat(size[0]) / 100;
|
|
||||||
} else if (/contain|cover/.test(size[0])) {
|
|
||||||
var targetRatio = bounds.width / bounds.height, currentRatio = image.width / image.height;
|
|
||||||
return (targetRatio < currentRatio ^ size[0] === 'contain') ? {width: bounds.height * currentRatio, height: bounds.height} : {width: bounds.width, height: bounds.width / currentRatio};
|
|
||||||
} else {
|
|
||||||
width = parseInt(size[0], 10);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (size[0] === 'auto' && size[1] === 'auto') {
|
|
||||||
height = image.height;
|
|
||||||
} else if (size[1] === 'auto') {
|
|
||||||
height = width / image.width * image.height;
|
|
||||||
} else if (isPercentage(size[1])) {
|
|
||||||
height = bounds.height * parseFloat(size[1]) / 100;
|
|
||||||
} else {
|
|
||||||
height = parseInt(size[1], 10);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (size[0] === 'auto') {
|
|
||||||
width = height / image.height * image.width;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {width: width, height: height};
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.parseBackgroundPosition = function(bounds, image, index, backgroundSize) {
|
|
||||||
var position = this.cssList('backgroundPosition', index);
|
|
||||||
var left, top;
|
|
||||||
|
|
||||||
if (isPercentage(position[0])){
|
|
||||||
left = (bounds.width - (backgroundSize || image).width) * (parseFloat(position[0]) / 100);
|
|
||||||
} else {
|
|
||||||
left = parseInt(position[0], 10);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (position[1] === 'auto') {
|
|
||||||
top = left / image.width * image.height;
|
|
||||||
} else if (isPercentage(position[1])){
|
|
||||||
top = (bounds.height - (backgroundSize || image).height) * parseFloat(position[1]) / 100;
|
|
||||||
} else {
|
|
||||||
top = parseInt(position[1], 10);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (position[0] === 'auto') {
|
|
||||||
left = top / image.height * image.width;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {left: left, top: top};
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.parseBackgroundRepeat = function(index) {
|
|
||||||
return this.cssList("backgroundRepeat", index)[0];
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.parseTextShadows = function() {
|
|
||||||
var textShadow = this.css("textShadow");
|
|
||||||
var results = [];
|
|
||||||
|
|
||||||
if (textShadow && textShadow !== 'none') {
|
|
||||||
var shadows = textShadow.match(this.TEXT_SHADOW_PROPERTY);
|
|
||||||
for (var i = 0; shadows && (i < shadows.length); i++) {
|
|
||||||
var s = shadows[i].match(this.TEXT_SHADOW_VALUES);
|
|
||||||
results.push({
|
|
||||||
color: new Color(s[0]),
|
|
||||||
offsetX: s[1] ? parseFloat(s[1].replace('px', '')) : 0,
|
|
||||||
offsetY: s[2] ? parseFloat(s[2].replace('px', '')) : 0,
|
|
||||||
blur: s[3] ? s[3].replace('px', '') : 0
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return results;
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.parseTransform = function() {
|
|
||||||
if (!this.transformData) {
|
|
||||||
if (this.hasTransform()) {
|
|
||||||
var offset = this.parseBounds();
|
|
||||||
var origin = this.prefixedCss("transformOrigin").split(" ").map(removePx).map(asFloat);
|
|
||||||
origin[0] += offset.left;
|
|
||||||
origin[1] += offset.top;
|
|
||||||
this.transformData = {
|
|
||||||
origin: origin,
|
|
||||||
matrix: this.parseTransformMatrix()
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
this.transformData = {
|
|
||||||
origin: [0, 0],
|
|
||||||
matrix: [1, 0, 0, 1, 0, 0]
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return this.transformData;
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.parseTransformMatrix = function() {
|
|
||||||
if (!this.transformMatrix) {
|
|
||||||
var transform = this.prefixedCss("transform");
|
|
||||||
var matrix = transform ? parseMatrix(transform.match(this.MATRIX_PROPERTY)) : null;
|
|
||||||
this.transformMatrix = matrix ? matrix : [1, 0, 0, 1, 0, 0];
|
|
||||||
}
|
|
||||||
return this.transformMatrix;
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.parseBounds = function() {
|
|
||||||
return this.bounds || (this.bounds = this.hasTransform() ? offsetBounds(this.node) : getBounds(this.node));
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.hasTransform = function() {
|
|
||||||
return this.parseTransformMatrix().join(",") !== "1,0,0,1,0,0" || (this.parent && this.parent.hasTransform());
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.getValue = function() {
|
|
||||||
var value = this.node.value || "";
|
|
||||||
if (this.node.tagName === "SELECT") {
|
|
||||||
value = selectionValue(this.node);
|
|
||||||
} else if (this.node.type === "password") {
|
|
||||||
value = Array(value.length + 1).join('\u2022'); // jshint ignore:line
|
|
||||||
}
|
|
||||||
return value.length === 0 ? (this.node.placeholder || "") : value;
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeContainer.prototype.MATRIX_PROPERTY = /(matrix|matrix3d)\((.+)\)/;
|
|
||||||
NodeContainer.prototype.TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g;
|
|
||||||
NodeContainer.prototype.TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g;
|
|
||||||
NodeContainer.prototype.CLIP = /^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/;
|
|
||||||
|
|
||||||
function selectionValue(node) {
|
|
||||||
var option = node.options[node.selectedIndex || 0];
|
|
||||||
return option ? (option.text || "") : "";
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseMatrix(match) {
|
|
||||||
if (match && match[1] === "matrix") {
|
|
||||||
return match[2].split(",").map(function(s) {
|
|
||||||
return parseFloat(s.trim());
|
|
||||||
});
|
|
||||||
} else if (match && match[1] === "matrix3d") {
|
|
||||||
var matrix3d = match[2].split(",").map(function(s) {
|
|
||||||
return parseFloat(s.trim());
|
|
||||||
});
|
|
||||||
return [matrix3d[0], matrix3d[1], matrix3d[4], matrix3d[5], matrix3d[12], matrix3d[13]];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function isPercentage(value) {
|
|
||||||
return value.toString().indexOf("%") !== -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
function removePx(str) {
|
|
||||||
return str.replace("px", "");
|
|
||||||
}
|
|
||||||
|
|
||||||
function asFloat(str) {
|
|
||||||
return parseFloat(str);
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = NodeContainer;
|
|
@ -1,869 +0,0 @@
|
|||||||
var log = require('./log');
|
|
||||||
var punycode = require('punycode');
|
|
||||||
var NodeContainer = require('./nodecontainer');
|
|
||||||
var TextContainer = require('./textcontainer');
|
|
||||||
var PseudoElementContainer = require('./pseudoelementcontainer');
|
|
||||||
var FontMetrics = require('./fontmetrics');
|
|
||||||
var Color = require('./color');
|
|
||||||
var StackingContext = require('./stackingcontext');
|
|
||||||
var utils = require('./utils');
|
|
||||||
var bind = utils.bind;
|
|
||||||
var getBounds = utils.getBounds;
|
|
||||||
var parseBackgrounds = utils.parseBackgrounds;
|
|
||||||
var offsetBounds = utils.offsetBounds;
|
|
||||||
|
|
||||||
function NodeParser(element, renderer, support, imageLoader, options) {
|
|
||||||
log("Starting NodeParser");
|
|
||||||
this.renderer = renderer;
|
|
||||||
this.options = options;
|
|
||||||
this.range = null;
|
|
||||||
this.support = support;
|
|
||||||
this.renderQueue = [];
|
|
||||||
this.stack = new StackingContext(true, 1, element.ownerDocument, null);
|
|
||||||
var parent = new NodeContainer(element, null);
|
|
||||||
if (options.background) {
|
|
||||||
renderer.rectangle(0, 0, renderer.width, renderer.height, new Color(options.background));
|
|
||||||
}
|
|
||||||
if (element === element.ownerDocument.documentElement) {
|
|
||||||
// http://www.w3.org/TR/css3-background/#special-backgrounds
|
|
||||||
var canvasBackground = new NodeContainer(parent.color('backgroundColor').isTransparent() ? element.ownerDocument.body : element.ownerDocument.documentElement, null);
|
|
||||||
renderer.rectangle(0, 0, renderer.width, renderer.height, canvasBackground.color('backgroundColor'));
|
|
||||||
}
|
|
||||||
parent.visibile = parent.isElementVisible();
|
|
||||||
this.createPseudoHideStyles(element.ownerDocument);
|
|
||||||
this.disableAnimations(element.ownerDocument);
|
|
||||||
this.nodes = flatten([parent].concat(this.getChildren(parent)).filter(function(container) {
|
|
||||||
return container.visible = container.isElementVisible();
|
|
||||||
}).map(this.getPseudoElements, this));
|
|
||||||
this.fontMetrics = new FontMetrics();
|
|
||||||
log("Fetched nodes, total:", this.nodes.length);
|
|
||||||
log("Calculate overflow clips");
|
|
||||||
this.calculateOverflowClips();
|
|
||||||
log("Start fetching images");
|
|
||||||
this.images = imageLoader.fetch(this.nodes.filter(isElement));
|
|
||||||
this.ready = this.images.ready.then(bind(function() {
|
|
||||||
log("Images loaded, starting parsing");
|
|
||||||
log("Creating stacking contexts");
|
|
||||||
this.createStackingContexts();
|
|
||||||
log("Sorting stacking contexts");
|
|
||||||
this.sortStackingContexts(this.stack);
|
|
||||||
this.parse(this.stack);
|
|
||||||
log("Render queue created with " + this.renderQueue.length + " items");
|
|
||||||
return new Promise(bind(function(resolve) {
|
|
||||||
if (!options.async) {
|
|
||||||
this.renderQueue.forEach(this.paint, this);
|
|
||||||
resolve();
|
|
||||||
} else if (typeof(options.async) === "function") {
|
|
||||||
options.async.call(this, this.renderQueue, resolve);
|
|
||||||
} else if (this.renderQueue.length > 0){
|
|
||||||
this.renderIndex = 0;
|
|
||||||
this.asyncRenderer(this.renderQueue, resolve);
|
|
||||||
} else {
|
|
||||||
resolve();
|
|
||||||
}
|
|
||||||
}, this));
|
|
||||||
}, this));
|
|
||||||
}
|
|
||||||
|
|
||||||
NodeParser.prototype.calculateOverflowClips = function() {
|
|
||||||
this.nodes.forEach(function(container) {
|
|
||||||
if (isElement(container)) {
|
|
||||||
if (isPseudoElement(container)) {
|
|
||||||
container.appendToDOM();
|
|
||||||
}
|
|
||||||
container.borders = this.parseBorders(container);
|
|
||||||
var clip = (container.css('overflow') === "hidden") ? [container.borders.clip] : [];
|
|
||||||
var cssClip = container.parseClip();
|
|
||||||
if (cssClip && ["absolute", "fixed"].indexOf(container.css('position')) !== -1) {
|
|
||||||
clip.push([["rect",
|
|
||||||
container.bounds.left + cssClip.left,
|
|
||||||
container.bounds.top + cssClip.top,
|
|
||||||
cssClip.right - cssClip.left,
|
|
||||||
cssClip.bottom - cssClip.top
|
|
||||||
]]);
|
|
||||||
}
|
|
||||||
container.clip = hasParentClip(container) ? container.parent.clip.concat(clip) : clip;
|
|
||||||
container.backgroundClip = (container.css('overflow') !== "hidden") ? container.clip.concat([container.borders.clip]) : container.clip;
|
|
||||||
if (isPseudoElement(container)) {
|
|
||||||
container.cleanDOM();
|
|
||||||
}
|
|
||||||
} else if (isTextNode(container)) {
|
|
||||||
container.clip = hasParentClip(container) ? container.parent.clip : [];
|
|
||||||
}
|
|
||||||
if (!isPseudoElement(container)) {
|
|
||||||
container.bounds = null;
|
|
||||||
}
|
|
||||||
}, this);
|
|
||||||
};
|
|
||||||
|
|
||||||
function hasParentClip(container) {
|
|
||||||
return container.parent && container.parent.clip.length;
|
|
||||||
}
|
|
||||||
|
|
||||||
NodeParser.prototype.asyncRenderer = function(queue, resolve, asyncTimer) {
|
|
||||||
asyncTimer = asyncTimer || Date.now();
|
|
||||||
this.paint(queue[this.renderIndex++]);
|
|
||||||
if (queue.length === this.renderIndex) {
|
|
||||||
resolve();
|
|
||||||
} else if (asyncTimer + 20 > Date.now()) {
|
|
||||||
this.asyncRenderer(queue, resolve, asyncTimer);
|
|
||||||
} else {
|
|
||||||
setTimeout(bind(function() {
|
|
||||||
this.asyncRenderer(queue, resolve);
|
|
||||||
}, this), 0);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.createPseudoHideStyles = function(document) {
|
|
||||||
this.createStyles(document, '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ':before { content: "" !important; display: none !important; }' +
|
|
||||||
'.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER + ':after { content: "" !important; display: none !important; }');
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.disableAnimations = function(document) {
|
|
||||||
this.createStyles(document, '* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; ' +
|
|
||||||
'-webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}');
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.createStyles = function(document, styles) {
|
|
||||||
var hidePseudoElements = document.createElement('style');
|
|
||||||
hidePseudoElements.innerHTML = styles;
|
|
||||||
document.body.appendChild(hidePseudoElements);
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.getPseudoElements = function(container) {
|
|
||||||
var nodes = [[container]];
|
|
||||||
if (container.node.nodeType === Node.ELEMENT_NODE) {
|
|
||||||
var before = this.getPseudoElement(container, ":before");
|
|
||||||
var after = this.getPseudoElement(container, ":after");
|
|
||||||
|
|
||||||
if (before) {
|
|
||||||
nodes.push(before);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (after) {
|
|
||||||
nodes.push(after);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return flatten(nodes);
|
|
||||||
};
|
|
||||||
|
|
||||||
function toCamelCase(str) {
|
|
||||||
return str.replace(/(\-[a-z])/g, function(match){
|
|
||||||
return match.toUpperCase().replace('-','');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
NodeParser.prototype.getPseudoElement = function(container, type) {
|
|
||||||
var style = container.computedStyle(type);
|
|
||||||
if(!style || !style.content || style.content === "none" || style.content === "-moz-alt-content" || style.display === "none") {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
var content = stripQuotes(style.content);
|
|
||||||
var isImage = content.substr(0, 3) === 'url';
|
|
||||||
var pseudoNode = document.createElement(isImage ? 'img' : 'html2canvaspseudoelement');
|
|
||||||
var pseudoContainer = new PseudoElementContainer(pseudoNode, container, type);
|
|
||||||
|
|
||||||
for (var i = style.length-1; i >= 0; i--) {
|
|
||||||
var property = toCamelCase(style.item(i));
|
|
||||||
pseudoNode.style[property] = style[property];
|
|
||||||
}
|
|
||||||
|
|
||||||
pseudoNode.className = PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
|
|
||||||
|
|
||||||
if (isImage) {
|
|
||||||
pseudoNode.src = parseBackgrounds(content)[0].args[0];
|
|
||||||
return [pseudoContainer];
|
|
||||||
} else {
|
|
||||||
var text = document.createTextNode(content);
|
|
||||||
pseudoNode.appendChild(text);
|
|
||||||
return [pseudoContainer, new TextContainer(text, pseudoContainer)];
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
NodeParser.prototype.getChildren = function(parentContainer) {
|
|
||||||
return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) {
|
|
||||||
var container = [node.nodeType === Node.TEXT_NODE ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
|
|
||||||
return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container;
|
|
||||||
}, this));
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.newStackingContext = function(container, hasOwnStacking) {
|
|
||||||
var stack = new StackingContext(hasOwnStacking, container.getOpacity(), container.node, container.parent);
|
|
||||||
container.cloneTo(stack);
|
|
||||||
var parentStack = hasOwnStacking ? stack.getParentStack(this) : stack.parent.stack;
|
|
||||||
parentStack.contexts.push(stack);
|
|
||||||
container.stack = stack;
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.createStackingContexts = function() {
|
|
||||||
this.nodes.forEach(function(container) {
|
|
||||||
if (isElement(container) && (this.isRootElement(container) || hasOpacity(container) || isPositionedForStacking(container) || this.isBodyWithTransparentRoot(container) || container.hasTransform())) {
|
|
||||||
this.newStackingContext(container, true);
|
|
||||||
} else if (isElement(container) && ((isPositioned(container) && zIndex0(container)) || isInlineBlock(container) || isFloating(container))) {
|
|
||||||
this.newStackingContext(container, false);
|
|
||||||
} else {
|
|
||||||
container.assignStack(container.parent.stack);
|
|
||||||
}
|
|
||||||
}, this);
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.isBodyWithTransparentRoot = function(container) {
|
|
||||||
return container.node.nodeName === "BODY" && container.parent.color('backgroundColor').isTransparent();
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.isRootElement = function(container) {
|
|
||||||
return container.parent === null;
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.sortStackingContexts = function(stack) {
|
|
||||||
stack.contexts.sort(zIndexSort(stack.contexts.slice(0)));
|
|
||||||
stack.contexts.forEach(this.sortStackingContexts, this);
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.parseTextBounds = function(container) {
|
|
||||||
return function(text, index, textList) {
|
|
||||||
if (container.parent.css("textDecoration").substr(0, 4) !== "none" || text.trim().length !== 0) {
|
|
||||||
if (this.support.rangeBounds && !container.parent.hasTransform()) {
|
|
||||||
var offset = textList.slice(0, index).join("").length;
|
|
||||||
return this.getRangeBounds(container.node, offset, text.length);
|
|
||||||
} else if (container.node && typeof(container.node.data) === "string") {
|
|
||||||
var replacementNode = container.node.splitText(text.length);
|
|
||||||
var bounds = this.getWrapperBounds(container.node, container.parent.hasTransform());
|
|
||||||
container.node = replacementNode;
|
|
||||||
return bounds;
|
|
||||||
}
|
|
||||||
} else if(!this.support.rangeBounds || container.parent.hasTransform()){
|
|
||||||
container.node = container.node.splitText(text.length);
|
|
||||||
}
|
|
||||||
return {};
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.getWrapperBounds = function(node, transform) {
|
|
||||||
var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
|
|
||||||
var parent = node.parentNode,
|
|
||||||
backupText = node.cloneNode(true);
|
|
||||||
|
|
||||||
wrapper.appendChild(node.cloneNode(true));
|
|
||||||
parent.replaceChild(wrapper, node);
|
|
||||||
var bounds = transform ? offsetBounds(wrapper) : getBounds(wrapper);
|
|
||||||
parent.replaceChild(backupText, wrapper);
|
|
||||||
return bounds;
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.getRangeBounds = function(node, offset, length) {
|
|
||||||
var range = this.range || (this.range = node.ownerDocument.createRange());
|
|
||||||
range.setStart(node, offset);
|
|
||||||
range.setEnd(node, offset + length);
|
|
||||||
return range.getBoundingClientRect();
|
|
||||||
};
|
|
||||||
|
|
||||||
function ClearTransform() {}
|
|
||||||
|
|
||||||
NodeParser.prototype.parse = function(stack) {
|
|
||||||
// http://www.w3.org/TR/CSS21/visuren.html#z-index
|
|
||||||
var negativeZindex = stack.contexts.filter(negativeZIndex); // 2. the child stacking contexts with negative stack levels (most negative first).
|
|
||||||
var descendantElements = stack.children.filter(isElement);
|
|
||||||
var descendantNonFloats = descendantElements.filter(not(isFloating));
|
|
||||||
var nonInlineNonPositionedDescendants = descendantNonFloats.filter(not(isPositioned)).filter(not(inlineLevel)); // 3 the in-flow, non-inline-level, non-positioned descendants.
|
|
||||||
var nonPositionedFloats = descendantElements.filter(not(isPositioned)).filter(isFloating); // 4. the non-positioned floats.
|
|
||||||
var inFlow = descendantNonFloats.filter(not(isPositioned)).filter(inlineLevel); // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
|
|
||||||
var stackLevel0 = stack.contexts.concat(descendantNonFloats.filter(isPositioned)).filter(zIndex0); // 6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
|
|
||||||
var text = stack.children.filter(isTextNode).filter(hasText);
|
|
||||||
var positiveZindex = stack.contexts.filter(positiveZIndex); // 7. the child stacking contexts with positive stack levels (least positive first).
|
|
||||||
negativeZindex.concat(nonInlineNonPositionedDescendants).concat(nonPositionedFloats)
|
|
||||||
.concat(inFlow).concat(stackLevel0).concat(text).concat(positiveZindex).forEach(function(container) {
|
|
||||||
this.renderQueue.push(container);
|
|
||||||
if (isStackingContext(container)) {
|
|
||||||
this.parse(container);
|
|
||||||
this.renderQueue.push(new ClearTransform());
|
|
||||||
}
|
|
||||||
}, this);
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.paint = function(container) {
|
|
||||||
try {
|
|
||||||
if (container instanceof ClearTransform) {
|
|
||||||
this.renderer.ctx.restore();
|
|
||||||
} else if (isTextNode(container)) {
|
|
||||||
if (isPseudoElement(container.parent)) {
|
|
||||||
container.parent.appendToDOM();
|
|
||||||
}
|
|
||||||
this.paintText(container);
|
|
||||||
if (isPseudoElement(container.parent)) {
|
|
||||||
container.parent.cleanDOM();
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
this.paintNode(container);
|
|
||||||
}
|
|
||||||
} catch(e) {
|
|
||||||
log(e);
|
|
||||||
if (this.options.strict) {
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.paintNode = function(container) {
|
|
||||||
if (isStackingContext(container)) {
|
|
||||||
this.renderer.setOpacity(container.opacity);
|
|
||||||
this.renderer.ctx.save();
|
|
||||||
if (container.hasTransform()) {
|
|
||||||
this.renderer.setTransform(container.parseTransform());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (container.node.nodeName === "INPUT" && container.node.type === "checkbox") {
|
|
||||||
this.paintCheckbox(container);
|
|
||||||
} else if (container.node.nodeName === "INPUT" && container.node.type === "radio") {
|
|
||||||
this.paintRadio(container);
|
|
||||||
} else {
|
|
||||||
this.paintElement(container);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.paintElement = function(container) {
|
|
||||||
var bounds = container.parseBounds();
|
|
||||||
this.renderer.clip(container.backgroundClip, function() {
|
|
||||||
this.renderer.renderBackground(container, bounds, container.borders.borders.map(getWidth));
|
|
||||||
}, this);
|
|
||||||
|
|
||||||
this.renderer.clip(container.clip, function() {
|
|
||||||
this.renderer.renderBorders(container.borders.borders);
|
|
||||||
}, this);
|
|
||||||
|
|
||||||
this.renderer.clip(container.backgroundClip, function() {
|
|
||||||
switch (container.node.nodeName) {
|
|
||||||
case "svg":
|
|
||||||
case "IFRAME":
|
|
||||||
var imgContainer = this.images.get(container.node);
|
|
||||||
if (imgContainer) {
|
|
||||||
this.renderer.renderImage(container, bounds, container.borders, imgContainer);
|
|
||||||
} else {
|
|
||||||
log("Error loading <" + container.node.nodeName + ">", container.node);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case "IMG":
|
|
||||||
var imageContainer = this.images.get(container.node.src);
|
|
||||||
if (imageContainer) {
|
|
||||||
this.renderer.renderImage(container, bounds, container.borders, imageContainer);
|
|
||||||
} else {
|
|
||||||
log("Error loading <img>", container.node.src);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case "CANVAS":
|
|
||||||
this.renderer.renderImage(container, bounds, container.borders, {image: container.node});
|
|
||||||
break;
|
|
||||||
case "SELECT":
|
|
||||||
case "INPUT":
|
|
||||||
case "TEXTAREA":
|
|
||||||
this.paintFormValue(container);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}, this);
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.paintCheckbox = function(container) {
|
|
||||||
var b = container.parseBounds();
|
|
||||||
|
|
||||||
var size = Math.min(b.width, b.height);
|
|
||||||
var bounds = {width: size - 1, height: size - 1, top: b.top, left: b.left};
|
|
||||||
var r = [3, 3];
|
|
||||||
var radius = [r, r, r, r];
|
|
||||||
var borders = [1,1,1,1].map(function(w) {
|
|
||||||
return {color: new Color('#A5A5A5'), width: w};
|
|
||||||
});
|
|
||||||
|
|
||||||
var borderPoints = calculateCurvePoints(bounds, radius, borders);
|
|
||||||
|
|
||||||
this.renderer.clip(container.backgroundClip, function() {
|
|
||||||
this.renderer.rectangle(bounds.left + 1, bounds.top + 1, bounds.width - 2, bounds.height - 2, new Color("#DEDEDE"));
|
|
||||||
this.renderer.renderBorders(calculateBorders(borders, bounds, borderPoints, radius));
|
|
||||||
if (container.node.checked) {
|
|
||||||
this.renderer.font(new Color('#424242'), 'normal', 'normal', 'bold', (size - 3) + "px", 'arial');
|
|
||||||
this.renderer.text("\u2714", bounds.left + size / 6, bounds.top + size - 1);
|
|
||||||
}
|
|
||||||
}, this);
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.paintRadio = function(container) {
|
|
||||||
var bounds = container.parseBounds();
|
|
||||||
|
|
||||||
var size = Math.min(bounds.width, bounds.height) - 2;
|
|
||||||
|
|
||||||
this.renderer.clip(container.backgroundClip, function() {
|
|
||||||
this.renderer.circleStroke(bounds.left + 1, bounds.top + 1, size, new Color('#DEDEDE'), 1, new Color('#A5A5A5'));
|
|
||||||
if (container.node.checked) {
|
|
||||||
this.renderer.circle(Math.ceil(bounds.left + size / 4) + 1, Math.ceil(bounds.top + size / 4) + 1, Math.floor(size / 2), new Color('#424242'));
|
|
||||||
}
|
|
||||||
}, this);
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.paintFormValue = function(container) {
|
|
||||||
var value = container.getValue();
|
|
||||||
if (value.length > 0) {
|
|
||||||
var document = container.node.ownerDocument;
|
|
||||||
var wrapper = document.createElement('html2canvaswrapper');
|
|
||||||
var properties = ['lineHeight', 'textAlign', 'fontFamily', 'fontWeight', 'fontSize', 'color',
|
|
||||||
'paddingLeft', 'paddingTop', 'paddingRight', 'paddingBottom',
|
|
||||||
'width', 'height', 'borderLeftStyle', 'borderTopStyle', 'borderLeftWidth', 'borderTopWidth',
|
|
||||||
'boxSizing', 'whiteSpace', 'wordWrap'];
|
|
||||||
|
|
||||||
properties.forEach(function(property) {
|
|
||||||
try {
|
|
||||||
wrapper.style[property] = container.css(property);
|
|
||||||
} catch(e) {
|
|
||||||
// Older IE has issues with "border"
|
|
||||||
log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
var bounds = container.parseBounds();
|
|
||||||
wrapper.style.position = "fixed";
|
|
||||||
wrapper.style.left = bounds.left + "px";
|
|
||||||
wrapper.style.top = bounds.top + "px";
|
|
||||||
wrapper.textContent = value;
|
|
||||||
document.body.appendChild(wrapper);
|
|
||||||
this.paintText(new TextContainer(wrapper.firstChild, container));
|
|
||||||
document.body.removeChild(wrapper);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.paintText = function(container) {
|
|
||||||
container.applyTextTransform();
|
|
||||||
var characters = punycode.ucs2.decode(container.node.data);
|
|
||||||
var textList = (!this.options.letterRendering || noLetterSpacing(container)) && !hasUnicode(container.node.data) ? getWords(characters) : characters.map(function(character) {
|
|
||||||
return punycode.ucs2.encode([character]);
|
|
||||||
});
|
|
||||||
|
|
||||||
var weight = container.parent.fontWeight();
|
|
||||||
var size = container.parent.css('fontSize');
|
|
||||||
var family = container.parent.css('fontFamily');
|
|
||||||
var shadows = container.parent.parseTextShadows();
|
|
||||||
|
|
||||||
this.renderer.font(container.parent.color('color'), container.parent.css('fontStyle'), container.parent.css('fontVariant'), weight, size, family);
|
|
||||||
if (shadows.length) {
|
|
||||||
// TODO: support multiple text shadows
|
|
||||||
this.renderer.fontShadow(shadows[0].color, shadows[0].offsetX, shadows[0].offsetY, shadows[0].blur);
|
|
||||||
} else {
|
|
||||||
this.renderer.clearShadow();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.renderer.clip(container.parent.clip, function() {
|
|
||||||
textList.map(this.parseTextBounds(container), this).forEach(function(bounds, index) {
|
|
||||||
if (bounds) {
|
|
||||||
this.renderer.text(textList[index], bounds.left, bounds.bottom);
|
|
||||||
this.renderTextDecoration(container.parent, bounds, this.fontMetrics.getMetrics(family, size));
|
|
||||||
}
|
|
||||||
}, this);
|
|
||||||
}, this);
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.renderTextDecoration = function(container, bounds, metrics) {
|
|
||||||
switch(container.css("textDecoration").split(" ")[0]) {
|
|
||||||
case "underline":
|
|
||||||
// Draws a line at the baseline of the font
|
|
||||||
// TODO As some browsers display the line as more than 1px if the font-size is big, need to take that into account both in position and size
|
|
||||||
this.renderer.rectangle(bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, container.color("color"));
|
|
||||||
break;
|
|
||||||
case "overline":
|
|
||||||
this.renderer.rectangle(bounds.left, Math.round(bounds.top), bounds.width, 1, container.color("color"));
|
|
||||||
break;
|
|
||||||
case "line-through":
|
|
||||||
// TODO try and find exact position for line-through
|
|
||||||
this.renderer.rectangle(bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, container.color("color"));
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
var borderColorTransforms = {
|
|
||||||
inset: [
|
|
||||||
["darken", 0.60],
|
|
||||||
["darken", 0.10],
|
|
||||||
["darken", 0.10],
|
|
||||||
["darken", 0.60]
|
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeParser.prototype.parseBorders = function(container) {
|
|
||||||
var nodeBounds = container.parseBounds();
|
|
||||||
var radius = getBorderRadiusData(container);
|
|
||||||
var borders = ["Top", "Right", "Bottom", "Left"].map(function(side, index) {
|
|
||||||
var style = container.css('border' + side + 'Style');
|
|
||||||
var color = container.color('border' + side + 'Color');
|
|
||||||
if (style === "inset" && color.isBlack()) {
|
|
||||||
color = new Color([255, 255, 255, color.a]); // this is wrong, but
|
|
||||||
}
|
|
||||||
var colorTransform = borderColorTransforms[style] ? borderColorTransforms[style][index] : null;
|
|
||||||
return {
|
|
||||||
width: container.cssInt('border' + side + 'Width'),
|
|
||||||
color: colorTransform ? color[colorTransform[0]](colorTransform[1]) : color,
|
|
||||||
args: null
|
|
||||||
};
|
|
||||||
});
|
|
||||||
var borderPoints = calculateCurvePoints(nodeBounds, radius, borders);
|
|
||||||
|
|
||||||
return {
|
|
||||||
clip: this.parseBackgroundClip(container, borderPoints, borders, radius, nodeBounds),
|
|
||||||
borders: calculateBorders(borders, nodeBounds, borderPoints, radius)
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
function calculateBorders(borders, nodeBounds, borderPoints, radius) {
|
|
||||||
return borders.map(function(border, borderSide) {
|
|
||||||
if (border.width > 0) {
|
|
||||||
var bx = nodeBounds.left;
|
|
||||||
var by = nodeBounds.top;
|
|
||||||
var bw = nodeBounds.width;
|
|
||||||
var bh = nodeBounds.height - (borders[2].width);
|
|
||||||
|
|
||||||
switch(borderSide) {
|
|
||||||
case 0:
|
|
||||||
// top border
|
|
||||||
bh = borders[0].width;
|
|
||||||
border.args = drawSide({
|
|
||||||
c1: [bx, by],
|
|
||||||
c2: [bx + bw, by],
|
|
||||||
c3: [bx + bw - borders[1].width, by + bh],
|
|
||||||
c4: [bx + borders[3].width, by + bh]
|
|
||||||
}, radius[0], radius[1],
|
|
||||||
borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner);
|
|
||||||
break;
|
|
||||||
case 1:
|
|
||||||
// right border
|
|
||||||
bx = nodeBounds.left + nodeBounds.width - (borders[1].width);
|
|
||||||
bw = borders[1].width;
|
|
||||||
|
|
||||||
border.args = drawSide({
|
|
||||||
c1: [bx + bw, by],
|
|
||||||
c2: [bx + bw, by + bh + borders[2].width],
|
|
||||||
c3: [bx, by + bh],
|
|
||||||
c4: [bx, by + borders[0].width]
|
|
||||||
}, radius[1], radius[2],
|
|
||||||
borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner);
|
|
||||||
break;
|
|
||||||
case 2:
|
|
||||||
// bottom border
|
|
||||||
by = (by + nodeBounds.height) - (borders[2].width);
|
|
||||||
bh = borders[2].width;
|
|
||||||
border.args = drawSide({
|
|
||||||
c1: [bx + bw, by + bh],
|
|
||||||
c2: [bx, by + bh],
|
|
||||||
c3: [bx + borders[3].width, by],
|
|
||||||
c4: [bx + bw - borders[3].width, by]
|
|
||||||
}, radius[2], radius[3],
|
|
||||||
borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner);
|
|
||||||
break;
|
|
||||||
case 3:
|
|
||||||
// left border
|
|
||||||
bw = borders[3].width;
|
|
||||||
border.args = drawSide({
|
|
||||||
c1: [bx, by + bh + borders[2].width],
|
|
||||||
c2: [bx, by],
|
|
||||||
c3: [bx + bw, by + borders[0].width],
|
|
||||||
c4: [bx + bw, by + bh]
|
|
||||||
}, radius[3], radius[0],
|
|
||||||
borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return border;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
NodeParser.prototype.parseBackgroundClip = function(container, borderPoints, borders, radius, bounds) {
|
|
||||||
var backgroundClip = container.css('backgroundClip'),
|
|
||||||
borderArgs = [];
|
|
||||||
|
|
||||||
switch(backgroundClip) {
|
|
||||||
case "content-box":
|
|
||||||
case "padding-box":
|
|
||||||
parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width);
|
|
||||||
parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width);
|
|
||||||
parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width);
|
|
||||||
parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width);
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top);
|
|
||||||
parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top);
|
|
||||||
parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height);
|
|
||||||
parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
return borderArgs;
|
|
||||||
};
|
|
||||||
|
|
||||||
function getCurvePoints(x, y, r1, r2) {
|
|
||||||
var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
|
|
||||||
var ox = (r1) * kappa, // control point offset horizontal
|
|
||||||
oy = (r2) * kappa, // control point offset vertical
|
|
||||||
xm = x + r1, // x-middle
|
|
||||||
ym = y + r2; // y-middle
|
|
||||||
return {
|
|
||||||
topLeft: bezierCurve({x: x, y: ym}, {x: x, y: ym - oy}, {x: xm - ox, y: y}, {x: xm, y: y}),
|
|
||||||
topRight: bezierCurve({x: x, y: y}, {x: x + ox,y: y}, {x: xm, y: ym - oy}, {x: xm, y: ym}),
|
|
||||||
bottomRight: bezierCurve({x: xm, y: y}, {x: xm, y: y + oy}, {x: x + ox, y: ym}, {x: x, y: ym}),
|
|
||||||
bottomLeft: bezierCurve({x: xm, y: ym}, {x: xm - ox, y: ym}, {x: x, y: y + oy}, {x: x, y:y})
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function calculateCurvePoints(bounds, borderRadius, borders) {
|
|
||||||
var x = bounds.left,
|
|
||||||
y = bounds.top,
|
|
||||||
width = bounds.width,
|
|
||||||
height = bounds.height,
|
|
||||||
|
|
||||||
tlh = borderRadius[0][0] < width / 2 ? borderRadius[0][0] : width / 2,
|
|
||||||
tlv = borderRadius[0][1] < height / 2 ? borderRadius[0][1] : height / 2,
|
|
||||||
trh = borderRadius[1][0] < width / 2 ? borderRadius[1][0] : width / 2,
|
|
||||||
trv = borderRadius[1][1] < height / 2 ? borderRadius[1][1] : height / 2,
|
|
||||||
brh = borderRadius[2][0] < width / 2 ? borderRadius[2][0] : width / 2,
|
|
||||||
brv = borderRadius[2][1] < height / 2 ? borderRadius[2][1] : height / 2,
|
|
||||||
blh = borderRadius[3][0] < width / 2 ? borderRadius[3][0] : width / 2,
|
|
||||||
blv = borderRadius[3][1] < height / 2 ? borderRadius[3][1] : height / 2;
|
|
||||||
|
|
||||||
var topWidth = width - trh,
|
|
||||||
rightHeight = height - brv,
|
|
||||||
bottomWidth = width - brh,
|
|
||||||
leftHeight = height - blv;
|
|
||||||
|
|
||||||
return {
|
|
||||||
topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5),
|
|
||||||
topLeftInner: getCurvePoints(x + borders[3].width, y + borders[0].width, Math.max(0, tlh - borders[3].width), Math.max(0, tlv - borders[0].width)).topLeft.subdivide(0.5),
|
|
||||||
topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5),
|
|
||||||
topRightInner: getCurvePoints(x + Math.min(topWidth, width + borders[3].width), y + borders[0].width, (topWidth > width + borders[3].width) ? 0 :trh - borders[3].width, trv - borders[0].width).topRight.subdivide(0.5),
|
|
||||||
bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5),
|
|
||||||
bottomRightInner: getCurvePoints(x + Math.min(bottomWidth, width - borders[3].width), y + Math.min(rightHeight, height + borders[0].width), Math.max(0, brh - borders[1].width), brv - borders[2].width).bottomRight.subdivide(0.5),
|
|
||||||
bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5),
|
|
||||||
bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - borders[3].width), blv - borders[2].width).bottomLeft.subdivide(0.5)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function bezierCurve(start, startControl, endControl, end) {
|
|
||||||
var lerp = function (a, b, t) {
|
|
||||||
return {
|
|
||||||
x: a.x + (b.x - a.x) * t,
|
|
||||||
y: a.y + (b.y - a.y) * t
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
|
||||||
start: start,
|
|
||||||
startControl: startControl,
|
|
||||||
endControl: endControl,
|
|
||||||
end: end,
|
|
||||||
subdivide: function(t) {
|
|
||||||
var ab = lerp(start, startControl, t),
|
|
||||||
bc = lerp(startControl, endControl, t),
|
|
||||||
cd = lerp(endControl, end, t),
|
|
||||||
abbc = lerp(ab, bc, t),
|
|
||||||
bccd = lerp(bc, cd, t),
|
|
||||||
dest = lerp(abbc, bccd, t);
|
|
||||||
return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)];
|
|
||||||
},
|
|
||||||
curveTo: function(borderArgs) {
|
|
||||||
borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y]);
|
|
||||||
},
|
|
||||||
curveToReversed: function(borderArgs) {
|
|
||||||
borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y]);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) {
|
|
||||||
var borderArgs = [];
|
|
||||||
|
|
||||||
if (radius1[0] > 0 || radius1[1] > 0) {
|
|
||||||
borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]);
|
|
||||||
outer1[1].curveTo(borderArgs);
|
|
||||||
} else {
|
|
||||||
borderArgs.push([ "line", borderData.c1[0], borderData.c1[1]]);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (radius2[0] > 0 || radius2[1] > 0) {
|
|
||||||
borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]);
|
|
||||||
outer2[0].curveTo(borderArgs);
|
|
||||||
borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]);
|
|
||||||
inner2[0].curveToReversed(borderArgs);
|
|
||||||
} else {
|
|
||||||
borderArgs.push(["line", borderData.c2[0], borderData.c2[1]]);
|
|
||||||
borderArgs.push(["line", borderData.c3[0], borderData.c3[1]]);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (radius1[0] > 0 || radius1[1] > 0) {
|
|
||||||
borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]);
|
|
||||||
inner1[1].curveToReversed(borderArgs);
|
|
||||||
} else {
|
|
||||||
borderArgs.push(["line", borderData.c4[0], borderData.c4[1]]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return borderArgs;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) {
|
|
||||||
if (radius1[0] > 0 || radius1[1] > 0) {
|
|
||||||
borderArgs.push(["line", corner1[0].start.x, corner1[0].start.y]);
|
|
||||||
corner1[0].curveTo(borderArgs);
|
|
||||||
corner1[1].curveTo(borderArgs);
|
|
||||||
} else {
|
|
||||||
borderArgs.push(["line", x, y]);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (radius2[0] > 0 || radius2[1] > 0) {
|
|
||||||
borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function negativeZIndex(container) {
|
|
||||||
return container.cssInt("zIndex") < 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
function positiveZIndex(container) {
|
|
||||||
return container.cssInt("zIndex") > 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
function zIndex0(container) {
|
|
||||||
return container.cssInt("zIndex") === 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
function inlineLevel(container) {
|
|
||||||
return ["inline", "inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isStackingContext(container) {
|
|
||||||
return (container instanceof StackingContext);
|
|
||||||
}
|
|
||||||
|
|
||||||
function hasText(container) {
|
|
||||||
return container.node.data.trim().length > 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
function noLetterSpacing(container) {
|
|
||||||
return (/^(normal|none|0px)$/.test(container.parent.css("letterSpacing")));
|
|
||||||
}
|
|
||||||
|
|
||||||
function getBorderRadiusData(container) {
|
|
||||||
return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function(side) {
|
|
||||||
var value = container.css('border' + side + 'Radius');
|
|
||||||
var arr = value.split(" ");
|
|
||||||
if (arr.length <= 1) {
|
|
||||||
arr[1] = arr[0];
|
|
||||||
}
|
|
||||||
return arr.map(asInt);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderableNode(node) {
|
|
||||||
return (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE);
|
|
||||||
}
|
|
||||||
|
|
||||||
function isPositionedForStacking(container) {
|
|
||||||
var position = container.css("position");
|
|
||||||
var zIndex = (["absolute", "relative", "fixed"].indexOf(position) !== -1) ? container.css("zIndex") : "auto";
|
|
||||||
return zIndex !== "auto";
|
|
||||||
}
|
|
||||||
|
|
||||||
function isPositioned(container) {
|
|
||||||
return container.css("position") !== "static";
|
|
||||||
}
|
|
||||||
|
|
||||||
function isFloating(container) {
|
|
||||||
return container.css("float") !== "none";
|
|
||||||
}
|
|
||||||
|
|
||||||
function isInlineBlock(container) {
|
|
||||||
return ["inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
function not(callback) {
|
|
||||||
var context = this;
|
|
||||||
return function() {
|
|
||||||
return !callback.apply(context, arguments);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function isElement(container) {
|
|
||||||
return container.node.nodeType === Node.ELEMENT_NODE;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isPseudoElement(container) {
|
|
||||||
return container.isPseudoElement === true;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isTextNode(container) {
|
|
||||||
return container.node.nodeType === Node.TEXT_NODE;
|
|
||||||
}
|
|
||||||
|
|
||||||
function zIndexSort(contexts) {
|
|
||||||
return function(a, b) {
|
|
||||||
return (a.cssInt("zIndex") + (contexts.indexOf(a) / contexts.length)) - (b.cssInt("zIndex") + (contexts.indexOf(b) / contexts.length));
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function hasOpacity(container) {
|
|
||||||
return container.getOpacity() < 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
function asInt(value) {
|
|
||||||
return parseInt(value, 10);
|
|
||||||
}
|
|
||||||
|
|
||||||
function getWidth(border) {
|
|
||||||
return border.width;
|
|
||||||
}
|
|
||||||
|
|
||||||
function nonIgnoredElement(nodeContainer) {
|
|
||||||
return (nodeContainer.node.nodeType !== Node.ELEMENT_NODE || ["SCRIPT", "HEAD", "TITLE", "OBJECT", "BR", "OPTION"].indexOf(nodeContainer.node.nodeName) === -1);
|
|
||||||
}
|
|
||||||
|
|
||||||
function flatten(arrays) {
|
|
||||||
return [].concat.apply([], arrays);
|
|
||||||
}
|
|
||||||
|
|
||||||
function stripQuotes(content) {
|
|
||||||
var first = content.substr(0, 1);
|
|
||||||
return (first === content.substr(content.length - 1) && first.match(/'|"/)) ? content.substr(1, content.length - 2) : content;
|
|
||||||
}
|
|
||||||
|
|
||||||
function getWords(characters) {
|
|
||||||
var words = [], i = 0, onWordBoundary = false, word;
|
|
||||||
while(characters.length) {
|
|
||||||
if (isWordBoundary(characters[i]) === onWordBoundary) {
|
|
||||||
word = characters.splice(0, i);
|
|
||||||
if (word.length) {
|
|
||||||
words.push(punycode.ucs2.encode(word));
|
|
||||||
}
|
|
||||||
onWordBoundary =! onWordBoundary;
|
|
||||||
i = 0;
|
|
||||||
} else {
|
|
||||||
i++;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (i >= characters.length) {
|
|
||||||
word = characters.splice(0, i);
|
|
||||||
if (word.length) {
|
|
||||||
words.push(punycode.ucs2.encode(word));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return words;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isWordBoundary(characterCode) {
|
|
||||||
return [
|
|
||||||
32, // <space>
|
|
||||||
13, // \r
|
|
||||||
10, // \n
|
|
||||||
9, // \t
|
|
||||||
45 // -
|
|
||||||
].indexOf(characterCode) !== -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
function hasUnicode(string) {
|
|
||||||
return (/[^\u0000-\u00ff]/).test(string);
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = NodeParser;
|
|
366
src/parsing/background.js
Normal file
366
src/parsing/background.js
Normal file
@ -0,0 +1,366 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
import type {Bounds} from '../Bounds';
|
||||||
|
import type ImageLoader from '../ImageLoader';
|
||||||
|
|
||||||
|
import Color from '../Color';
|
||||||
|
import Length from '../Length';
|
||||||
|
import Size from '../Size';
|
||||||
|
import Vector from '../Vector';
|
||||||
|
|
||||||
|
export type Background = {
|
||||||
|
backgroundImage: Array<BackgroundImage>,
|
||||||
|
backgroundColor: Color
|
||||||
|
};
|
||||||
|
|
||||||
|
export type BackgroundRepeat = $Values<typeof BACKGROUND_REPEAT>;
|
||||||
|
export type BackgroundSizeTypes = $Values<typeof BACKGROUND_SIZE>;
|
||||||
|
|
||||||
|
export type BackgroundSource = {
|
||||||
|
prefix: string,
|
||||||
|
method: string,
|
||||||
|
args: Array<string>
|
||||||
|
};
|
||||||
|
|
||||||
|
export type BackgroundImage = {
|
||||||
|
source: BackgroundSource,
|
||||||
|
position: [Length, Length],
|
||||||
|
size: [BackgroundSize, BackgroundSize],
|
||||||
|
repeat: BackgroundRepeat
|
||||||
|
};
|
||||||
|
|
||||||
|
export const BACKGROUND_REPEAT = {
|
||||||
|
REPEAT: 0,
|
||||||
|
NO_REPEAT: 1,
|
||||||
|
REPEAT_X: 2,
|
||||||
|
REPEAT_Y: 3
|
||||||
|
};
|
||||||
|
|
||||||
|
export const BACKGROUND_SIZE = {
|
||||||
|
AUTO: 0,
|
||||||
|
CONTAIN: 1,
|
||||||
|
COVER: 2,
|
||||||
|
LENGTH: 3
|
||||||
|
};
|
||||||
|
|
||||||
|
const AUTO = 'auto';
|
||||||
|
|
||||||
|
class BackgroundSize {
|
||||||
|
size: ?BackgroundSizeTypes;
|
||||||
|
value: ?Length;
|
||||||
|
|
||||||
|
constructor(size: string) {
|
||||||
|
switch (size) {
|
||||||
|
case 'contain':
|
||||||
|
this.size = BACKGROUND_SIZE.CONTAIN;
|
||||||
|
break;
|
||||||
|
case 'cover':
|
||||||
|
this.size = BACKGROUND_SIZE.COVER;
|
||||||
|
break;
|
||||||
|
case 'auto':
|
||||||
|
this.size = BACKGROUND_SIZE.AUTO;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
this.value = new Length(size);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const calculateBackgroundSize = (
|
||||||
|
backgroundImage: BackgroundImage,
|
||||||
|
image: HTMLImageElement,
|
||||||
|
bounds: Bounds
|
||||||
|
): Size => {
|
||||||
|
let width = 0;
|
||||||
|
let height = 0;
|
||||||
|
const size = backgroundImage.size;
|
||||||
|
if (size[0].size === BACKGROUND_SIZE.CONTAIN || size[0].size === BACKGROUND_SIZE.COVER) {
|
||||||
|
const targetRatio = bounds.width / bounds.height;
|
||||||
|
const currentRatio = image.width / image.height;
|
||||||
|
return targetRatio < currentRatio !== (size[0].size === BACKGROUND_SIZE.COVER)
|
||||||
|
? new Size(bounds.height * currentRatio, bounds.height)
|
||||||
|
: new Size(bounds.width, bounds.width / currentRatio);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (size[0].value) {
|
||||||
|
width = size[0].value.getAbsoluteValue(bounds.width);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (size[0].size === BACKGROUND_SIZE.AUTO && size[1].size === BACKGROUND_SIZE.AUTO) {
|
||||||
|
height = image.height;
|
||||||
|
} else if (size[1].size === BACKGROUND_SIZE.AUTO) {
|
||||||
|
height = width / image.width * image.height;
|
||||||
|
} else if (size[1].value) {
|
||||||
|
height = size[1].value.getAbsoluteValue(bounds.height);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (size[0].size === BACKGROUND_SIZE.AUTO) {
|
||||||
|
width = height / image.height * image.width;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Size(width, height);
|
||||||
|
};
|
||||||
|
|
||||||
|
const AUTO_SIZE = new BackgroundSize(AUTO);
|
||||||
|
|
||||||
|
export const calculateBackgroundPosition = (
|
||||||
|
position: [Length, Length],
|
||||||
|
size: Size,
|
||||||
|
bounds: Bounds
|
||||||
|
): Vector => {
|
||||||
|
return new Vector(
|
||||||
|
position[0].getAbsoluteValue(bounds.width - size.width),
|
||||||
|
position[1].getAbsoluteValue(bounds.height - size.height)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const calculateBackgroundRepeatPath = (
|
||||||
|
background: BackgroundImage,
|
||||||
|
position: Vector,
|
||||||
|
size: Size,
|
||||||
|
bounds: Bounds
|
||||||
|
) => {
|
||||||
|
const repeat = background.repeat;
|
||||||
|
switch (repeat) {
|
||||||
|
case BACKGROUND_REPEAT.REPEAT_X:
|
||||||
|
return [
|
||||||
|
new Vector(Math.round(bounds.left), Math.round(bounds.top + position.y)),
|
||||||
|
new Vector(
|
||||||
|
Math.round(bounds.left + bounds.width),
|
||||||
|
Math.round(bounds.top + position.y)
|
||||||
|
),
|
||||||
|
new Vector(
|
||||||
|
Math.round(bounds.left + bounds.width),
|
||||||
|
Math.round(size.height + bounds.top + position.y)
|
||||||
|
),
|
||||||
|
new Vector(
|
||||||
|
Math.round(bounds.left),
|
||||||
|
Math.round(size.height + bounds.top + position.y)
|
||||||
|
)
|
||||||
|
];
|
||||||
|
case BACKGROUND_REPEAT.REPEAT_Y:
|
||||||
|
return [
|
||||||
|
new Vector(Math.round(bounds.left + position.x), Math.round(bounds.top)),
|
||||||
|
new Vector(
|
||||||
|
Math.round(bounds.left + position.x + size.width),
|
||||||
|
Math.round(bounds.top)
|
||||||
|
),
|
||||||
|
new Vector(
|
||||||
|
Math.round(bounds.left + position.x + size.width),
|
||||||
|
Math.round(bounds.height + bounds.top)
|
||||||
|
),
|
||||||
|
new Vector(
|
||||||
|
Math.round(bounds.left + position.x),
|
||||||
|
Math.round(bounds.height + bounds.top)
|
||||||
|
)
|
||||||
|
];
|
||||||
|
case BACKGROUND_REPEAT.NO_REPEAT:
|
||||||
|
return [
|
||||||
|
new Vector(
|
||||||
|
Math.round(bounds.left + position.x),
|
||||||
|
Math.round(bounds.top + position.y)
|
||||||
|
),
|
||||||
|
new Vector(
|
||||||
|
Math.round(bounds.left + position.x + size.width),
|
||||||
|
Math.round(bounds.top + position.y)
|
||||||
|
),
|
||||||
|
new Vector(
|
||||||
|
Math.round(bounds.left + position.x + size.width),
|
||||||
|
Math.round(bounds.top + position.y + size.height)
|
||||||
|
),
|
||||||
|
new Vector(
|
||||||
|
Math.round(bounds.left + position.x),
|
||||||
|
Math.round(bounds.top + position.y + size.height)
|
||||||
|
)
|
||||||
|
];
|
||||||
|
default:
|
||||||
|
return [
|
||||||
|
new Vector(Math.round(bounds.left), Math.round(bounds.top)),
|
||||||
|
new Vector(Math.round(bounds.left + bounds.width), Math.round(bounds.top)),
|
||||||
|
new Vector(
|
||||||
|
Math.round(bounds.left + bounds.width),
|
||||||
|
Math.round(bounds.height + bounds.top)
|
||||||
|
),
|
||||||
|
new Vector(Math.round(bounds.left), Math.round(bounds.height + bounds.top))
|
||||||
|
];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const parseBackground = (
|
||||||
|
style: CSSStyleDeclaration,
|
||||||
|
imageLoader: ImageLoader
|
||||||
|
): Background => {
|
||||||
|
return {
|
||||||
|
backgroundImage: parseBackgroundImages(style, imageLoader),
|
||||||
|
backgroundColor: new Color(style.backgroundColor)
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseBackgroundRepeat = (backgroundRepeat: string): BackgroundRepeat => {
|
||||||
|
switch (backgroundRepeat) {
|
||||||
|
case 'no-repeat':
|
||||||
|
return BACKGROUND_REPEAT.NO_REPEAT;
|
||||||
|
case 'repeat-x':
|
||||||
|
case 'repeat no-repeat':
|
||||||
|
return BACKGROUND_REPEAT.REPEAT_X;
|
||||||
|
case 'repeat-y':
|
||||||
|
case 'no-repeat repeat':
|
||||||
|
return BACKGROUND_REPEAT.REPEAT_Y;
|
||||||
|
case 'repeat':
|
||||||
|
return BACKGROUND_REPEAT.REPEAT;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (__DEV__) {
|
||||||
|
console.error(`Invalid background-repeat value "${backgroundRepeat}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return BACKGROUND_REPEAT.REPEAT;
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseBackgroundImages = (
|
||||||
|
style: CSSStyleDeclaration,
|
||||||
|
imageLoader: ImageLoader
|
||||||
|
): Array<BackgroundImage> => {
|
||||||
|
const sources: Array<BackgroundSource> = parseBackgroundImage(
|
||||||
|
style.backgroundImage,
|
||||||
|
imageLoader
|
||||||
|
);
|
||||||
|
const positions = style.backgroundPosition.split(',');
|
||||||
|
const repeats = style.backgroundRepeat.split(',');
|
||||||
|
const sizes = style.backgroundSize.split(',');
|
||||||
|
|
||||||
|
return sources.map((source, index) => {
|
||||||
|
const size = (sizes[index] || AUTO).trim().split(' ').map(parseBackgroundSize);
|
||||||
|
const position = (positions[index] || AUTO).trim().split(' ').map(parseBackgoundPosition);
|
||||||
|
|
||||||
|
return {
|
||||||
|
source,
|
||||||
|
repeat: parseBackgroundRepeat(repeats[index]),
|
||||||
|
size: size.length < 2 ? [size[0], AUTO_SIZE] : [size[0], size[1]],
|
||||||
|
position: position.length < 2 ? [position[0], position[0]] : [position[0], position[1]]
|
||||||
|
};
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseBackgroundSize = (size: string): BackgroundSize =>
|
||||||
|
size === 'auto' ? AUTO_SIZE : new BackgroundSize(size);
|
||||||
|
|
||||||
|
const parseBackgoundPosition = (position: string): Length => {
|
||||||
|
switch (position) {
|
||||||
|
case 'bottom':
|
||||||
|
case 'right':
|
||||||
|
return new Length('100%');
|
||||||
|
case 'left':
|
||||||
|
case 'top':
|
||||||
|
return new Length('0%');
|
||||||
|
case 'auto':
|
||||||
|
return new Length('0');
|
||||||
|
}
|
||||||
|
return new Length(position);
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseBackgroundImage = (image: string, imageLoader: ImageLoader): Array<BackgroundSource> => {
|
||||||
|
const whitespace = /^\s$/;
|
||||||
|
const results = [];
|
||||||
|
|
||||||
|
let args = [];
|
||||||
|
let method = '';
|
||||||
|
let quote = null;
|
||||||
|
let definition = '';
|
||||||
|
let mode = 0;
|
||||||
|
let numParen = 0;
|
||||||
|
|
||||||
|
const appendResult = () => {
|
||||||
|
let prefix = '';
|
||||||
|
if (method) {
|
||||||
|
if (definition.substr(0, 1) === '"') {
|
||||||
|
definition = definition.substr(1, definition.length - 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (definition) {
|
||||||
|
args.push(definition);
|
||||||
|
}
|
||||||
|
|
||||||
|
const prefix_i = method.indexOf('-', 1) + 1;
|
||||||
|
if (method.substr(0, 1) === '-' && prefix_i > 0) {
|
||||||
|
prefix = method.substr(0, prefix_i).toLowerCase();
|
||||||
|
method = method.substr(prefix_i);
|
||||||
|
}
|
||||||
|
method = method.toLowerCase();
|
||||||
|
if (method === 'url') {
|
||||||
|
const key = imageLoader.loadImage(args[0]);
|
||||||
|
args = key ? [key] : [];
|
||||||
|
}
|
||||||
|
results.push({
|
||||||
|
prefix,
|
||||||
|
method,
|
||||||
|
args
|
||||||
|
});
|
||||||
|
}
|
||||||
|
args = [];
|
||||||
|
method = definition = '';
|
||||||
|
};
|
||||||
|
|
||||||
|
image.split('').forEach(c => {
|
||||||
|
if (mode === 0 && whitespace.test(c)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
switch (c) {
|
||||||
|
case '"':
|
||||||
|
if (!quote) {
|
||||||
|
quote = c;
|
||||||
|
} else if (quote === c) {
|
||||||
|
quote = null;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case '(':
|
||||||
|
if (quote) {
|
||||||
|
break;
|
||||||
|
} else if (mode === 0) {
|
||||||
|
mode = 1;
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
numParen++;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case ')':
|
||||||
|
if (quote) {
|
||||||
|
break;
|
||||||
|
} else if (mode === 1) {
|
||||||
|
if (numParen === 0) {
|
||||||
|
mode = 0;
|
||||||
|
appendResult();
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
numParen--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ',':
|
||||||
|
if (quote) {
|
||||||
|
break;
|
||||||
|
} else if (mode === 0) {
|
||||||
|
appendResult();
|
||||||
|
return;
|
||||||
|
} else if (mode === 1) {
|
||||||
|
if (numParen === 0 && !method.match(/^url$/i)) {
|
||||||
|
args.push(definition);
|
||||||
|
definition = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mode === 0) {
|
||||||
|
method += c;
|
||||||
|
} else {
|
||||||
|
definition += c;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
appendResult();
|
||||||
|
return results;
|
||||||
|
};
|
49
src/parsing/border.js
Normal file
49
src/parsing/border.js
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
import Color from '../Color';
|
||||||
|
|
||||||
|
export const BORDER_STYLE = {
|
||||||
|
NONE: 0,
|
||||||
|
SOLID: 1
|
||||||
|
};
|
||||||
|
|
||||||
|
export type BorderStyle = $Values<typeof BORDER_STYLE>;
|
||||||
|
|
||||||
|
export type Border = {
|
||||||
|
borderColor: Color,
|
||||||
|
borderStyle: BorderStyle,
|
||||||
|
borderWidth: number
|
||||||
|
};
|
||||||
|
|
||||||
|
export const BORDER_SIDES = {
|
||||||
|
TOP: 0,
|
||||||
|
RIGHT: 1,
|
||||||
|
BOTTOM: 2,
|
||||||
|
LEFT: 3
|
||||||
|
};
|
||||||
|
|
||||||
|
export type BorderSide = $Values<typeof BORDER_SIDES>;
|
||||||
|
|
||||||
|
const SIDES = Object.keys(BORDER_SIDES).map(s => s.toLowerCase());
|
||||||
|
|
||||||
|
const parseBorderStyle = (style: string): BorderStyle => {
|
||||||
|
switch (style) {
|
||||||
|
case 'none':
|
||||||
|
return BORDER_STYLE.NONE;
|
||||||
|
}
|
||||||
|
return BORDER_STYLE.SOLID;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const parseBorder = (style: CSSStyleDeclaration): Array<Border> => {
|
||||||
|
return SIDES.map(side => {
|
||||||
|
const borderColor = new Color(style.getPropertyValue(`border-${side}-color`));
|
||||||
|
const borderStyle = parseBorderStyle(style.getPropertyValue(`border-${side}-style`));
|
||||||
|
const borderWidth = parseInt(style.getPropertyValue(`border-${side}-width`), 10);
|
||||||
|
return {
|
||||||
|
borderColor,
|
||||||
|
borderStyle,
|
||||||
|
borderWidth: isNaN(borderWidth) ? 0 : borderWidth
|
||||||
|
};
|
||||||
|
});
|
||||||
|
};
|
15
src/parsing/borderRadius.js
Normal file
15
src/parsing/borderRadius.js
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
import Length from '../Length';
|
||||||
|
|
||||||
|
const SIDES = ['top-left', 'top-right', 'bottom-right', 'bottom-left'];
|
||||||
|
|
||||||
|
export type BorderRadius = Array<Length>;
|
||||||
|
|
||||||
|
export const parseBorderRadius = (style: CSSStyleDeclaration): Array<BorderRadius> => {
|
||||||
|
return SIDES.map(side => {
|
||||||
|
const value = style.getPropertyValue(`border-${side}-radius`);
|
||||||
|
const [horizontal, vertical] = value.split(' ').map(Length.create);
|
||||||
|
return typeof vertical === 'undefined' ? [horizontal, horizontal] : [horizontal, vertical];
|
||||||
|
});
|
||||||
|
};
|
111
src/parsing/display.js
Normal file
111
src/parsing/display.js
Normal file
@ -0,0 +1,111 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
export const DISPLAY = {
|
||||||
|
NONE: 1 << 0,
|
||||||
|
BLOCK: 1 << 1,
|
||||||
|
INLINE: 1 << 2,
|
||||||
|
RUN_IN: 1 << 3,
|
||||||
|
FLOW: 1 << 4,
|
||||||
|
FLOW_ROOT: 1 << 5,
|
||||||
|
TABLE: 1 << 6,
|
||||||
|
FLEX: 1 << 7,
|
||||||
|
GRID: 1 << 8,
|
||||||
|
RUBY: 1 << 9,
|
||||||
|
SUBGRID: 1 << 10,
|
||||||
|
LIST_ITEM: 1 << 11,
|
||||||
|
TABLE_ROW_GROUP: 1 << 12,
|
||||||
|
TABLE_HEADER_GROUP: 1 << 13,
|
||||||
|
TABLE_FOOTER_GROUP: 1 << 14,
|
||||||
|
TABLE_ROW: 1 << 15,
|
||||||
|
TABLE_CELL: 1 << 16,
|
||||||
|
TABLE_COLUMN_GROUP: 1 << 17,
|
||||||
|
TABLE_COLUMN: 1 << 18,
|
||||||
|
TABLE_CAPTION: 1 << 19,
|
||||||
|
RUBY_BASE: 1 << 20,
|
||||||
|
RUBY_TEXT: 1 << 21,
|
||||||
|
RUBY_BASE_CONTAINER: 1 << 22,
|
||||||
|
RUBY_TEXT_CONTAINER: 1 << 23,
|
||||||
|
CONTENTS: 1 << 24,
|
||||||
|
INLINE_BLOCK: 1 << 25,
|
||||||
|
INLINE_LIST_ITEM: 1 << 26,
|
||||||
|
INLINE_TABLE: 1 << 27,
|
||||||
|
INLINE_FLEX: 1 << 28,
|
||||||
|
INLINE_GRID: 1 << 29
|
||||||
|
};
|
||||||
|
|
||||||
|
export type Display = $Values<typeof DISPLAY>;
|
||||||
|
export type DisplayBit = number;
|
||||||
|
|
||||||
|
const parseDisplayValue = (display: string): Display => {
|
||||||
|
switch (display) {
|
||||||
|
case 'block':
|
||||||
|
return DISPLAY.BLOCK;
|
||||||
|
case 'inline':
|
||||||
|
return DISPLAY.INLINE;
|
||||||
|
case 'run-in':
|
||||||
|
return DISPLAY.RUN_IN;
|
||||||
|
case 'flow':
|
||||||
|
return DISPLAY.FLOW;
|
||||||
|
case 'flow-root':
|
||||||
|
return DISPLAY.FLOW_ROOT;
|
||||||
|
case 'table':
|
||||||
|
return DISPLAY.TABLE;
|
||||||
|
case 'flex':
|
||||||
|
return DISPLAY.FLEX;
|
||||||
|
case 'grid':
|
||||||
|
return DISPLAY.GRID;
|
||||||
|
case 'ruby':
|
||||||
|
return DISPLAY.RUBY;
|
||||||
|
case 'subgrid':
|
||||||
|
return DISPLAY.SUBGRID;
|
||||||
|
case 'list-item':
|
||||||
|
return DISPLAY.LIST_ITEM;
|
||||||
|
case 'table-row-group':
|
||||||
|
return DISPLAY.TABLE_ROW_GROUP;
|
||||||
|
case 'table-header-group':
|
||||||
|
return DISPLAY.TABLE_HEADER_GROUP;
|
||||||
|
case 'table-footer-group':
|
||||||
|
return DISPLAY.TABLE_FOOTER_GROUP;
|
||||||
|
case 'table-row':
|
||||||
|
return DISPLAY.TABLE_ROW;
|
||||||
|
case 'table-cell':
|
||||||
|
return DISPLAY.TABLE_CELL;
|
||||||
|
case 'table-column-group':
|
||||||
|
return DISPLAY.TABLE_COLUMN_GROUP;
|
||||||
|
case 'table-column':
|
||||||
|
return DISPLAY.TABLE_COLUMN;
|
||||||
|
case 'table-caption':
|
||||||
|
return DISPLAY.TABLE_CAPTION;
|
||||||
|
case 'ruby-base':
|
||||||
|
return DISPLAY.RUBY_BASE;
|
||||||
|
case 'ruby-text':
|
||||||
|
return DISPLAY.RUBY_TEXT;
|
||||||
|
case 'ruby-base-container':
|
||||||
|
return DISPLAY.RUBY_BASE_CONTAINER;
|
||||||
|
case 'ruby-text-container':
|
||||||
|
return DISPLAY.RUBY_TEXT_CONTAINER;
|
||||||
|
case 'contents':
|
||||||
|
return DISPLAY.CONTENTS;
|
||||||
|
case 'inline-block':
|
||||||
|
return DISPLAY.INLINE_BLOCK;
|
||||||
|
case 'inline-list-item':
|
||||||
|
return DISPLAY.INLINE_LIST_ITEM;
|
||||||
|
case 'inline-table':
|
||||||
|
return DISPLAY.INLINE_TABLE;
|
||||||
|
case 'inline-flex':
|
||||||
|
return DISPLAY.INLINE_FLEX;
|
||||||
|
case 'inline-grid':
|
||||||
|
return DISPLAY.INLINE_GRID;
|
||||||
|
}
|
||||||
|
|
||||||
|
return DISPLAY.NONE;
|
||||||
|
};
|
||||||
|
|
||||||
|
const setDisplayBit = (bit: DisplayBit, display: string): DisplayBit => {
|
||||||
|
return bit | parseDisplayValue(display);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const parseDisplay = (display: string): Display => {
|
||||||
|
return display.split(' ').reduce(setDisplayBit, 0);
|
||||||
|
};
|
26
src/parsing/float.js
Normal file
26
src/parsing/float.js
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
export const FLOAT = {
|
||||||
|
NONE: 0,
|
||||||
|
LEFT: 1,
|
||||||
|
RIGHT: 2,
|
||||||
|
INLINE_START: 3,
|
||||||
|
INLINE_END: 4
|
||||||
|
};
|
||||||
|
|
||||||
|
export type Float = $Values<typeof FLOAT>;
|
||||||
|
|
||||||
|
export const parseCSSFloat = (float: string): Float => {
|
||||||
|
switch (float) {
|
||||||
|
case 'left':
|
||||||
|
return FLOAT.LEFT;
|
||||||
|
case 'right':
|
||||||
|
return FLOAT.RIGHT;
|
||||||
|
case 'inline-start':
|
||||||
|
return FLOAT.INLINE_START;
|
||||||
|
case 'inline-end':
|
||||||
|
return FLOAT.INLINE_END;
|
||||||
|
}
|
||||||
|
return FLOAT.NONE;
|
||||||
|
};
|
38
src/parsing/font.js
Normal file
38
src/parsing/font.js
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
export type Font = {
|
||||||
|
fontFamily: string,
|
||||||
|
fontSize: string,
|
||||||
|
fontStyle: string,
|
||||||
|
fontVariant: string,
|
||||||
|
fontWeight: number
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseFontWeight = (weight: string): number => {
|
||||||
|
switch (weight) {
|
||||||
|
case 'normal':
|
||||||
|
return 400;
|
||||||
|
case 'bold':
|
||||||
|
return 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
const value = parseInt(weight, 10);
|
||||||
|
return isNaN(value) ? 400 : value;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const parseFont = (style: CSSStyleDeclaration): Font => {
|
||||||
|
const fontFamily = style.fontFamily;
|
||||||
|
const fontSize = style.fontSize;
|
||||||
|
const fontStyle = style.fontStyle;
|
||||||
|
const fontVariant = style.fontVariant;
|
||||||
|
const fontWeight = parseFontWeight(style.fontWeight);
|
||||||
|
|
||||||
|
return {
|
||||||
|
fontFamily,
|
||||||
|
fontSize,
|
||||||
|
fontStyle,
|
||||||
|
fontVariant,
|
||||||
|
fontWeight
|
||||||
|
};
|
||||||
|
};
|
10
src/parsing/letterSpacing.js
Normal file
10
src/parsing/letterSpacing.js
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
export const parseLetterSpacing = (letterSpacing: string): number => {
|
||||||
|
if (letterSpacing === 'normal') {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const value = parseInt(letterSpacing, 10);
|
||||||
|
return isNaN(value) ? 0 : value;
|
||||||
|
};
|
11
src/parsing/padding.js
Normal file
11
src/parsing/padding.js
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
import Length from '../Length';
|
||||||
|
|
||||||
|
const SIDES = ['top', 'right', 'bottom', 'left'];
|
||||||
|
|
||||||
|
export type Padding = Array<Length>;
|
||||||
|
|
||||||
|
export const parsePadding = (style: CSSStyleDeclaration): Padding => {
|
||||||
|
return SIDES.map(side => new Length(style.getPropertyValue(`padding-${side}`)));
|
||||||
|
};
|
27
src/parsing/position.js
Normal file
27
src/parsing/position.js
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
export const POSITION = {
|
||||||
|
STATIC: 0,
|
||||||
|
RELATIVE: 1,
|
||||||
|
ABSOLUTE: 2,
|
||||||
|
FIXED: 3,
|
||||||
|
STICKY: 4
|
||||||
|
};
|
||||||
|
|
||||||
|
export type Position = $Values<typeof POSITION>;
|
||||||
|
|
||||||
|
export const parsePosition = (position: string): Position => {
|
||||||
|
switch (position) {
|
||||||
|
case 'relative':
|
||||||
|
return POSITION.RELATIVE;
|
||||||
|
case 'absolute':
|
||||||
|
return POSITION.ABSOLUTE;
|
||||||
|
case 'fixed':
|
||||||
|
return POSITION.FIXED;
|
||||||
|
case 'sticky':
|
||||||
|
return POSITION.STICKY;
|
||||||
|
}
|
||||||
|
|
||||||
|
return POSITION.STATIC;
|
||||||
|
};
|
88
src/parsing/textDecoration.js
Normal file
88
src/parsing/textDecoration.js
Normal file
@ -0,0 +1,88 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
import Color from '../Color';
|
||||||
|
|
||||||
|
export const TEXT_DECORATION_STYLE = {
|
||||||
|
SOLID: 0,
|
||||||
|
DOUBLE: 1,
|
||||||
|
DOTTED: 2,
|
||||||
|
DASHED: 3,
|
||||||
|
WAVY: 4
|
||||||
|
};
|
||||||
|
|
||||||
|
export const TEXT_DECORATION = {
|
||||||
|
NONE: null
|
||||||
|
};
|
||||||
|
|
||||||
|
export const TEXT_DECORATION_LINE = {
|
||||||
|
UNDERLINE: 1,
|
||||||
|
OVERLINE: 2,
|
||||||
|
LINE_THROUGH: 3,
|
||||||
|
BLINK: 4
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TextDecorationStyle = $Values<typeof TEXT_DECORATION_STYLE>;
|
||||||
|
export type TextDecorationLine = $Values<typeof TEXT_DECORATION_LINE>;
|
||||||
|
type TextDecorationLineType = Array<TextDecorationLine> | null;
|
||||||
|
export type TextDecoration =
|
||||||
|
| {
|
||||||
|
textDecorationLine: Array<TextDecorationLine>,
|
||||||
|
textDecorationStyle: TextDecorationStyle,
|
||||||
|
textDecorationColor: Color | null
|
||||||
|
}
|
||||||
|
| $Values<typeof TEXT_DECORATION>;
|
||||||
|
|
||||||
|
const parseLine = (line: string): TextDecorationLine => {
|
||||||
|
switch (line) {
|
||||||
|
case 'underline':
|
||||||
|
return TEXT_DECORATION_LINE.UNDERLINE;
|
||||||
|
case 'overline':
|
||||||
|
return TEXT_DECORATION_LINE.OVERLINE;
|
||||||
|
case 'line-through':
|
||||||
|
return TEXT_DECORATION_LINE.LINE_THROUGH;
|
||||||
|
}
|
||||||
|
return TEXT_DECORATION_LINE.BLINK;
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseTextDecorationLine = (line: string): TextDecorationLineType => {
|
||||||
|
if (line === 'none') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return line.split(' ').map(parseLine);
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseTextDecorationStyle = (style: string): TextDecorationStyle => {
|
||||||
|
switch (style) {
|
||||||
|
case 'double':
|
||||||
|
return TEXT_DECORATION_STYLE.DOUBLE;
|
||||||
|
case 'dotted':
|
||||||
|
return TEXT_DECORATION_STYLE.DOTTED;
|
||||||
|
case 'dashed':
|
||||||
|
return TEXT_DECORATION_STYLE.DASHED;
|
||||||
|
case 'wavy':
|
||||||
|
return TEXT_DECORATION_STYLE.WAVY;
|
||||||
|
}
|
||||||
|
return TEXT_DECORATION_STYLE.SOLID;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const parseTextDecoration = (style: CSSStyleDeclaration): TextDecoration => {
|
||||||
|
const textDecorationLine = parseTextDecorationLine(
|
||||||
|
style.textDecorationLine ? style.textDecorationLine : style.textDecoration
|
||||||
|
);
|
||||||
|
if (textDecorationLine === null) {
|
||||||
|
return TEXT_DECORATION.NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
const textDecorationColor = style.textDecorationColor
|
||||||
|
? new Color(style.textDecorationColor)
|
||||||
|
: null;
|
||||||
|
const textDecorationStyle = parseTextDecorationStyle(style.textDecorationStyle);
|
||||||
|
|
||||||
|
return {
|
||||||
|
textDecorationLine,
|
||||||
|
textDecorationColor,
|
||||||
|
textDecorationStyle
|
||||||
|
};
|
||||||
|
};
|
24
src/parsing/textTransform.js
Normal file
24
src/parsing/textTransform.js
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
export const TEXT_TRANSFORM = {
|
||||||
|
NONE: 0,
|
||||||
|
LOWERCASE: 1,
|
||||||
|
UPPERCASE: 2,
|
||||||
|
CAPITALIZE: 3
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TextTransform = $Values<typeof TEXT_TRANSFORM>;
|
||||||
|
|
||||||
|
export const parseTextTransform = (textTransform: string): TextTransform => {
|
||||||
|
switch (textTransform) {
|
||||||
|
case 'uppercase':
|
||||||
|
return TEXT_TRANSFORM.UPPERCASE;
|
||||||
|
case 'lowercase':
|
||||||
|
return TEXT_TRANSFORM.LOWERCASE;
|
||||||
|
case 'capitalize':
|
||||||
|
return TEXT_TRANSFORM.CAPITALIZE;
|
||||||
|
}
|
||||||
|
|
||||||
|
return TEXT_TRANSFORM.NONE;
|
||||||
|
};
|
49
src/parsing/transform.js
Normal file
49
src/parsing/transform.js
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
import Length from '../Length';
|
||||||
|
|
||||||
|
const toFloat = (s: string): number => parseFloat(s.trim());
|
||||||
|
|
||||||
|
export type Matrix = [number, number, number, number, number, number];
|
||||||
|
export type TransformOrigin = [Length, Length];
|
||||||
|
export type Transform = {
|
||||||
|
transform: Matrix,
|
||||||
|
transformOrigin: TransformOrigin
|
||||||
|
} | null;
|
||||||
|
|
||||||
|
const MATRIX = /(matrix|matrix3d)\((.+)\)/;
|
||||||
|
|
||||||
|
export const parseTransform = (style: CSSStyleDeclaration): Transform => {
|
||||||
|
// TODO get prefixed values
|
||||||
|
const transform = parseTransformMatrix(style.transform);
|
||||||
|
if (transform === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
transform,
|
||||||
|
transformOrigin: parseTransformOrigin(style.transformOrigin)
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseTransformOrigin = (origin: string): TransformOrigin => {
|
||||||
|
const values = origin.split(' ').map(Length.create);
|
||||||
|
return [values[0], values[1]];
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseTransformMatrix = (transform: string): Matrix | null => {
|
||||||
|
if (transform === 'none') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const match = transform.match(MATRIX);
|
||||||
|
if (match) {
|
||||||
|
if (match[1] === 'matrix') {
|
||||||
|
const matrix = match[2].split(',').map(toFloat);
|
||||||
|
return [matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]];
|
||||||
|
} else {
|
||||||
|
const matrix3d = match[2].split(',').map(toFloat);
|
||||||
|
return [matrix3d[0], matrix3d[1], matrix3d[4], matrix3d[5], matrix3d[12], matrix3d[13]];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
15
src/parsing/zIndex.js
Normal file
15
src/parsing/zIndex.js
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
/* @flow */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
export type zIndex = {
|
||||||
|
auto: boolean,
|
||||||
|
order: number
|
||||||
|
};
|
||||||
|
|
||||||
|
export const parseZIndex = (zIndex: string): zIndex => {
|
||||||
|
const auto = zIndex === 'auto';
|
||||||
|
return {
|
||||||
|
auto,
|
||||||
|
order: auto ? 0 : parseInt(zIndex, 10)
|
||||||
|
};
|
||||||
|
};
|
95
src/proxy.js
95
src/proxy.js
@ -1,95 +0,0 @@
|
|||||||
var XHR = require('./xhr');
|
|
||||||
var utils = require('./utils');
|
|
||||||
var log = require('./log');
|
|
||||||
var createWindowClone = require('./clone');
|
|
||||||
var decode64 = utils.decode64;
|
|
||||||
|
|
||||||
function Proxy(src, proxyUrl, document) {
|
|
||||||
var supportsCORS = ('withCredentials' in new XMLHttpRequest());
|
|
||||||
if (!proxyUrl) {
|
|
||||||
return Promise.reject("No proxy configured");
|
|
||||||
}
|
|
||||||
var callback = createCallback(supportsCORS);
|
|
||||||
var url = createProxyUrl(proxyUrl, src, callback);
|
|
||||||
|
|
||||||
return supportsCORS ? XHR(url) : (jsonp(document, url, callback).then(function(response) {
|
|
||||||
return decode64(response.content);
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
var proxyCount = 0;
|
|
||||||
|
|
||||||
function ProxyURL(src, proxyUrl, document) {
|
|
||||||
var supportsCORSImage = ('crossOrigin' in new Image());
|
|
||||||
var callback = createCallback(supportsCORSImage);
|
|
||||||
var url = createProxyUrl(proxyUrl, src, callback);
|
|
||||||
return (supportsCORSImage ? Promise.resolve(url) : jsonp(document, url, callback).then(function(response) {
|
|
||||||
return "data:" + response.type + ";base64," + response.content;
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
function jsonp(document, url, callback) {
|
|
||||||
return new Promise(function(resolve, reject) {
|
|
||||||
var s = document.createElement("script");
|
|
||||||
var cleanup = function() {
|
|
||||||
delete window.html2canvas.proxy[callback];
|
|
||||||
document.body.removeChild(s);
|
|
||||||
};
|
|
||||||
window.html2canvas.proxy[callback] = function(response) {
|
|
||||||
cleanup();
|
|
||||||
resolve(response);
|
|
||||||
};
|
|
||||||
s.src = url;
|
|
||||||
s.onerror = function(e) {
|
|
||||||
cleanup();
|
|
||||||
reject(e);
|
|
||||||
};
|
|
||||||
document.body.appendChild(s);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function createCallback(useCORS) {
|
|
||||||
return !useCORS ? "html2canvas_" + Date.now() + "_" + (++proxyCount) + "_" + Math.round(Math.random() * 100000) : "";
|
|
||||||
}
|
|
||||||
|
|
||||||
function createProxyUrl(proxyUrl, src, callback) {
|
|
||||||
return proxyUrl + "?url=" + encodeURIComponent(src) + (callback.length ? "&callback=html2canvas.proxy." + callback : "");
|
|
||||||
}
|
|
||||||
|
|
||||||
function documentFromHTML(src) {
|
|
||||||
return function(html) {
|
|
||||||
var parser = new DOMParser(), doc;
|
|
||||||
try {
|
|
||||||
doc = parser.parseFromString(html, "text/html");
|
|
||||||
} catch(e) {
|
|
||||||
log("DOMParser not supported, falling back to createHTMLDocument");
|
|
||||||
doc = document.implementation.createHTMLDocument("");
|
|
||||||
try {
|
|
||||||
doc.open();
|
|
||||||
doc.write(html);
|
|
||||||
doc.close();
|
|
||||||
} catch(ee) {
|
|
||||||
log("createHTMLDocument write not supported, falling back to document.body.innerHTML");
|
|
||||||
doc.body.innerHTML = html; // ie9 doesnt support writing to documentElement
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var b = doc.querySelector("base");
|
|
||||||
if (!b || !b.href.host) {
|
|
||||||
var base = doc.createElement("base");
|
|
||||||
base.href = src;
|
|
||||||
doc.head.insertBefore(base, doc.head.firstChild);
|
|
||||||
}
|
|
||||||
|
|
||||||
return doc;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadUrlDocument(src, proxy, document, width, height, options) {
|
|
||||||
return new Proxy(src, proxy, window.document).then(documentFromHTML(src)).then(function(doc) {
|
|
||||||
return createWindowClone(doc, document, width, height, options, 0, 0);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.Proxy = Proxy;
|
|
||||||
exports.ProxyURL = ProxyURL;
|
|
||||||
exports.loadUrlDocument = loadUrlDocument;
|
|
@ -1,21 +0,0 @@
|
|||||||
var ProxyURL = require('./proxy').ProxyURL;
|
|
||||||
|
|
||||||
function ProxyImageContainer(src, proxy) {
|
|
||||||
var link = document.createElement("a");
|
|
||||||
link.href = src;
|
|
||||||
src = link.href;
|
|
||||||
this.src = src;
|
|
||||||
this.image = new Image();
|
|
||||||
var self = this;
|
|
||||||
this.promise = new Promise(function(resolve, reject) {
|
|
||||||
self.image.crossOrigin = "Anonymous";
|
|
||||||
self.image.onload = resolve;
|
|
||||||
self.image.onerror = reject;
|
|
||||||
|
|
||||||
new ProxyURL(src, proxy, document).then(function(url) {
|
|
||||||
self.image.src = url;
|
|
||||||
})['catch'](reject);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = ProxyImageContainer;
|
|
@ -1,38 +0,0 @@
|
|||||||
var NodeContainer = require('./nodecontainer');
|
|
||||||
|
|
||||||
function PseudoElementContainer(node, parent, type) {
|
|
||||||
NodeContainer.call(this, node, parent);
|
|
||||||
this.isPseudoElement = true;
|
|
||||||
this.before = type === ":before";
|
|
||||||
}
|
|
||||||
|
|
||||||
PseudoElementContainer.prototype.cloneTo = function(stack) {
|
|
||||||
PseudoElementContainer.prototype.cloneTo.call(this, stack);
|
|
||||||
stack.isPseudoElement = true;
|
|
||||||
stack.before = this.before;
|
|
||||||
};
|
|
||||||
|
|
||||||
PseudoElementContainer.prototype = Object.create(NodeContainer.prototype);
|
|
||||||
|
|
||||||
PseudoElementContainer.prototype.appendToDOM = function() {
|
|
||||||
if (this.before) {
|
|
||||||
this.parent.node.insertBefore(this.node, this.parent.node.firstChild);
|
|
||||||
} else {
|
|
||||||
this.parent.node.appendChild(this.node);
|
|
||||||
}
|
|
||||||
this.parent.node.className += " " + this.getHideClass();
|
|
||||||
};
|
|
||||||
|
|
||||||
PseudoElementContainer.prototype.cleanDOM = function() {
|
|
||||||
this.node.parentNode.removeChild(this.node);
|
|
||||||
this.parent.node.className = this.parent.node.className.replace(this.getHideClass(), "");
|
|
||||||
};
|
|
||||||
|
|
||||||
PseudoElementContainer.prototype.getHideClass = function() {
|
|
||||||
return this["PSEUDO_HIDE_ELEMENT_CLASS_" + (this.before ? "BEFORE" : "AFTER")];
|
|
||||||
};
|
|
||||||
|
|
||||||
PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before";
|
|
||||||
PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after";
|
|
||||||
|
|
||||||
module.exports = PseudoElementContainer;
|
|
108
src/renderer.js
108
src/renderer.js
@ -1,108 +0,0 @@
|
|||||||
var log = require('./log');
|
|
||||||
|
|
||||||
function Renderer(width, height, images, options, document) {
|
|
||||||
this.width = width;
|
|
||||||
this.height = height;
|
|
||||||
this.images = images;
|
|
||||||
this.options = options;
|
|
||||||
this.document = document;
|
|
||||||
}
|
|
||||||
|
|
||||||
Renderer.prototype.renderImage = function(container, bounds, borderData, imageContainer) {
|
|
||||||
var paddingLeft = container.cssInt('paddingLeft'),
|
|
||||||
paddingTop = container.cssInt('paddingTop'),
|
|
||||||
paddingRight = container.cssInt('paddingRight'),
|
|
||||||
paddingBottom = container.cssInt('paddingBottom'),
|
|
||||||
borders = borderData.borders;
|
|
||||||
|
|
||||||
var width = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight);
|
|
||||||
var height = bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom);
|
|
||||||
this.drawImage(
|
|
||||||
imageContainer,
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
imageContainer.image.width || width,
|
|
||||||
imageContainer.image.height || height,
|
|
||||||
bounds.left + paddingLeft + borders[3].width,
|
|
||||||
bounds.top + paddingTop + borders[0].width,
|
|
||||||
width,
|
|
||||||
height
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
Renderer.prototype.renderBackground = function(container, bounds, borderData) {
|
|
||||||
if (bounds.height > 0 && bounds.width > 0) {
|
|
||||||
this.renderBackgroundColor(container, bounds);
|
|
||||||
this.renderBackgroundImage(container, bounds, borderData);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Renderer.prototype.renderBackgroundColor = function(container, bounds) {
|
|
||||||
var color = container.color("backgroundColor");
|
|
||||||
if (!color.isTransparent()) {
|
|
||||||
this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, color);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Renderer.prototype.renderBorders = function(borders) {
|
|
||||||
borders.forEach(this.renderBorder, this);
|
|
||||||
};
|
|
||||||
|
|
||||||
Renderer.prototype.renderBorder = function(data) {
|
|
||||||
if (!data.color.isTransparent() && data.args !== null) {
|
|
||||||
this.drawShape(data.args, data.color);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Renderer.prototype.renderBackgroundImage = function(container, bounds, borderData) {
|
|
||||||
var backgroundImages = container.parseBackgroundImages();
|
|
||||||
backgroundImages.reverse().forEach(function(backgroundImage, index, arr) {
|
|
||||||
switch(backgroundImage.method) {
|
|
||||||
case "url":
|
|
||||||
var image = this.images.get(backgroundImage.args[0]);
|
|
||||||
if (image) {
|
|
||||||
this.renderBackgroundRepeating(container, bounds, image, arr.length - (index+1), borderData);
|
|
||||||
} else {
|
|
||||||
log("Error loading background-image", backgroundImage.args[0]);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case "linear-gradient":
|
|
||||||
case "gradient":
|
|
||||||
var gradientImage = this.images.get(backgroundImage.value);
|
|
||||||
if (gradientImage) {
|
|
||||||
this.renderBackgroundGradient(gradientImage, bounds, borderData);
|
|
||||||
} else {
|
|
||||||
log("Error loading background-image", backgroundImage.args[0]);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case "none":
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
log("Unknown background-image type", backgroundImage.args[0]);
|
|
||||||
}
|
|
||||||
}, this);
|
|
||||||
};
|
|
||||||
|
|
||||||
Renderer.prototype.renderBackgroundRepeating = function(container, bounds, imageContainer, index, borderData) {
|
|
||||||
var size = container.parseBackgroundSize(bounds, imageContainer.image, index);
|
|
||||||
var position = container.parseBackgroundPosition(bounds, imageContainer.image, index, size);
|
|
||||||
var repeat = container.parseBackgroundRepeat(index);
|
|
||||||
switch (repeat) {
|
|
||||||
case "repeat-x":
|
|
||||||
case "repeat no-repeat":
|
|
||||||
this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + borderData[3], bounds.top + position.top + borderData[0], 99999, size.height, borderData);
|
|
||||||
break;
|
|
||||||
case "repeat-y":
|
|
||||||
case "no-repeat repeat":
|
|
||||||
this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + borderData[0], size.width, 99999, borderData);
|
|
||||||
break;
|
|
||||||
case "no-repeat":
|
|
||||||
this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + position.top + borderData[0], size.width, size.height, borderData);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
this.renderBackgroundRepeat(imageContainer, position, size, {top: bounds.top, left: bounds.left}, borderData[3], borderData[0]);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
module.exports = Renderer;
|
|
@ -1,181 +0,0 @@
|
|||||||
var Renderer = require('../renderer');
|
|
||||||
var LinearGradientContainer = require('../lineargradientcontainer');
|
|
||||||
var log = require('../log');
|
|
||||||
|
|
||||||
function CanvasRenderer(width, height) {
|
|
||||||
Renderer.apply(this, arguments);
|
|
||||||
this.canvas = this.options.canvas || this.document.createElement("canvas");
|
|
||||||
if (!this.options.canvas) {
|
|
||||||
this.canvas.width = width;
|
|
||||||
this.canvas.height = height;
|
|
||||||
}
|
|
||||||
this.ctx = this.canvas.getContext("2d");
|
|
||||||
this.taintCtx = this.document.createElement("canvas").getContext("2d");
|
|
||||||
this.ctx.textBaseline = "bottom";
|
|
||||||
this.variables = {};
|
|
||||||
log("Initialized CanvasRenderer with size", width, "x", height);
|
|
||||||
}
|
|
||||||
|
|
||||||
CanvasRenderer.prototype = Object.create(Renderer.prototype);
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.setFillStyle = function(fillStyle) {
|
|
||||||
this.ctx.fillStyle = typeof(fillStyle) === "object" && !!fillStyle.isColor ? fillStyle.toString() : fillStyle;
|
|
||||||
return this.ctx;
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.rectangle = function(left, top, width, height, color) {
|
|
||||||
this.setFillStyle(color).fillRect(left, top, width, height);
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.circle = function(left, top, size, color) {
|
|
||||||
this.setFillStyle(color);
|
|
||||||
this.ctx.beginPath();
|
|
||||||
this.ctx.arc(left + size / 2, top + size / 2, size / 2, 0, Math.PI*2, true);
|
|
||||||
this.ctx.closePath();
|
|
||||||
this.ctx.fill();
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.circleStroke = function(left, top, size, color, stroke, strokeColor) {
|
|
||||||
this.circle(left, top, size, color);
|
|
||||||
this.ctx.strokeStyle = strokeColor.toString();
|
|
||||||
this.ctx.stroke();
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.drawShape = function(shape, color) {
|
|
||||||
this.shape(shape);
|
|
||||||
this.setFillStyle(color).fill();
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.taints = function(imageContainer) {
|
|
||||||
if (imageContainer.tainted === null) {
|
|
||||||
this.taintCtx.drawImage(imageContainer.image, 0, 0);
|
|
||||||
try {
|
|
||||||
this.taintCtx.getImageData(0, 0, 1, 1);
|
|
||||||
imageContainer.tainted = false;
|
|
||||||
} catch(e) {
|
|
||||||
this.taintCtx = document.createElement("canvas").getContext("2d");
|
|
||||||
imageContainer.tainted = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return imageContainer.tainted;
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.drawImage = function(imageContainer, sx, sy, sw, sh, dx, dy, dw, dh) {
|
|
||||||
if (!this.taints(imageContainer) || this.options.allowTaint) {
|
|
||||||
this.ctx.drawImage(imageContainer.image, sx, sy, sw, sh, dx, dy, dw, dh);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.clip = function(shapes, callback, context) {
|
|
||||||
this.ctx.save();
|
|
||||||
shapes.filter(hasEntries).forEach(function(shape) {
|
|
||||||
this.shape(shape).clip();
|
|
||||||
}, this);
|
|
||||||
callback.call(context);
|
|
||||||
this.ctx.restore();
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.shape = function(shape) {
|
|
||||||
this.ctx.beginPath();
|
|
||||||
shape.forEach(function(point, index) {
|
|
||||||
if (point[0] === "rect") {
|
|
||||||
this.ctx.rect.apply(this.ctx, point.slice(1));
|
|
||||||
} else {
|
|
||||||
this.ctx[(index === 0) ? "moveTo" : point[0] + "To" ].apply(this.ctx, point.slice(1));
|
|
||||||
}
|
|
||||||
}, this);
|
|
||||||
this.ctx.closePath();
|
|
||||||
return this.ctx;
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.font = function(color, style, variant, weight, size, family) {
|
|
||||||
this.setFillStyle(color).font = [style, variant, weight, size, family].join(" ").split(",")[0];
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.fontShadow = function(color, offsetX, offsetY, blur) {
|
|
||||||
this.setVariable("shadowColor", color.toString())
|
|
||||||
.setVariable("shadowOffsetY", offsetX)
|
|
||||||
.setVariable("shadowOffsetX", offsetY)
|
|
||||||
.setVariable("shadowBlur", blur);
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.clearShadow = function() {
|
|
||||||
this.setVariable("shadowColor", "rgba(0,0,0,0)");
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.setOpacity = function(opacity) {
|
|
||||||
this.ctx.globalAlpha = opacity;
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.setTransform = function(transform) {
|
|
||||||
this.ctx.translate(transform.origin[0], transform.origin[1]);
|
|
||||||
this.ctx.transform.apply(this.ctx, transform.matrix);
|
|
||||||
this.ctx.translate(-transform.origin[0], -transform.origin[1]);
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.setVariable = function(property, value) {
|
|
||||||
if (this.variables[property] !== value) {
|
|
||||||
this.variables[property] = this.ctx[property] = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
return this;
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.text = function(text, left, bottom) {
|
|
||||||
this.ctx.fillText(text, left, bottom);
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.backgroundRepeatShape = function(imageContainer, backgroundPosition, size, bounds, left, top, width, height, borderData) {
|
|
||||||
var shape = [
|
|
||||||
["line", Math.round(left), Math.round(top)],
|
|
||||||
["line", Math.round(left + width), Math.round(top)],
|
|
||||||
["line", Math.round(left + width), Math.round(height + top)],
|
|
||||||
["line", Math.round(left), Math.round(height + top)]
|
|
||||||
];
|
|
||||||
this.clip([shape], function() {
|
|
||||||
this.renderBackgroundRepeat(imageContainer, backgroundPosition, size, bounds, borderData[3], borderData[0]);
|
|
||||||
}, this);
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.renderBackgroundRepeat = function(imageContainer, backgroundPosition, size, bounds, borderLeft, borderTop) {
|
|
||||||
var offsetX = Math.round(bounds.left + backgroundPosition.left + borderLeft), offsetY = Math.round(bounds.top + backgroundPosition.top + borderTop);
|
|
||||||
this.setFillStyle(this.ctx.createPattern(this.resizeImage(imageContainer, size), "repeat"));
|
|
||||||
this.ctx.translate(offsetX, offsetY);
|
|
||||||
this.ctx.fill();
|
|
||||||
this.ctx.translate(-offsetX, -offsetY);
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.renderBackgroundGradient = function(gradientImage, bounds) {
|
|
||||||
if (gradientImage instanceof LinearGradientContainer) {
|
|
||||||
var gradient = this.ctx.createLinearGradient(
|
|
||||||
bounds.left + bounds.width * gradientImage.x0,
|
|
||||||
bounds.top + bounds.height * gradientImage.y0,
|
|
||||||
bounds.left + bounds.width * gradientImage.x1,
|
|
||||||
bounds.top + bounds.height * gradientImage.y1);
|
|
||||||
gradientImage.colorStops.forEach(function(colorStop) {
|
|
||||||
gradient.addColorStop(colorStop.stop, colorStop.color.toString());
|
|
||||||
});
|
|
||||||
this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, gradient);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
CanvasRenderer.prototype.resizeImage = function(imageContainer, size) {
|
|
||||||
var image = imageContainer.image;
|
|
||||||
if(image.width === size.width && image.height === size.height) {
|
|
||||||
return image;
|
|
||||||
}
|
|
||||||
|
|
||||||
var ctx, canvas = document.createElement('canvas');
|
|
||||||
canvas.width = size.width;
|
|
||||||
canvas.height = size.height;
|
|
||||||
ctx = canvas.getContext("2d");
|
|
||||||
ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height );
|
|
||||||
return canvas;
|
|
||||||
};
|
|
||||||
|
|
||||||
function hasEntries(array) {
|
|
||||||
return array.length > 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = CanvasRenderer;
|
|
@ -1,18 +0,0 @@
|
|||||||
var NodeContainer = require('./nodecontainer');
|
|
||||||
|
|
||||||
function StackingContext(hasOwnStacking, opacity, element, parent) {
|
|
||||||
NodeContainer.call(this, element, parent);
|
|
||||||
this.ownStacking = hasOwnStacking;
|
|
||||||
this.contexts = [];
|
|
||||||
this.children = [];
|
|
||||||
this.opacity = (this.parent ? this.parent.stack.opacity : 1) * opacity;
|
|
||||||
}
|
|
||||||
|
|
||||||
StackingContext.prototype = Object.create(NodeContainer.prototype);
|
|
||||||
|
|
||||||
StackingContext.prototype.getParentStack = function(context) {
|
|
||||||
var parentStack = (this.parent) ? this.parent.stack : null;
|
|
||||||
return parentStack ? (parentStack.ownStacking ? parentStack : parentStack.getParentStack(context)) : context.stack;
|
|
||||||
};
|
|
||||||
|
|
||||||
module.exports = StackingContext;
|
|
@ -1,51 +0,0 @@
|
|||||||
function Support(document) {
|
|
||||||
this.rangeBounds = this.testRangeBounds(document);
|
|
||||||
this.cors = this.testCORS();
|
|
||||||
this.svg = this.testSVG();
|
|
||||||
}
|
|
||||||
|
|
||||||
Support.prototype.testRangeBounds = function(document) {
|
|
||||||
var range, testElement, rangeBounds, rangeHeight, support = false;
|
|
||||||
|
|
||||||
if (document.createRange) {
|
|
||||||
range = document.createRange();
|
|
||||||
if (range.getBoundingClientRect) {
|
|
||||||
testElement = document.createElement('boundtest');
|
|
||||||
testElement.style.height = "123px";
|
|
||||||
testElement.style.display = "block";
|
|
||||||
document.body.appendChild(testElement);
|
|
||||||
|
|
||||||
range.selectNode(testElement);
|
|
||||||
rangeBounds = range.getBoundingClientRect();
|
|
||||||
rangeHeight = rangeBounds.height;
|
|
||||||
|
|
||||||
if (rangeHeight === 123) {
|
|
||||||
support = true;
|
|
||||||
}
|
|
||||||
document.body.removeChild(testElement);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return support;
|
|
||||||
};
|
|
||||||
|
|
||||||
Support.prototype.testCORS = function() {
|
|
||||||
return typeof((new Image()).crossOrigin) !== "undefined";
|
|
||||||
};
|
|
||||||
|
|
||||||
Support.prototype.testSVG = function() {
|
|
||||||
var img = new Image();
|
|
||||||
var canvas = document.createElement("canvas");
|
|
||||||
var ctx = canvas.getContext("2d");
|
|
||||||
img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
|
|
||||||
|
|
||||||
try {
|
|
||||||
ctx.drawImage(img, 0, 0);
|
|
||||||
canvas.toDataURL();
|
|
||||||
} catch(e) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
|
|
||||||
module.exports = Support;
|
|
@ -1,52 +0,0 @@
|
|||||||
var XHR = require('./xhr');
|
|
||||||
var decode64 = require('./utils').decode64;
|
|
||||||
|
|
||||||
function SVGContainer(src) {
|
|
||||||
this.src = src;
|
|
||||||
this.image = null;
|
|
||||||
var self = this;
|
|
||||||
|
|
||||||
this.promise = this.hasFabric().then(function() {
|
|
||||||
return (self.isInline(src) ? Promise.resolve(self.inlineFormatting(src)) : XHR(src));
|
|
||||||
}).then(function(svg) {
|
|
||||||
return new Promise(function(resolve) {
|
|
||||||
window.html2canvas.svg.fabric.loadSVGFromString(svg, self.createCanvas.call(self, resolve));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
SVGContainer.prototype.hasFabric = function() {
|
|
||||||
return !window.html2canvas.svg || !window.html2canvas.svg.fabric ? Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg")) : Promise.resolve();
|
|
||||||
};
|
|
||||||
|
|
||||||
SVGContainer.prototype.inlineFormatting = function(src) {
|
|
||||||
return (/^data:image\/svg\+xml;base64,/.test(src)) ? this.decode64(this.removeContentType(src)) : this.removeContentType(src);
|
|
||||||
};
|
|
||||||
|
|
||||||
SVGContainer.prototype.removeContentType = function(src) {
|
|
||||||
return src.replace(/^data:image\/svg\+xml(;base64)?,/,'');
|
|
||||||
};
|
|
||||||
|
|
||||||
SVGContainer.prototype.isInline = function(src) {
|
|
||||||
return (/^data:image\/svg\+xml/i.test(src));
|
|
||||||
};
|
|
||||||
|
|
||||||
SVGContainer.prototype.createCanvas = function(resolve) {
|
|
||||||
var self = this;
|
|
||||||
return function (objects, options) {
|
|
||||||
var canvas = new window.html2canvas.svg.fabric.StaticCanvas('c');
|
|
||||||
self.image = canvas.lowerCanvasEl;
|
|
||||||
canvas
|
|
||||||
.setWidth(options.width)
|
|
||||||
.setHeight(options.height)
|
|
||||||
.add(window.html2canvas.svg.fabric.util.groupSVGElements(objects, options))
|
|
||||||
.renderAll();
|
|
||||||
resolve(canvas.lowerCanvasEl);
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
SVGContainer.prototype.decode64 = function(str) {
|
|
||||||
return (typeof(window.atob) === "function") ? window.atob(str) : decode64(str);
|
|
||||||
};
|
|
||||||
|
|
||||||
module.exports = SVGContainer;
|
|
@ -1,25 +0,0 @@
|
|||||||
var SVGContainer = require('./svgcontainer');
|
|
||||||
|
|
||||||
function SVGNodeContainer(node, _native) {
|
|
||||||
this.src = node;
|
|
||||||
this.image = null;
|
|
||||||
var self = this;
|
|
||||||
|
|
||||||
this.promise = _native ? new Promise(function(resolve, reject) {
|
|
||||||
self.image = new Image();
|
|
||||||
self.image.onload = resolve;
|
|
||||||
self.image.onerror = reject;
|
|
||||||
self.image.src = "data:image/svg+xml," + (new XMLSerializer()).serializeToString(node);
|
|
||||||
if (self.image.complete === true) {
|
|
||||||
resolve(self.image);
|
|
||||||
}
|
|
||||||
}) : this.hasFabric().then(function() {
|
|
||||||
return new Promise(function(resolve) {
|
|
||||||
window.html2canvas.svg.fabric.parseSVGDocument(node, self.createCanvas.call(self, resolve));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
SVGNodeContainer.prototype = Object.create(SVGContainer.prototype);
|
|
||||||
|
|
||||||
module.exports = SVGNodeContainer;
|
|
@ -1,33 +0,0 @@
|
|||||||
var NodeContainer = require('./nodecontainer');
|
|
||||||
|
|
||||||
function TextContainer(node, parent) {
|
|
||||||
NodeContainer.call(this, node, parent);
|
|
||||||
}
|
|
||||||
|
|
||||||
TextContainer.prototype = Object.create(NodeContainer.prototype);
|
|
||||||
|
|
||||||
TextContainer.prototype.applyTextTransform = function() {
|
|
||||||
this.node.data = this.transform(this.parent.css("textTransform"));
|
|
||||||
};
|
|
||||||
|
|
||||||
TextContainer.prototype.transform = function(transform) {
|
|
||||||
var text = this.node.data;
|
|
||||||
switch(transform){
|
|
||||||
case "lowercase":
|
|
||||||
return text.toLowerCase();
|
|
||||||
case "capitalize":
|
|
||||||
return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize);
|
|
||||||
case "uppercase":
|
|
||||||
return text.toUpperCase();
|
|
||||||
default:
|
|
||||||
return text;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
function capitalize(m, p1, p2) {
|
|
||||||
if (m.length > 0) {
|
|
||||||
return p1 + p2.toUpperCase();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = TextContainer;
|
|
169
src/utils.js
169
src/utils.js
@ -1,169 +0,0 @@
|
|||||||
exports.smallImage = function smallImage() {
|
|
||||||
return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
|
|
||||||
};
|
|
||||||
|
|
||||||
exports.bind = function(callback, context) {
|
|
||||||
return function() {
|
|
||||||
return callback.apply(context, arguments);
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
/*
|
|
||||||
* base64-arraybuffer
|
|
||||||
* https://github.com/niklasvh/base64-arraybuffer
|
|
||||||
*
|
|
||||||
* Copyright (c) 2012 Niklas von Hertzen
|
|
||||||
* Licensed under the MIT license.
|
|
||||||
*/
|
|
||||||
|
|
||||||
exports.decode64 = function(base64) {
|
|
||||||
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
||||||
var len = base64.length, i, encoded1, encoded2, encoded3, encoded4, byte1, byte2, byte3;
|
|
||||||
|
|
||||||
var output = "";
|
|
||||||
|
|
||||||
for (i = 0; i < len; i+=4) {
|
|
||||||
encoded1 = chars.indexOf(base64[i]);
|
|
||||||
encoded2 = chars.indexOf(base64[i+1]);
|
|
||||||
encoded3 = chars.indexOf(base64[i+2]);
|
|
||||||
encoded4 = chars.indexOf(base64[i+3]);
|
|
||||||
|
|
||||||
byte1 = (encoded1 << 2) | (encoded2 >> 4);
|
|
||||||
byte2 = ((encoded2 & 15) << 4) | (encoded3 >> 2);
|
|
||||||
byte3 = ((encoded3 & 3) << 6) | encoded4;
|
|
||||||
if (encoded3 === 64) {
|
|
||||||
output += String.fromCharCode(byte1);
|
|
||||||
} else if (encoded4 === 64 || encoded4 === -1) {
|
|
||||||
output += String.fromCharCode(byte1, byte2);
|
|
||||||
} else{
|
|
||||||
output += String.fromCharCode(byte1, byte2, byte3);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return output;
|
|
||||||
};
|
|
||||||
|
|
||||||
exports.getBounds = function(node) {
|
|
||||||
if (node.getBoundingClientRect) {
|
|
||||||
var clientRect = node.getBoundingClientRect();
|
|
||||||
var width = node.offsetWidth == null ? clientRect.width : node.offsetWidth;
|
|
||||||
return {
|
|
||||||
top: clientRect.top,
|
|
||||||
bottom: clientRect.bottom || (clientRect.top + clientRect.height),
|
|
||||||
right: clientRect.left + width,
|
|
||||||
left: clientRect.left,
|
|
||||||
width: width,
|
|
||||||
height: node.offsetHeight == null ? clientRect.height : node.offsetHeight
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return {};
|
|
||||||
};
|
|
||||||
|
|
||||||
exports.offsetBounds = function(node) {
|
|
||||||
var parent = node.offsetParent ? exports.offsetBounds(node.offsetParent) : {top: 0, left: 0};
|
|
||||||
|
|
||||||
return {
|
|
||||||
top: node.offsetTop + parent.top,
|
|
||||||
bottom: node.offsetTop + node.offsetHeight + parent.top,
|
|
||||||
right: node.offsetLeft + parent.left + node.offsetWidth,
|
|
||||||
left: node.offsetLeft + parent.left,
|
|
||||||
width: node.offsetWidth,
|
|
||||||
height: node.offsetHeight
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
exports.parseBackgrounds = function(backgroundImage) {
|
|
||||||
var whitespace = ' \r\n\t',
|
|
||||||
method, definition, prefix, prefix_i, block, results = [],
|
|
||||||
mode = 0, numParen = 0, quote, args;
|
|
||||||
var appendResult = function() {
|
|
||||||
if(method) {
|
|
||||||
if (definition.substr(0, 1) === '"') {
|
|
||||||
definition = definition.substr(1, definition.length - 2);
|
|
||||||
}
|
|
||||||
if (definition) {
|
|
||||||
args.push(definition);
|
|
||||||
}
|
|
||||||
if (method.substr(0, 1) === '-' && (prefix_i = method.indexOf('-', 1 ) + 1) > 0) {
|
|
||||||
prefix = method.substr(0, prefix_i);
|
|
||||||
method = method.substr(prefix_i);
|
|
||||||
}
|
|
||||||
results.push({
|
|
||||||
prefix: prefix,
|
|
||||||
method: method.toLowerCase(),
|
|
||||||
value: block,
|
|
||||||
args: args,
|
|
||||||
image: null
|
|
||||||
});
|
|
||||||
}
|
|
||||||
args = [];
|
|
||||||
method = prefix = definition = block = '';
|
|
||||||
};
|
|
||||||
args = [];
|
|
||||||
method = prefix = definition = block = '';
|
|
||||||
backgroundImage.split("").forEach(function(c) {
|
|
||||||
if (mode === 0 && whitespace.indexOf(c) > -1) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
switch(c) {
|
|
||||||
case '"':
|
|
||||||
if(!quote) {
|
|
||||||
quote = c;
|
|
||||||
} else if(quote === c) {
|
|
||||||
quote = null;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case '(':
|
|
||||||
if(quote) {
|
|
||||||
break;
|
|
||||||
} else if(mode === 0) {
|
|
||||||
mode = 1;
|
|
||||||
block += c;
|
|
||||||
return;
|
|
||||||
} else {
|
|
||||||
numParen++;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case ')':
|
|
||||||
if (quote) {
|
|
||||||
break;
|
|
||||||
} else if(mode === 1) {
|
|
||||||
if(numParen === 0) {
|
|
||||||
mode = 0;
|
|
||||||
block += c;
|
|
||||||
appendResult();
|
|
||||||
return;
|
|
||||||
} else {
|
|
||||||
numParen--;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case ',':
|
|
||||||
if (quote) {
|
|
||||||
break;
|
|
||||||
} else if(mode === 0) {
|
|
||||||
appendResult();
|
|
||||||
return;
|
|
||||||
} else if (mode === 1) {
|
|
||||||
if (numParen === 0 && !method.match(/^url$/i)) {
|
|
||||||
args.push(definition);
|
|
||||||
definition = '';
|
|
||||||
block += c;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
block += c;
|
|
||||||
if (mode === 0) {
|
|
||||||
method += c;
|
|
||||||
} else {
|
|
||||||
definition += c;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
appendResult();
|
|
||||||
return results;
|
|
||||||
};
|
|
@ -1,10 +0,0 @@
|
|||||||
var GradientContainer = require('./gradientcontainer');
|
|
||||||
|
|
||||||
function WebkitGradientContainer(imageData) {
|
|
||||||
GradientContainer.apply(this, arguments);
|
|
||||||
this.type = imageData.args[0] === "linear" ? GradientContainer.TYPES.LINEAR : GradientContainer.TYPES.RADIAL;
|
|
||||||
}
|
|
||||||
|
|
||||||
WebkitGradientContainer.prototype = Object.create(GradientContainer.prototype);
|
|
||||||
|
|
||||||
module.exports = WebkitGradientContainer;
|
|
22
src/xhr.js
22
src/xhr.js
@ -1,22 +0,0 @@
|
|||||||
function XHR(url) {
|
|
||||||
return new Promise(function(resolve, reject) {
|
|
||||||
var xhr = new XMLHttpRequest();
|
|
||||||
xhr.open('GET', url);
|
|
||||||
|
|
||||||
xhr.onload = function() {
|
|
||||||
if (xhr.status === 200) {
|
|
||||||
resolve(xhr.responseText);
|
|
||||||
} else {
|
|
||||||
reject(new Error(xhr.statusText));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
xhr.onerror = function() {
|
|
||||||
reject(new Error("Network Error"));
|
|
||||||
};
|
|
||||||
|
|
||||||
xhr.send();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = XHR;
|
|
@ -4,11 +4,7 @@ var h2cSelector, h2cOptions;
|
|||||||
document.write('<script type="text/javascript" src="' + src + '.js?' + Math.random() + '"></script>');
|
document.write('<script type="text/javascript" src="' + src + '.js?' + Math.random() + '"></script>');
|
||||||
}
|
}
|
||||||
|
|
||||||
['/node_modules/bluebird/js/browser/bluebird', '/tests/assets/jquery-1.6.2', '/dist/html2canvas'].forEach(appendScript);
|
['/tests/assets/jquery-1.6.2', '/dist/html2canvas'].forEach(appendScript);
|
||||||
|
|
||||||
if (typeof(noFabric) === "undefined") {
|
|
||||||
appendScript('/dist/html2canvas.svg');
|
|
||||||
}
|
|
||||||
|
|
||||||
window.onload = function() {
|
window.onload = function() {
|
||||||
(function( $ ){
|
(function( $ ){
|
||||||
@ -21,8 +17,7 @@ var h2cSelector, h2cOptions;
|
|||||||
timeoutTimer = false,
|
timeoutTimer = false,
|
||||||
timer = date.getTime();
|
timer = date.getTime();
|
||||||
options = options || {};
|
options = options || {};
|
||||||
|
var promise = html2canvas(this[0], options);
|
||||||
var promise = html2canvas(this, options);
|
|
||||||
promise['catch'](function(err) {
|
promise['catch'](function(err) {
|
||||||
console.log("html2canvas threw an error", err);
|
console.log("html2canvas threw an error", err);
|
||||||
});
|
});
|
||||||
|
21
webpack.config.js
Normal file
21
webpack.config.js
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
const webpack = require('webpack');
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
entry: './src/index.js',
|
||||||
|
output: {
|
||||||
|
filename: './dist/html2canvas.js',
|
||||||
|
library: 'html2canvas'
|
||||||
|
},
|
||||||
|
module: {
|
||||||
|
loaders: [{
|
||||||
|
test: /\.js$/,
|
||||||
|
exclude: /node_modules/,
|
||||||
|
loader: 'babel-loader'
|
||||||
|
}]
|
||||||
|
},
|
||||||
|
plugins: [
|
||||||
|
new webpack.DefinePlugin({
|
||||||
|
'__DEV__': true
|
||||||
|
})
|
||||||
|
]
|
||||||
|
};
|
Loading…
x
Reference in New Issue
Block a user