Compare commits

..

7 Commits

Author SHA1 Message Date
CI
b09ee30dae chore(release): 1.0.0 2021-07-04 05:15:53 +00:00
72cd528429 add features for border-style dashed, dotted, double. (#2531) 2021-07-04 12:17:07 +08:00
2a013e20c8 deps: update www deps (#2525) 2021-05-08 20:31:35 +08:00
ff35c7dbd3 test: update karma runner (#2524)
* test: update karma runner

* fix: Promise polyfill for testrunner
2021-05-08 18:32:03 +08:00
ba172678f0 fix top right border radius (#2522) 2021-05-07 17:32:51 +08:00
7222aba1b4 ci: update docs publish action (#2451) 2020-12-29 15:25:08 +08:00
82b7da558c fix: opacity with overflow hidden (#2450) 2020-12-29 12:29:00 +08:00
21 changed files with 60042 additions and 8808 deletions

View File

@ -297,7 +297,7 @@ jobs:
name: docs
path: docs
- name: Publish docs
uses: JamesIves/github-pages-deploy-action@3.5.9
uses: JamesIves/github-pages-deploy-action@3.7.1
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BRANCH: gh-pages

View File

@ -2,6 +2,27 @@
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
# [1.0.0](https://github.com/niklasvh/html2canvas/compare/v1.0.0-rc.7...v1.0.0) (2021-07-04)
### ci
* update docs publish action (#2451) ([7222aba](https://github.com/niklasvh/html2canvas/commit/7222aba1b42138c3d466525172411b3d9869095f)), closes [#2451](https://github.com/niklasvh/html2canvas/issues/2451)
### deps
* update www deps (#2525) ([2a013e2](https://github.com/niklasvh/html2canvas/commit/2a013e20c814b7dbaea98f54f0bde8f553eb79a2)), closes [#2525](https://github.com/niklasvh/html2canvas/issues/2525)
### fix
* opacity with overflow hidden (#2450) ([82b7da5](https://github.com/niklasvh/html2canvas/commit/82b7da558c342e7f53d298bb1d843a5db86c3b21)), closes [#2450](https://github.com/niklasvh/html2canvas/issues/2450)
### test
* update karma runner (#2524) ([ff35c7d](https://github.com/niklasvh/html2canvas/commit/ff35c7dbd33f863f5b614d778baf8cb1e8dded60)), closes [#2524](https://github.com/niklasvh/html2canvas/issues/2524)
# [1.0.0-rc.7](https://github.com/niklasvh/html2canvas/compare/v1.0.0-rc.6...v1.0.0-rc.7) (2020-08-09)

103
karma.js
View File

@ -1,103 +0,0 @@
const Server = require('karma').Server;
const cfg = require('karma').config;
const path = require('path');
const proxy = require('html2canvas-proxy');
const karmaConfig = cfg.parseConfig(path.resolve('./karma.conf.js'));
const server = new Server(karmaConfig, (exitCode) => {
console.log('Karma has exited with ' + exitCode);
process.exit(exitCode)
});
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const filenamifyUrl = require('filenamify-url');
const mkdirp = require('mkdirp');
const screenshotFolder = './tmp/reftests';
const metadataFolder = './tmp/reftests/metadata';
mkdirp.sync(path.resolve(__dirname, screenshotFolder));
mkdirp.sync(path.resolve(__dirname, metadataFolder));
const CORS_PORT = 8081;
const corsApp = express();
corsApp.use('/proxy', proxy());
corsApp.use('/cors', cors(), express.static(path.resolve(__dirname)));
corsApp.use('/', express.static(path.resolve(__dirname, '/tests')));
corsApp.use((error, req, res, next) => {
console.error(error);
next();
});
process.on('uncaughtException', (err) => {
if(err.errno === 'EADDRINUSE') {
console.warn(err);
} else {
console.log(err);
process.exit(1);
}
});
corsApp.listen(CORS_PORT, () => {
console.log(`CORS server running on port ${CORS_PORT}`);
});
const app = express();
app.use(cors());
app.use((req, res, next) => {
// IE9 doesn't set headers for cross-domain ajax requests
if(typeof(req.headers['content-type']) === 'undefined'){
req.headers['content-type'] = "application/json";
}
next();
});
app.use(
bodyParser.json({
limit: '15mb',
type: '*/*'
})
);
const prefix = 'data:image/png;base64,';
const writeScreenshot = (buffer, body) => {
const filename = `${filenamifyUrl(
body.test.replace(/^\/tests\/reftests\//, '').replace(/\.html$/, ''),
{replacement: '-'}
)}!${[process.env.TARGET_BROWSER, body.platform.name, body.platform.version].join('-')}`;
fs.writeFileSync(path.resolve(__dirname, screenshotFolder, `${filename}.png`), buffer);
return filename;
};
app.post('/screenshot', (req, res) => {
if (!req.body || !req.body.screenshot) {
return res.sendStatus(400);
}
const buffer = new Buffer(req.body.screenshot.substring(prefix.length), 'base64');
const filename = writeScreenshot(buffer, req.body);
fs.writeFileSync(path.resolve(__dirname, metadataFolder, `${filename}.json`), JSON.stringify({
windowWidth: req.body.windowWidth,
windowHeight: req.body.windowHeight,
platform: req.body.platform,
devicePixelRatio: req.body.devicePixelRatio,
test: req.body.test,
id: process.env.TARGET_BROWSER,
screenshot: filename
}));
return res.sendStatus(200);
});
app.use((error, req, res, next) => {
console.error(error);
next();
});
const listener = app.listen(8000, () => {
server.start();
});

30274
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -6,7 +6,7 @@
"module": "dist/html2canvas.esm.js",
"typings": "dist/types/index.d.ts",
"browser": "dist/html2canvas.js",
"version": "1.0.0-rc.7",
"version": "1.0.0",
"author": {
"name": "Niklas von Hertzen",
"email": "niklasvh@gmail.com",
@ -28,8 +28,10 @@
"@babel/preset-env": "^7.4.3",
"@babel/preset-flow": "^7.0.0",
"@types/chai": "^4.1.7",
"@types/express": "^4.17.11",
"@types/glob": "^7.1.1",
"@types/jest": "^24.0.18",
"@types/karma": "^6.3.0",
"@types/mocha": "^5.2.6",
"@types/node": "^11.13.2",
"@types/platform": "^1.3.2",
@ -50,20 +52,20 @@
"eslint": "^5.16.0",
"eslint-config-prettier": "^4.2.0",
"eslint-plugin-prettier": "3.0.1",
"express": "^4.16.4",
"express": "^4.17.1",
"filenamify-url": "1.0.0",
"glob": "7.1.3",
"html2canvas-proxy": "1.0.1",
"jest": "^24.9.0",
"jquery": "^3.5.1",
"js-polyfills": "^0.1.42",
"karma": "^4.0.1",
"karma-chrome-launcher": "^2.2.0",
"karma": "^6.3.2",
"karma-chrome-launcher": "^3.1.0",
"karma-edge-launcher": "^0.4.2",
"karma-firefox-launcher": "^1.1.0",
"karma-firefox-launcher": "^2.1.0",
"karma-ie-launcher": "^1.0.0",
"karma-junit-reporter": "^1.2.0",
"karma-mocha": "^1.3.0",
"karma-junit-reporter": "^2.0.1",
"karma-mocha": "^2.0.1",
"karma-safarinative-launcher": "^1.1.0",
"karma-sauce-launcher": "^2.0.2",
"mocha": "^6.1.4",
@ -88,7 +90,8 @@
"uglify-js": "^3.5.11",
"uglifyjs-webpack-plugin": "^1.1.2",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.12"
"webpack-cli": "^3.3.12",
"yargs": "^17.0.1"
},
"scripts": {
"prebuild": "rimraf dist/ && rimraf build/ && mkdirp dist && mkdirp build",
@ -103,10 +106,10 @@
"lint": "eslint src/**/*.ts",
"test": "npm run lint && npm run unittest && npm run karma",
"unittest": "jest",
"karma": "node karma",
"karma": "ts-node tests/karma",
"watch": "rollup -c rollup.config.ts -w",
"watch:unittest": "mocha --require ts-node/register --watch-extensions ts -w src/**/__tests__/*.ts",
"start": "node tests/server"
"start": "ts-node tests/server --port=8080 --cors=8081"
},
"homepage": "https://html2canvas.hertzen.com",
"license": "MIT",

View File

@ -1,7 +1,10 @@
import {IPropertyIdentValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
export enum BORDER_STYLE {
NONE = 0,
SOLID = 1
SOLID = 1,
DASHED = 2,
DOTTED = 3,
DOUBLE = 4
}
const borderStyleForSide = (side: string): IPropertyIdentValueDescriptor<BORDER_STYLE> => ({
@ -13,6 +16,12 @@ const borderStyleForSide = (side: string): IPropertyIdentValueDescriptor<BORDER_
switch (style) {
case 'none':
return BORDER_STYLE.NONE;
case 'dashed':
return BORDER_STYLE.DASHED;
case 'dotted':
return BORDER_STYLE.DOTTED;
case 'double':
return BORDER_STYLE.DOUBLE;
}
return BORDER_STYLE.SOLID;
}

View File

@ -50,6 +50,7 @@ export const display: IPropertyListDescriptor<Display> = {
const parseDisplayValue = (display: string): Display => {
switch (display) {
case 'block':
case '-webkit-box':
return DISPLAY.BLOCK;
case 'inline':
return DISPLAY.INLINE;

6
src/global.d.ts vendored
View File

@ -1,7 +1,7 @@
interface CSSStyleDeclaration {
textDecorationColor: string | null;
textDecorationLine: string | null;
overflowWrap: string | null;
textDecorationColor: string;
textDecorationLine: string;
overflowWrap: string;
}
interface DocumentType extends Node, ChildNode {

View File

@ -36,6 +36,105 @@ export const parsePathForBorder = (curves: BoundCurves, borderSide: number): Pat
}
};
export const parsePathForBorderDoubleOuter = (curves: BoundCurves, borderSide: number): Path[] => {
switch (borderSide) {
case 0:
return createPathFromCurves(
curves.topLeftBorderBox,
curves.topLeftBorderDoubleOuterBox,
curves.topRightBorderBox,
curves.topRightBorderDoubleOuterBox
);
case 1:
return createPathFromCurves(
curves.topRightBorderBox,
curves.topRightBorderDoubleOuterBox,
curves.bottomRightBorderBox,
curves.bottomRightBorderDoubleOuterBox
);
case 2:
return createPathFromCurves(
curves.bottomRightBorderBox,
curves.bottomRightBorderDoubleOuterBox,
curves.bottomLeftBorderBox,
curves.bottomLeftBorderDoubleOuterBox
);
case 3:
default:
return createPathFromCurves(
curves.bottomLeftBorderBox,
curves.bottomLeftBorderDoubleOuterBox,
curves.topLeftBorderBox,
curves.topLeftBorderDoubleOuterBox
);
}
};
export const parsePathForBorderDoubleInner = (curves: BoundCurves, borderSide: number): Path[] => {
switch (borderSide) {
case 0:
return createPathFromCurves(
curves.topLeftBorderDoubleInnerBox,
curves.topLeftPaddingBox,
curves.topRightBorderDoubleInnerBox,
curves.topRightPaddingBox
);
case 1:
return createPathFromCurves(
curves.topRightBorderDoubleInnerBox,
curves.topRightPaddingBox,
curves.bottomRightBorderDoubleInnerBox,
curves.bottomRightPaddingBox
);
case 2:
return createPathFromCurves(
curves.bottomRightBorderDoubleInnerBox,
curves.bottomRightPaddingBox,
curves.bottomLeftBorderDoubleInnerBox,
curves.bottomLeftPaddingBox
);
case 3:
default:
return createPathFromCurves(
curves.bottomLeftBorderDoubleInnerBox,
curves.bottomLeftPaddingBox,
curves.topLeftBorderDoubleInnerBox,
curves.topLeftPaddingBox
);
}
};
export const parsePathForBorderStroke = (curves: BoundCurves, borderSide: number): Path[] => {
switch (borderSide) {
case 0:
return createStrokePathFromCurves(curves.topLeftBorderStroke, curves.topRightBorderStroke);
case 1:
return createStrokePathFromCurves(curves.topRightBorderStroke, curves.bottomRightBorderStroke);
case 2:
return createStrokePathFromCurves(curves.bottomRightBorderStroke, curves.bottomLeftBorderStroke);
case 3:
default:
return createStrokePathFromCurves(curves.bottomLeftBorderStroke, curves.topLeftBorderStroke);
}
};
const createStrokePathFromCurves = (outer1: Path, outer2: Path): Path[] => {
const path = [];
if (isBezierCurve(outer1)) {
path.push(outer1.subdivide(0.5, false));
} else {
path.push(outer1);
}
if (isBezierCurve(outer2)) {
path.push(outer2.subdivide(0.5, true));
} else {
path.push(outer2);
}
return path;
};
const createPathFromCurves = (outer1: Path, inner1: Path, outer2: Path, inner2: Path): Path[] => {
const path = [];
if (isBezierCurve(outer1)) {

View File

@ -5,6 +5,18 @@ import {BezierCurve} from './bezier-curve';
import {Path} from './path';
export class BoundCurves {
readonly topLeftBorderDoubleOuterBox: Path;
readonly topRightBorderDoubleOuterBox: Path;
readonly bottomRightBorderDoubleOuterBox: Path;
readonly bottomLeftBorderDoubleOuterBox: Path;
readonly topLeftBorderDoubleInnerBox: Path;
readonly topRightBorderDoubleInnerBox: Path;
readonly bottomRightBorderDoubleInnerBox: Path;
readonly bottomLeftBorderDoubleInnerBox: Path;
readonly topLeftBorderStroke: Path;
readonly topRightBorderStroke: Path;
readonly bottomRightBorderStroke: Path;
readonly bottomLeftBorderStroke: Path;
readonly topLeftBorderBox: Path;
readonly topRightBorderBox: Path;
readonly bottomRightBorderBox: Path;
@ -60,6 +72,141 @@ export class BoundCurves {
const paddingBottom = getAbsoluteValue(styles.paddingBottom, element.bounds.width);
const paddingLeft = getAbsoluteValue(styles.paddingLeft, element.bounds.width);
this.topLeftBorderDoubleOuterBox =
tlh > 0 || tlv > 0
? getCurvePoints(
bounds.left + borderLeftWidth / 3,
bounds.top + borderTopWidth / 3,
tlh - borderLeftWidth / 3,
tlv - borderTopWidth / 3,
CORNER.TOP_LEFT
)
: new Vector(bounds.left + borderLeftWidth / 3, bounds.top + borderTopWidth / 3);
this.topRightBorderDoubleOuterBox =
tlh > 0 || tlv > 0
? getCurvePoints(
bounds.left + topWidth,
bounds.top + borderTopWidth / 3,
trh - borderRightWidth / 3,
trv - borderTopWidth / 3,
CORNER.TOP_RIGHT
)
: new Vector(bounds.left + bounds.width - borderRightWidth / 3, bounds.top + borderTopWidth / 3);
this.bottomRightBorderDoubleOuterBox =
brh > 0 || brv > 0
? getCurvePoints(
bounds.left + bottomWidth,
bounds.top + rightHeight,
brh - borderRightWidth / 3,
brv - borderBottomWidth / 3,
CORNER.BOTTOM_RIGHT
)
: new Vector(
bounds.left + bounds.width - borderRightWidth / 3,
bounds.top + bounds.height - borderBottomWidth / 3
);
this.bottomLeftBorderDoubleOuterBox =
blh > 0 || blv > 0
? getCurvePoints(
bounds.left + borderLeftWidth / 3,
bounds.top + leftHeight,
blh - borderLeftWidth / 3,
blv - borderBottomWidth / 3,
CORNER.BOTTOM_LEFT
)
: new Vector(bounds.left + borderLeftWidth / 3, bounds.top + bounds.height - borderBottomWidth / 3);
this.topLeftBorderDoubleInnerBox =
tlh > 0 || tlv > 0
? getCurvePoints(
bounds.left + (borderLeftWidth * 2) / 3,
bounds.top + (borderTopWidth * 2) / 3,
tlh - (borderLeftWidth * 2) / 3,
tlv - (borderTopWidth * 2) / 3,
CORNER.TOP_LEFT
)
: new Vector(bounds.left + (borderLeftWidth * 2) / 3, bounds.top + (borderTopWidth * 2) / 3);
this.topRightBorderDoubleInnerBox =
tlh > 0 || tlv > 0
? getCurvePoints(
bounds.left + topWidth,
bounds.top + (borderTopWidth * 2) / 3,
trh - (borderRightWidth * 2) / 3,
trv - (borderTopWidth * 2) / 3,
CORNER.TOP_RIGHT
)
: new Vector(
bounds.left + bounds.width - (borderRightWidth * 2) / 3,
bounds.top + (borderTopWidth * 2) / 3
);
this.bottomRightBorderDoubleInnerBox =
brh > 0 || brv > 0
? getCurvePoints(
bounds.left + bottomWidth,
bounds.top + rightHeight,
brh - (borderRightWidth * 2) / 3,
brv - (borderBottomWidth * 2) / 3,
CORNER.BOTTOM_RIGHT
)
: new Vector(
bounds.left + bounds.width - (borderRightWidth * 2) / 3,
bounds.top + bounds.height - (borderBottomWidth * 2) / 3
);
this.bottomLeftBorderDoubleInnerBox =
blh > 0 || blv > 0
? getCurvePoints(
bounds.left + (borderLeftWidth * 2) / 3,
bounds.top + leftHeight,
blh - (borderLeftWidth * 2) / 3,
blv - (borderBottomWidth * 2) / 3,
CORNER.BOTTOM_LEFT
)
: new Vector(
bounds.left + (borderLeftWidth * 2) / 3,
bounds.top + bounds.height - (borderBottomWidth * 2) / 3
);
this.topLeftBorderStroke =
tlh > 0 || tlv > 0
? getCurvePoints(
bounds.left + borderLeftWidth / 2,
bounds.top + borderTopWidth / 2,
tlh - borderLeftWidth / 2,
tlv - borderTopWidth / 2,
CORNER.TOP_LEFT
)
: new Vector(bounds.left + borderLeftWidth / 2, bounds.top + borderTopWidth / 2);
this.topRightBorderStroke =
tlh > 0 || tlv > 0
? getCurvePoints(
bounds.left + topWidth,
bounds.top + borderTopWidth / 2,
trh - borderRightWidth / 2,
trv - borderTopWidth / 2,
CORNER.TOP_RIGHT
)
: new Vector(bounds.left + bounds.width - borderRightWidth / 2, bounds.top + borderTopWidth / 2);
this.bottomRightBorderStroke =
brh > 0 || brv > 0
? getCurvePoints(
bounds.left + bottomWidth,
bounds.top + rightHeight,
brh - borderRightWidth / 2,
brv - borderBottomWidth / 2,
CORNER.BOTTOM_RIGHT
)
: new Vector(
bounds.left + bounds.width - borderRightWidth / 2,
bounds.top + bounds.height - borderBottomWidth / 2
);
this.bottomLeftBorderStroke =
blh > 0 || blv > 0
? getCurvePoints(
bounds.left + borderLeftWidth / 2,
bounds.top + leftHeight,
blh - borderLeftWidth / 2,
blv - borderBottomWidth / 2,
CORNER.BOTTOM_LEFT
)
: new Vector(bounds.left + borderLeftWidth / 2, bounds.top + bounds.height - borderBottomWidth / 2);
this.topLeftBorderBox =
tlh > 0 || tlv > 0
? getCurvePoints(bounds.left, bounds.top, tlh, tlv, CORNER.TOP_LEFT)
@ -89,10 +236,10 @@ export class BoundCurves {
this.topRightPaddingBox =
trh > 0 || trv > 0
? getCurvePoints(
bounds.left + Math.min(topWidth, bounds.width + borderLeftWidth),
bounds.left + Math.min(topWidth, bounds.width - borderRightWidth),
bounds.top + borderTopWidth,
topWidth > bounds.width + borderLeftWidth ? 0 : trh - borderLeftWidth,
trv - borderTopWidth,
topWidth > bounds.width + borderRightWidth ? 0 : Math.max(0, trh - borderRightWidth),
Math.max(0, trv - borderTopWidth),
CORNER.TOP_RIGHT
)
: new Vector(bounds.left + bounds.width - borderRightWidth, bounds.top + borderTopWidth);
@ -100,9 +247,9 @@ export class BoundCurves {
brh > 0 || brv > 0
? getCurvePoints(
bounds.left + Math.min(bottomWidth, bounds.width - borderLeftWidth),
bounds.top + Math.min(rightHeight, bounds.height + borderTopWidth),
bounds.top + Math.min(rightHeight, bounds.height - borderBottomWidth),
Math.max(0, brh - borderRightWidth),
brv - borderBottomWidth,
Math.max(0, brv - borderBottomWidth),
CORNER.BOTTOM_RIGHT
)
: new Vector(
@ -113,9 +260,9 @@ export class BoundCurves {
blh > 0 || blv > 0
? getCurvePoints(
bounds.left + borderLeftWidth,
bounds.top + leftHeight,
bounds.top + Math.min(leftHeight, bounds.height - borderBottomWidth),
Math.max(0, blh - borderLeftWidth),
blv - borderBottomWidth,
Math.max(0, blv - borderBottomWidth),
CORNER.BOTTOM_LEFT
)
: new Vector(bounds.left + borderLeftWidth, bounds.top + bounds.height - borderBottomWidth);

View File

@ -8,10 +8,15 @@ import {TextContainer} from '../../dom/text-container';
import {Path, transformPath} from '../path';
import {BACKGROUND_CLIP} from '../../css/property-descriptors/background-clip';
import {BoundCurves, calculateBorderBoxPath, calculateContentBoxPath, calculatePaddingBoxPath} from '../bound-curves';
import {isBezierCurve} from '../bezier-curve';
import {BezierCurve, isBezierCurve} from '../bezier-curve';
import {Vector} from '../vector';
import {CSSImageType, CSSURLImage, isLinearGradient, isRadialGradient} from '../../css/types/image';
import {parsePathForBorder} from '../border';
import {
parsePathForBorder,
parsePathForBorderDoubleInner,
parsePathForBorderDoubleOuter,
parsePathForBorderStroke
} from '../border';
import {Cache} from '../../core/cache-storage';
import {calculateBackgroundRendering, getBackgroundValueForIndex} from '../background';
import {isDimensionToken} from '../../css/syntax/parser';
@ -22,7 +27,7 @@ import {contentBox} from '../box-sizing';
import {CanvasElementContainer} from '../../dom/replaced-elements/canvas-element-container';
import {SVGElementContainer} from '../../dom/replaced-elements/svg-element-container';
import {ReplacedElementContainer} from '../../dom/replaced-elements/index';
import {EffectTarget, IElementEffect, isClipEffect, isTransformEffect} from '../effects';
import {EffectTarget, IElementEffect, isClipEffect, isOpacityEffect, isTransformEffect} from '../effects';
import {contains} from '../../core/bitwise';
import {calculateGradientDirection, calculateRadius, processColorStops} from '../../css/types/functions/gradient';
import {FIFTY_PERCENT, getAbsoluteValue} from '../../css/types/length-percentage';
@ -99,6 +104,10 @@ export class CanvasRenderer {
applyEffect(effect: IElementEffect) {
this.ctx.save();
if (isOpacityEffect(effect)) {
this.ctx.globalAlpha = effect.opacity;
}
if (isTransformEffect(effect)) {
this.ctx.translate(effect.offsetX, effect.offsetY);
this.ctx.transform(
@ -128,7 +137,6 @@ export class CanvasRenderer {
async renderStack(stack: StackingContext) {
const styles = stack.element.container.styles;
if (styles.isVisible()) {
this.ctx.globalAlpha = styles.opacity;
await this.renderStackContent(stack);
}
}
@ -627,22 +635,37 @@ export class CanvasRenderer {
}
}
async renderBorder(color: Color, side: number, curvePoints: BoundCurves) {
async renderSolidBorder(color: Color, side: number, curvePoints: BoundCurves) {
this.path(parsePathForBorder(curvePoints, side));
this.ctx.fillStyle = asString(color);
this.ctx.fill();
}
async renderDoubleBorder(color: Color, width: number, side: number, curvePoints: BoundCurves) {
if (width < 3) {
await this.renderSolidBorder(color, side, curvePoints);
return;
}
const outerPaths = parsePathForBorderDoubleOuter(curvePoints, side);
this.path(outerPaths);
this.ctx.fillStyle = asString(color);
this.ctx.fill();
const innerPaths = parsePathForBorderDoubleInner(curvePoints, side);
this.path(innerPaths);
this.ctx.fill();
}
async renderNodeBackgroundAndBorders(paint: ElementPaint) {
this.applyEffects(paint.effects, EffectTarget.BACKGROUND_BORDERS);
const styles = paint.container.styles;
const hasBackground = !isTransparent(styles.backgroundColor) || styles.backgroundImage.length;
const borders = [
{style: styles.borderTopStyle, color: styles.borderTopColor},
{style: styles.borderRightStyle, color: styles.borderRightColor},
{style: styles.borderBottomStyle, color: styles.borderBottomColor},
{style: styles.borderLeftStyle, color: styles.borderLeftColor}
{style: styles.borderTopStyle, color: styles.borderTopColor, width: styles.borderTopWidth},
{style: styles.borderRightStyle, color: styles.borderRightColor, width: styles.borderRightWidth},
{style: styles.borderBottomStyle, color: styles.borderBottomColor, width: styles.borderBottomWidth},
{style: styles.borderLeftStyle, color: styles.borderLeftColor, width: styles.borderLeftWidth}
];
const backgroundPaintingArea = calculateBackgroundCurvedPaintingArea(
@ -702,13 +725,143 @@ export class CanvasRenderer {
let side = 0;
for (const border of borders) {
if (border.style !== BORDER_STYLE.NONE && !isTransparent(border.color)) {
await this.renderBorder(border.color, side, paint.curves);
if (border.style !== BORDER_STYLE.NONE && !isTransparent(border.color) && border.width > 0) {
if (border.style === BORDER_STYLE.DASHED) {
await this.renderDashedDottedBorder(
border.color,
border.width,
side,
paint.curves,
BORDER_STYLE.DASHED
);
} else if (border.style === BORDER_STYLE.DOTTED) {
await this.renderDashedDottedBorder(
border.color,
border.width,
side,
paint.curves,
BORDER_STYLE.DOTTED
);
} else if (border.style === BORDER_STYLE.DOUBLE) {
await this.renderDoubleBorder(border.color, border.width, side, paint.curves);
} else {
await this.renderSolidBorder(border.color, side, paint.curves);
}
}
side++;
}
}
async renderDashedDottedBorder(
color: Color,
width: number,
side: number,
curvePoints: BoundCurves,
style: BORDER_STYLE
) {
this.ctx.save();
const strokePaths = parsePathForBorderStroke(curvePoints, side);
const boxPaths = parsePathForBorder(curvePoints, side);
if (style === BORDER_STYLE.DASHED) {
this.path(boxPaths);
this.ctx.clip();
}
let startX, startY, endX, endY;
if (isBezierCurve(boxPaths[0])) {
startX = (boxPaths[0] as BezierCurve).start.x;
startY = (boxPaths[0] as BezierCurve).start.y;
} else {
startX = (boxPaths[0] as Vector).x;
startY = (boxPaths[0] as Vector).y;
}
if (isBezierCurve(boxPaths[1])) {
endX = (boxPaths[1] as BezierCurve).end.x;
endY = (boxPaths[1] as BezierCurve).end.y;
} else {
endX = (boxPaths[1] as Vector).x;
endY = (boxPaths[1] as Vector).y;
}
let length;
if (side === 0 || side === 2) {
length = Math.abs(startX - endX);
} else {
length = Math.abs(startY - endY);
}
this.ctx.beginPath();
if (style === BORDER_STYLE.DOTTED) {
this.formatPath(strokePaths);
} else {
this.formatPath(boxPaths.slice(0, 2));
}
let dashLength = width < 3 ? width * 3 : width * 2;
let spaceLength = width < 3 ? width * 2 : width;
if (style === BORDER_STYLE.DOTTED) {
dashLength = width;
spaceLength = width;
}
let useLineDash = true;
if (length <= dashLength * 2) {
useLineDash = false;
} else if (length <= dashLength * 2 + spaceLength) {
const multiplier = length / (2 * dashLength + spaceLength);
dashLength *= multiplier;
spaceLength *= multiplier;
} else {
const numberOfDashes = Math.floor((length + spaceLength) / (dashLength + spaceLength));
const minSpace = (length - numberOfDashes * dashLength) / (numberOfDashes - 1);
const maxSpace = (length - (numberOfDashes + 1) * dashLength) / numberOfDashes;
spaceLength =
maxSpace <= 0 || Math.abs(spaceLength - minSpace) < Math.abs(spaceLength - maxSpace)
? minSpace
: maxSpace;
}
if (useLineDash) {
if (style === BORDER_STYLE.DOTTED) {
this.ctx.setLineDash([0, dashLength + spaceLength]);
} else {
this.ctx.setLineDash([dashLength, spaceLength]);
}
}
if (style === BORDER_STYLE.DOTTED) {
this.ctx.lineCap = 'round';
this.ctx.lineWidth = width;
} else {
this.ctx.lineWidth = width * 2 + 1.1;
}
this.ctx.strokeStyle = asString(color);
this.ctx.stroke();
this.ctx.setLineDash([]);
// dashed round edge gap
if (style === BORDER_STYLE.DASHED) {
if (isBezierCurve(boxPaths[0])) {
const path1 = boxPaths[3] as BezierCurve;
const path2 = boxPaths[0] as BezierCurve;
this.ctx.beginPath();
this.formatPath([new Vector(path1.end.x, path1.end.y), new Vector(path2.start.x, path2.start.y)]);
this.ctx.stroke();
}
if (isBezierCurve(boxPaths[1])) {
const path1 = boxPaths[1] as BezierCurve;
const path2 = boxPaths[2] as BezierCurve;
this.ctx.beginPath();
this.formatPath([new Vector(path1.end.x, path1.end.y), new Vector(path2.start.x, path2.start.y)]);
this.ctx.stroke();
}
}
this.ctx.restore();
}
async render(element: ElementContainer): Promise<HTMLCanvasElement> {
if (this.options.backgroundColor) {
this.ctx.fillStyle = asString(this.options.backgroundColor);

View File

@ -3,7 +3,8 @@ import {Path} from './path';
export const enum EffectType {
TRANSFORM = 0,
CLIP = 1
CLIP = 1,
OPACITY = 2
}
export const enum EffectTarget {
@ -17,33 +18,41 @@ export interface IElementEffect {
}
export class TransformEffect implements IElementEffect {
readonly type: EffectType;
readonly target: number;
readonly type: EffectType = EffectType.TRANSFORM;
readonly target: number = EffectTarget.BACKGROUND_BORDERS | EffectTarget.CONTENT;
readonly offsetX: number;
readonly offsetY: number;
readonly matrix: Matrix;
constructor(offsetX: number, offsetY: number, matrix: Matrix) {
this.type = EffectType.TRANSFORM;
this.offsetX = offsetX;
this.offsetY = offsetY;
this.matrix = matrix;
this.target = EffectTarget.BACKGROUND_BORDERS | EffectTarget.CONTENT;
}
}
export class ClipEffect implements IElementEffect {
readonly type: EffectType;
readonly type: EffectType = EffectType.CLIP;
readonly target: number;
readonly path: Path[];
constructor(path: Path[], target: EffectTarget) {
this.type = EffectType.CLIP;
this.target = target;
this.path = path;
}
}
export class OpacityEffect implements IElementEffect {
readonly type: EffectType = EffectType.OPACITY;
readonly target: number = EffectTarget.BACKGROUND_BORDERS | EffectTarget.CONTENT;
readonly opacity: number;
constructor(opacity: number) {
this.opacity = opacity;
}
}
export const isTransformEffect = (effect: IElementEffect): effect is TransformEffect =>
effect.type === EffectType.TRANSFORM;
export const isClipEffect = (effect: IElementEffect): effect is ClipEffect => effect.type === EffectType.CLIP;
export const isOpacityEffect = (effect: IElementEffect): effect is OpacityEffect => effect.type === EffectType.OPACITY;

View File

@ -1,7 +1,7 @@
import {ElementContainer, FLAGS} from '../dom/element-container';
import {contains} from '../core/bitwise';
import {BoundCurves, calculateBorderBoxPath, calculatePaddingBoxPath} from './bound-curves';
import {ClipEffect, EffectTarget, IElementEffect, TransformEffect} from './effects';
import {ClipEffect, EffectTarget, IElementEffect, OpacityEffect, TransformEffect} from './effects';
import {OVERFLOW} from '../css/property-descriptors/overflow';
import {equalPath} from './path';
import {DISPLAY} from '../css/property-descriptors/display';
@ -41,6 +41,10 @@ export class ElementPaint {
this.container = element;
this.effects = parentStack.slice(0);
this.curves = new BoundCurves(element);
if (element.styles.opacity < 1) {
this.effects.push(new OpacityEffect(element.styles.opacity));
}
if (element.styles.transform !== null) {
const offsetX = element.bounds.left + element.styles.transformOrigin[0].number;
const offsetY = element.bounds.top + element.styles.transformOrigin[1].number;

33
tests/karma.ts Normal file
View File

@ -0,0 +1,33 @@
import {screenshotApp, corsApp} from './server';
import {Server} from 'http';
import {config as KarmaConfig, Server as KarmaServer, TestResults} from 'karma';
import * as path from 'path';
const karmaTestRunner = (): Promise<void> =>
new Promise<void>((resolve, reject) => {
const karmaConfig = KarmaConfig.parseConfig(path.resolve(__dirname, '../karma.conf.js'), {});
const server = new KarmaServer(karmaConfig, (exitCode: number) => {
if (exitCode > 0) {
reject(`Karma has exited with ${exitCode}`);
} else {
resolve();
}
});
server.on('run_complete', (_browsers: any, _results: TestResults) => {
server.stop();
});
server.start();
});
const servers: Server[] = [];
servers.push(screenshotApp.listen(8000));
servers.push(corsApp.listen(8081));
karmaTestRunner()
.then(() => {
servers.forEach(server => server.close());
})
.catch(e => {
console.error(e);
process.exit(1);
});

View File

@ -63,6 +63,13 @@
border-radius: 200px;
}
.box7 {
border-width: 10px 10px 10px 1px;
border-left-color: transparent;
border-top-color: red;
border-right-color: green;
}
.gauge{
display: inline-block;
width: 100px;
@ -91,6 +98,7 @@
<div class="box box4">&nbsp;</div>
<div class="box box5">&nbsp;</div>
<div class="box box6">&nbsp;</div>
<div class="box box7">&nbsp;</div>
<div class="gauge gauge1"></div>
<div class="gauge gauge2"></div>
<div class="gauge gauge3"></div>

View File

@ -128,5 +128,6 @@
</script>
</div>
<div class="hidden">Hidden<div style="opacity: 0.5">With opacity</div></div>
</body>
</html>

View File

@ -1,24 +0,0 @@
const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const serveIndex = require('serve-index');
const proxy = require('html2canvas-proxy');
const PORT = 8080;
const CORS_PORT = 8081;
const app = express();
app.use('/', serveIndex(path.resolve(__dirname, '../'), {icons: true}));
app.use('/', express.static(path.resolve(__dirname, '../')));
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
const corsApp = express();
corsApp.use('/proxy', proxy());
corsApp.use('/cors', cors(), express.static(path.resolve(__dirname, '../')));
corsApp.use('/', express.static(path.resolve(__dirname, '.')));
corsApp.listen(CORS_PORT, () => {
console.log(`CORS server running on port ${CORS_PORT}`);
});

93
tests/server.ts Normal file
View File

@ -0,0 +1,93 @@
import * as express from 'express';
const cors = require('cors');
const path = require('path');
const serveIndex = require('serve-index');
const proxy = require('html2canvas-proxy');
import yargs from 'yargs';
import {ScreenshotRequest} from './types';
const fs = require('fs');
const bodyParser = require('body-parser');
const filenamifyUrl = require('filenamify-url');
const mkdirp = require('mkdirp');
export const app = express();
app.use('/', serveIndex(path.resolve(__dirname, '../'), {icons: true}));
app.use('/', express.static(path.resolve(__dirname, '../')));
export const corsApp = express();
corsApp.use('/proxy', proxy());
corsApp.use('/cors', cors(), express.static(path.resolve(__dirname, '../')));
corsApp.use('/', express.static(path.resolve(__dirname, '.')));
export const screenshotApp = express();
screenshotApp.use(cors());
screenshotApp.use((req: express.Request, _res: express.Response, next: express.NextFunction) => {
// IE9 doesn't set headers for cross-domain ajax requests
if (typeof req.headers['content-type'] === 'undefined') {
req.headers['content-type'] = 'application/json';
}
next();
});
screenshotApp.use(
bodyParser.json({
limit: '15mb',
type: '*/*'
})
);
const prefix = 'data:image/png;base64,';
const screenshotFolder = '../tmp/reftests';
const metadataFolder = '../tmp/reftests/metadata';
mkdirp.sync(path.resolve(__dirname, screenshotFolder));
mkdirp.sync(path.resolve(__dirname, metadataFolder));
const writeScreenshot = (buffer: Buffer, body: ScreenshotRequest) => {
const filename = `${filenamifyUrl(body.test.replace(/^\/tests\/reftests\//, '').replace(/\.html$/, ''), {
replacement: '-'
})}!${[process.env.TARGET_BROWSER, body.platform.name, body.platform.version].join('-')}`;
fs.writeFileSync(path.resolve(__dirname, screenshotFolder, `${filename}.png`), buffer);
return filename;
};
screenshotApp.post('/screenshot', (req: express.Request<{}, void, ScreenshotRequest>, res: express.Response) => {
if (!req.body || !req.body.screenshot) {
return res.sendStatus(400);
}
const buffer = Buffer.from(req.body.screenshot.substring(prefix.length), 'base64');
const filename = writeScreenshot(buffer, req.body);
fs.writeFileSync(
path.resolve(__dirname, metadataFolder, `${filename}.json`),
JSON.stringify({
windowWidth: req.body.windowWidth,
windowHeight: req.body.windowHeight,
platform: req.body.platform,
devicePixelRatio: req.body.devicePixelRatio,
test: req.body.test,
id: process.env.TARGET_BROWSER,
screenshot: filename
})
);
return res.sendStatus(200);
});
screenshotApp.use((error: Error, _req: express.Request, _res: express.Response, next: express.NextFunction) => {
console.error(error);
next();
});
const args = yargs(process.argv.slice(2)).number(['port', 'cors']).argv;
if (args.port) {
app.listen(args.port, () => {
console.log(`Server running on port ${args.port}`);
});
}
if (args.cors) {
corsApp.listen(args.cors, () => {
console.log(`CORS server running on port ${args.cors}`);
});
}

View File

@ -3,7 +3,10 @@ import {testList, ignoredTests} from '../build/reftests';
import {default as platform} from 'platform';
// @ts-ignore
import Promise from 'es6-promise';
import {ScreenshotRequest} from './types';
// @ts-ignore
window.Promise = Promise;
const testRunnerUrl = location.href;
const hasHistoryApi = typeof window.history !== 'undefined' && typeof window.history.replaceState !== 'undefined';
@ -21,20 +24,20 @@ const uploadResults = (canvas: HTMLCanvasElement, url: string) => {
};
xhr.onerror = reject;
const request: ScreenshotRequest = {
screenshot: canvas.toDataURL(),
test: url,
platform: {
name: platform.name,
version: platform.version
},
devicePixelRatio: window.devicePixelRatio || 1,
windowWidth: window.innerWidth,
windowHeight: window.innerHeight
};
xhr.open('POST', 'http://localhost:8000/screenshot', true);
xhr.send(
JSON.stringify({
screenshot: canvas.toDataURL(),
test: url,
platform: {
name: platform.name,
version: platform.version
},
devicePixelRatio: window.devicePixelRatio || 1,
windowWidth: window.innerWidth,
windowHeight: window.innerHeight
})
);
xhr.send(JSON.stringify(request));
});
};
@ -76,40 +79,38 @@ testList
}
document.body.removeChild(testContainer);
});
it('Should render untainted canvas', () => {
it('Should render untainted canvas', async () => {
const contentWindow = testContainer.contentWindow;
if (!contentWindow) {
throw new Error('Window not found for iframe');
}
return (
contentWindow
const canvas: HTMLCanvasElement = await contentWindow
// @ts-ignore
.html2canvas(contentWindow.forceElement || contentWindow.document.documentElement, {
removeContainer: true,
backgroundColor: '#ffffff',
proxy: 'http://localhost:8081/proxy',
// @ts-ignore
.html2canvas(contentWindow.forceElement || contentWindow.document.documentElement, {
removeContainer: true,
backgroundColor: '#ffffff',
proxy: 'http://localhost:8081/proxy',
// @ts-ignore
...(contentWindow.h2cOptions || {})
})
.then((canvas: HTMLCanvasElement) => {
try {
(canvas.getContext('2d') as CanvasRenderingContext2D).getImageData(
0,
0,
canvas.width,
canvas.height
);
} catch (e) {
return Promise.reject('Canvas is tainted');
}
...(contentWindow.h2cOptions || {})
});
// @ts-ignore
if (window.__karma__) {
return uploadResults(canvas, url);
}
})
);
try {
(canvas.getContext('2d') as CanvasRenderingContext2D).getImageData(
0,
0,
canvas.width,
canvas.height
);
} catch (e) {
throw new Error('Canvas is tainted');
}
// @ts-ignore
if (window.__karma__) {
return uploadResults(canvas, url);
}
});
});
});

13
tests/types.ts Normal file
View File

@ -0,0 +1,13 @@
export interface PlatformDetails {
name: string;
version: string;
}
export interface ScreenshotRequest {
screenshot: string;
test: string;
platform: PlatformDetails;
devicePixelRatio: number;
windowWidth: number;
windowHeight: number;
}

37692
www/package-lock.json generated

File diff suppressed because it is too large Load Diff