canvas-renderer.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. return new (P || (P = Promise))(function (resolve, reject) {
  4. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  5. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  6. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  7. step((generator = generator.apply(thisArg, _arguments || [])).next());
  8. });
  9. };
  10. var __generator = (this && this.__generator) || function (thisArg, body) {
  11. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  12. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  13. function verb(n) { return function (v) { return step([n, v]); }; }
  14. function step(op) {
  15. if (f) throw new TypeError("Generator is already executing.");
  16. while (_) try {
  17. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  18. if (y = 0, t) op = [op[0] & 2, t.value];
  19. switch (op[0]) {
  20. case 0: case 1: t = op; break;
  21. case 4: _.label++; return { value: op[1], done: false };
  22. case 5: _.label++; y = op[1]; op = [0]; continue;
  23. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  24. default:
  25. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  26. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  27. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  28. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  29. if (t[2]) _.ops.pop();
  30. _.trys.pop(); continue;
  31. }
  32. op = body.call(thisArg, _);
  33. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  34. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  35. }
  36. };
  37. Object.defineProperty(exports, "__esModule", { value: true });
  38. var stacking_context_1 = require("../stacking-context");
  39. var color_1 = require("../../css/types/color");
  40. var logger_1 = require("../../core/logger");
  41. var border_style_1 = require("../../css/property-descriptors/border-style");
  42. var path_1 = require("../path");
  43. var background_clip_1 = require("../../css/property-descriptors/background-clip");
  44. var bound_curves_1 = require("../bound-curves");
  45. var bezier_curve_1 = require("../bezier-curve");
  46. var vector_1 = require("../vector");
  47. var image_1 = require("../../css/types/image");
  48. var border_1 = require("../border");
  49. var background_1 = require("../background");
  50. var parser_1 = require("../../css/syntax/parser");
  51. var text_1 = require("../../css/layout/text");
  52. var css_line_break_1 = require("css-line-break");
  53. var image_element_container_1 = require("../../dom/replaced-elements/image-element-container");
  54. var box_sizing_1 = require("../box-sizing");
  55. var canvas_element_container_1 = require("../../dom/replaced-elements/canvas-element-container");
  56. var svg_element_container_1 = require("../../dom/replaced-elements/svg-element-container");
  57. var effects_1 = require("../effects");
  58. var bitwise_1 = require("../../core/bitwise");
  59. var gradient_1 = require("../../css/types/functions/gradient");
  60. var length_percentage_1 = require("../../css/types/length-percentage");
  61. var font_metrics_1 = require("../font-metrics");
  62. var bounds_1 = require("../../css/layout/bounds");
  63. var list_style_type_1 = require("../../css/property-descriptors/list-style-type");
  64. var line_height_1 = require("../../css/property-descriptors/line-height");
  65. var input_element_container_1 = require("../../dom/replaced-elements/input-element-container");
  66. var text_align_1 = require("../../css/property-descriptors/text-align");
  67. var textarea_element_container_1 = require("../../dom/elements/textarea-element-container");
  68. var select_element_container_1 = require("../../dom/elements/select-element-container");
  69. var iframe_element_container_1 = require("../../dom/replaced-elements/iframe-element-container");
  70. var MASK_OFFSET = 10000;
  71. var CanvasRenderer = /** @class */ (function () {
  72. function CanvasRenderer(options) {
  73. this._activeEffects = [];
  74. this.canvas = options.canvas ? options.canvas : document.createElement('canvas');
  75. this.ctx = this.canvas.getContext('2d');
  76. this.options = options;
  77. if (!options.canvas) {
  78. this.canvas.width = Math.floor(options.width * options.scale);
  79. this.canvas.height = Math.floor(options.height * options.scale);
  80. this.canvas.style.width = options.width + "px";
  81. this.canvas.style.height = options.height + "px";
  82. }
  83. this.fontMetrics = new font_metrics_1.FontMetrics(document);
  84. this.ctx.scale(this.options.scale, this.options.scale);
  85. this.ctx.translate(-options.x + options.scrollX, -options.y + options.scrollY);
  86. this.ctx.textBaseline = 'bottom';
  87. this._activeEffects = [];
  88. logger_1.Logger.getInstance(options.id).debug("Canvas renderer initialized (" + options.width + "x" + options.height + " at " + options.x + "," + options.y + ") with scale " + options.scale);
  89. }
  90. CanvasRenderer.prototype.applyEffects = function (effects, target) {
  91. var _this = this;
  92. while (this._activeEffects.length) {
  93. this.popEffect();
  94. }
  95. effects.filter(function (effect) { return bitwise_1.contains(effect.target, target); }).forEach(function (effect) { return _this.applyEffect(effect); });
  96. };
  97. CanvasRenderer.prototype.applyEffect = function (effect) {
  98. this.ctx.save();
  99. if (effects_1.isTransformEffect(effect)) {
  100. this.ctx.translate(effect.offsetX, effect.offsetY);
  101. this.ctx.transform(effect.matrix[0], effect.matrix[1], effect.matrix[2], effect.matrix[3], effect.matrix[4], effect.matrix[5]);
  102. this.ctx.translate(-effect.offsetX, -effect.offsetY);
  103. }
  104. if (effects_1.isClipEffect(effect)) {
  105. this.path(effect.path);
  106. this.ctx.clip();
  107. }
  108. this._activeEffects.push(effect);
  109. };
  110. CanvasRenderer.prototype.popEffect = function () {
  111. this._activeEffects.pop();
  112. this.ctx.restore();
  113. };
  114. CanvasRenderer.prototype.renderStack = function (stack) {
  115. return __awaiter(this, void 0, void 0, function () {
  116. var styles;
  117. return __generator(this, function (_a) {
  118. switch (_a.label) {
  119. case 0:
  120. styles = stack.element.container.styles;
  121. if (!styles.isVisible()) return [3 /*break*/, 2];
  122. this.ctx.globalAlpha = styles.opacity;
  123. return [4 /*yield*/, this.renderStackContent(stack)];
  124. case 1:
  125. _a.sent();
  126. _a.label = 2;
  127. case 2: return [2 /*return*/];
  128. }
  129. });
  130. });
  131. };
  132. CanvasRenderer.prototype.renderNode = function (paint) {
  133. return __awaiter(this, void 0, void 0, function () {
  134. return __generator(this, function (_a) {
  135. switch (_a.label) {
  136. case 0:
  137. if (!paint.container.styles.isVisible()) return [3 /*break*/, 3];
  138. return [4 /*yield*/, this.renderNodeBackgroundAndBorders(paint)];
  139. case 1:
  140. _a.sent();
  141. return [4 /*yield*/, this.renderNodeContent(paint)];
  142. case 2:
  143. _a.sent();
  144. _a.label = 3;
  145. case 3: return [2 /*return*/];
  146. }
  147. });
  148. });
  149. };
  150. CanvasRenderer.prototype.renderTextWithLetterSpacing = function (text, letterSpacing) {
  151. var _this = this;
  152. if (letterSpacing === 0) {
  153. this.ctx.fillText(text.text, text.bounds.left, text.bounds.top + text.bounds.height);
  154. }
  155. else {
  156. var letters = css_line_break_1.toCodePoints(text.text).map(function (i) { return css_line_break_1.fromCodePoint(i); });
  157. letters.reduce(function (left, letter) {
  158. _this.ctx.fillText(letter, left, text.bounds.top + text.bounds.height);
  159. return left + _this.ctx.measureText(letter).width;
  160. }, text.bounds.left);
  161. }
  162. };
  163. CanvasRenderer.prototype.createFontStyle = function (styles) {
  164. var fontVariant = styles.fontVariant
  165. .filter(function (variant) { return variant === 'normal' || variant === 'small-caps'; })
  166. .join('');
  167. var fontFamily = styles.fontFamily.join(', ');
  168. var fontSize = parser_1.isDimensionToken(styles.fontSize)
  169. ? "" + styles.fontSize.number + styles.fontSize.unit
  170. : styles.fontSize.number + "px";
  171. return [
  172. [styles.fontStyle, fontVariant, styles.fontWeight, fontSize, fontFamily].join(' '),
  173. fontFamily,
  174. fontSize
  175. ];
  176. };
  177. CanvasRenderer.prototype.renderTextNode = function (text, styles) {
  178. return __awaiter(this, void 0, void 0, function () {
  179. var _a, font, fontFamily, fontSize;
  180. var _this = this;
  181. return __generator(this, function (_b) {
  182. _a = this.createFontStyle(styles), font = _a[0], fontFamily = _a[1], fontSize = _a[2];
  183. this.ctx.font = font;
  184. text.textBounds.forEach(function (text) {
  185. _this.ctx.fillStyle = color_1.asString(styles.color);
  186. _this.renderTextWithLetterSpacing(text, styles.letterSpacing);
  187. var textShadows = styles.textShadow;
  188. if (textShadows.length && text.text.trim().length) {
  189. textShadows
  190. .slice(0)
  191. .reverse()
  192. .forEach(function (textShadow) {
  193. _this.ctx.shadowColor = color_1.asString(textShadow.color);
  194. _this.ctx.shadowOffsetX = textShadow.offsetX.number * _this.options.scale;
  195. _this.ctx.shadowOffsetY = textShadow.offsetY.number * _this.options.scale;
  196. _this.ctx.shadowBlur = textShadow.blur.number;
  197. _this.ctx.fillText(text.text, text.bounds.left, text.bounds.top + text.bounds.height);
  198. });
  199. _this.ctx.shadowColor = '';
  200. _this.ctx.shadowOffsetX = 0;
  201. _this.ctx.shadowOffsetY = 0;
  202. _this.ctx.shadowBlur = 0;
  203. }
  204. if (styles.textDecorationLine.length) {
  205. _this.ctx.fillStyle = color_1.asString(styles.textDecorationColor || styles.color);
  206. styles.textDecorationLine.forEach(function (textDecorationLine) {
  207. switch (textDecorationLine) {
  208. case 1 /* UNDERLINE */:
  209. // Draws a line at the baseline of the font
  210. // TODO As some browsers display the line as more than 1px if the font-size is big,
  211. // need to take that into account both in position and size
  212. var baseline = _this.fontMetrics.getMetrics(fontFamily, fontSize).baseline;
  213. _this.ctx.fillRect(text.bounds.left, Math.round(text.bounds.top + baseline), text.bounds.width, 1);
  214. break;
  215. case 2 /* OVERLINE */:
  216. _this.ctx.fillRect(text.bounds.left, Math.round(text.bounds.top), text.bounds.width, 1);
  217. break;
  218. case 3 /* LINE_THROUGH */:
  219. // TODO try and find exact position for line-through
  220. var middle = _this.fontMetrics.getMetrics(fontFamily, fontSize).middle;
  221. _this.ctx.fillRect(text.bounds.left, Math.ceil(text.bounds.top + middle), text.bounds.width, 1);
  222. break;
  223. }
  224. });
  225. }
  226. });
  227. return [2 /*return*/];
  228. });
  229. });
  230. };
  231. CanvasRenderer.prototype.renderReplacedElement = function (container, curves, image) {
  232. if (image && container.intrinsicWidth > 0 && container.intrinsicHeight > 0) {
  233. var box = box_sizing_1.contentBox(container);
  234. var path = bound_curves_1.calculatePaddingBoxPath(curves);
  235. this.path(path);
  236. this.ctx.save();
  237. this.ctx.clip();
  238. this.ctx.drawImage(image, 0, 0, container.intrinsicWidth, container.intrinsicHeight, box.left, box.top, box.width, box.height);
  239. this.ctx.restore();
  240. }
  241. };
  242. CanvasRenderer.prototype.renderNodeContent = function (paint) {
  243. return __awaiter(this, void 0, void 0, function () {
  244. var container, curves, styles, _i, _a, child, image, e_1, image, e_2, iframeRenderer, canvas, size, bounds, x, textBounds, img, image, url, e_3, bounds;
  245. return __generator(this, function (_b) {
  246. switch (_b.label) {
  247. case 0:
  248. this.applyEffects(paint.effects, 4 /* CONTENT */);
  249. container = paint.container;
  250. curves = paint.curves;
  251. styles = container.styles;
  252. _i = 0, _a = container.textNodes;
  253. _b.label = 1;
  254. case 1:
  255. if (!(_i < _a.length)) return [3 /*break*/, 4];
  256. child = _a[_i];
  257. return [4 /*yield*/, this.renderTextNode(child, styles)];
  258. case 2:
  259. _b.sent();
  260. _b.label = 3;
  261. case 3:
  262. _i++;
  263. return [3 /*break*/, 1];
  264. case 4:
  265. if (!(container instanceof image_element_container_1.ImageElementContainer)) return [3 /*break*/, 8];
  266. _b.label = 5;
  267. case 5:
  268. _b.trys.push([5, 7, , 8]);
  269. return [4 /*yield*/, this.options.cache.match(container.src)];
  270. case 6:
  271. image = _b.sent();
  272. this.renderReplacedElement(container, curves, image);
  273. return [3 /*break*/, 8];
  274. case 7:
  275. e_1 = _b.sent();
  276. logger_1.Logger.getInstance(this.options.id).error("Error loading image " + container.src);
  277. return [3 /*break*/, 8];
  278. case 8:
  279. if (container instanceof canvas_element_container_1.CanvasElementContainer) {
  280. this.renderReplacedElement(container, curves, container.canvas);
  281. }
  282. if (!(container instanceof svg_element_container_1.SVGElementContainer)) return [3 /*break*/, 12];
  283. _b.label = 9;
  284. case 9:
  285. _b.trys.push([9, 11, , 12]);
  286. return [4 /*yield*/, this.options.cache.match(container.svg)];
  287. case 10:
  288. image = _b.sent();
  289. this.renderReplacedElement(container, curves, image);
  290. return [3 /*break*/, 12];
  291. case 11:
  292. e_2 = _b.sent();
  293. logger_1.Logger.getInstance(this.options.id).error("Error loading svg " + container.svg.substring(0, 255));
  294. return [3 /*break*/, 12];
  295. case 12:
  296. if (!(container instanceof iframe_element_container_1.IFrameElementContainer && container.tree)) return [3 /*break*/, 14];
  297. iframeRenderer = new CanvasRenderer({
  298. id: this.options.id,
  299. scale: this.options.scale,
  300. backgroundColor: container.backgroundColor,
  301. x: 0,
  302. y: 0,
  303. scrollX: 0,
  304. scrollY: 0,
  305. width: container.width,
  306. height: container.height,
  307. cache: this.options.cache,
  308. windowWidth: container.width,
  309. windowHeight: container.height
  310. });
  311. return [4 /*yield*/, iframeRenderer.render(container.tree)];
  312. case 13:
  313. canvas = _b.sent();
  314. if (container.width && container.height) {
  315. this.ctx.drawImage(canvas, 0, 0, container.width, container.height, container.bounds.left, container.bounds.top, container.bounds.width, container.bounds.height);
  316. }
  317. _b.label = 14;
  318. case 14:
  319. if (container instanceof input_element_container_1.InputElementContainer) {
  320. size = Math.min(container.bounds.width, container.bounds.height);
  321. if (container.type === input_element_container_1.CHECKBOX) {
  322. if (container.checked) {
  323. this.ctx.save();
  324. this.path([
  325. new vector_1.Vector(container.bounds.left + size * 0.39363, container.bounds.top + size * 0.79),
  326. new vector_1.Vector(container.bounds.left + size * 0.16, container.bounds.top + size * 0.5549),
  327. new vector_1.Vector(container.bounds.left + size * 0.27347, container.bounds.top + size * 0.44071),
  328. new vector_1.Vector(container.bounds.left + size * 0.39694, container.bounds.top + size * 0.5649),
  329. new vector_1.Vector(container.bounds.left + size * 0.72983, container.bounds.top + size * 0.23),
  330. new vector_1.Vector(container.bounds.left + size * 0.84, container.bounds.top + size * 0.34085),
  331. new vector_1.Vector(container.bounds.left + size * 0.39363, container.bounds.top + size * 0.79)
  332. ]);
  333. this.ctx.fillStyle = color_1.asString(input_element_container_1.INPUT_COLOR);
  334. this.ctx.fill();
  335. this.ctx.restore();
  336. }
  337. }
  338. else if (container.type === input_element_container_1.RADIO) {
  339. if (container.checked) {
  340. this.ctx.save();
  341. this.ctx.beginPath();
  342. this.ctx.arc(container.bounds.left + size / 2, container.bounds.top + size / 2, size / 4, 0, Math.PI * 2, true);
  343. this.ctx.fillStyle = color_1.asString(input_element_container_1.INPUT_COLOR);
  344. this.ctx.fill();
  345. this.ctx.restore();
  346. }
  347. }
  348. }
  349. if (isTextInputElement(container) && container.value.length) {
  350. this.ctx.font = this.createFontStyle(styles)[0];
  351. this.ctx.fillStyle = color_1.asString(styles.color);
  352. this.ctx.textBaseline = 'middle';
  353. this.ctx.textAlign = canvasTextAlign(container.styles.textAlign);
  354. bounds = box_sizing_1.contentBox(container);
  355. x = 0;
  356. switch (container.styles.textAlign) {
  357. case text_align_1.TEXT_ALIGN.CENTER:
  358. x += bounds.width / 2;
  359. break;
  360. case text_align_1.TEXT_ALIGN.RIGHT:
  361. x += bounds.width;
  362. break;
  363. }
  364. textBounds = bounds.add(x, 0, 0, -bounds.height / 2 + 1);
  365. this.ctx.save();
  366. this.path([
  367. new vector_1.Vector(bounds.left, bounds.top),
  368. new vector_1.Vector(bounds.left + bounds.width, bounds.top),
  369. new vector_1.Vector(bounds.left + bounds.width, bounds.top + bounds.height),
  370. new vector_1.Vector(bounds.left, bounds.top + bounds.height)
  371. ]);
  372. this.ctx.clip();
  373. this.renderTextWithLetterSpacing(new text_1.TextBounds(container.value, textBounds), styles.letterSpacing);
  374. this.ctx.restore();
  375. this.ctx.textBaseline = 'bottom';
  376. this.ctx.textAlign = 'left';
  377. }
  378. if (!bitwise_1.contains(container.styles.display, 2048 /* LIST_ITEM */)) return [3 /*break*/, 20];
  379. if (!(container.styles.listStyleImage !== null)) return [3 /*break*/, 19];
  380. img = container.styles.listStyleImage;
  381. if (!(img.type === image_1.CSSImageType.URL)) return [3 /*break*/, 18];
  382. image = void 0;
  383. url = img.url;
  384. _b.label = 15;
  385. case 15:
  386. _b.trys.push([15, 17, , 18]);
  387. return [4 /*yield*/, this.options.cache.match(url)];
  388. case 16:
  389. image = _b.sent();
  390. this.ctx.drawImage(image, container.bounds.left - (image.width + 10), container.bounds.top);
  391. return [3 /*break*/, 18];
  392. case 17:
  393. e_3 = _b.sent();
  394. logger_1.Logger.getInstance(this.options.id).error("Error loading list-style-image " + url);
  395. return [3 /*break*/, 18];
  396. case 18: return [3 /*break*/, 20];
  397. case 19:
  398. if (paint.listValue && container.styles.listStyleType !== list_style_type_1.LIST_STYLE_TYPE.NONE) {
  399. this.ctx.font = this.createFontStyle(styles)[0];
  400. this.ctx.fillStyle = color_1.asString(styles.color);
  401. this.ctx.textBaseline = 'middle';
  402. this.ctx.textAlign = 'right';
  403. bounds = new bounds_1.Bounds(container.bounds.left, container.bounds.top + length_percentage_1.getAbsoluteValue(container.styles.paddingTop, container.bounds.width), container.bounds.width, line_height_1.computeLineHeight(styles.lineHeight, styles.fontSize.number) / 2 + 1);
  404. this.renderTextWithLetterSpacing(new text_1.TextBounds(paint.listValue, bounds), styles.letterSpacing);
  405. this.ctx.textBaseline = 'bottom';
  406. this.ctx.textAlign = 'left';
  407. }
  408. _b.label = 20;
  409. case 20: return [2 /*return*/];
  410. }
  411. });
  412. });
  413. };
  414. CanvasRenderer.prototype.renderStackContent = function (stack) {
  415. return __awaiter(this, void 0, void 0, function () {
  416. var _i, _a, child, _b, _c, child, _d, _e, child, _f, _g, child, _h, _j, child, _k, _l, child, _m, _o, child;
  417. return __generator(this, function (_p) {
  418. switch (_p.label) {
  419. case 0:
  420. // https://www.w3.org/TR/css-position-3/#painting-order
  421. // 1. the background and borders of the element forming the stacking context.
  422. return [4 /*yield*/, this.renderNodeBackgroundAndBorders(stack.element)];
  423. case 1:
  424. // https://www.w3.org/TR/css-position-3/#painting-order
  425. // 1. the background and borders of the element forming the stacking context.
  426. _p.sent();
  427. _i = 0, _a = stack.negativeZIndex;
  428. _p.label = 2;
  429. case 2:
  430. if (!(_i < _a.length)) return [3 /*break*/, 5];
  431. child = _a[_i];
  432. return [4 /*yield*/, this.renderStack(child)];
  433. case 3:
  434. _p.sent();
  435. _p.label = 4;
  436. case 4:
  437. _i++;
  438. return [3 /*break*/, 2];
  439. case 5:
  440. // 3. For all its in-flow, non-positioned, block-level descendants in tree order:
  441. return [4 /*yield*/, this.renderNodeContent(stack.element)];
  442. case 6:
  443. // 3. For all its in-flow, non-positioned, block-level descendants in tree order:
  444. _p.sent();
  445. _b = 0, _c = stack.nonInlineLevel;
  446. _p.label = 7;
  447. case 7:
  448. if (!(_b < _c.length)) return [3 /*break*/, 10];
  449. child = _c[_b];
  450. return [4 /*yield*/, this.renderNode(child)];
  451. case 8:
  452. _p.sent();
  453. _p.label = 9;
  454. case 9:
  455. _b++;
  456. return [3 /*break*/, 7];
  457. case 10:
  458. _d = 0, _e = stack.nonPositionedFloats;
  459. _p.label = 11;
  460. case 11:
  461. if (!(_d < _e.length)) return [3 /*break*/, 14];
  462. child = _e[_d];
  463. return [4 /*yield*/, this.renderStack(child)];
  464. case 12:
  465. _p.sent();
  466. _p.label = 13;
  467. case 13:
  468. _d++;
  469. return [3 /*break*/, 11];
  470. case 14:
  471. _f = 0, _g = stack.nonPositionedInlineLevel;
  472. _p.label = 15;
  473. case 15:
  474. if (!(_f < _g.length)) return [3 /*break*/, 18];
  475. child = _g[_f];
  476. return [4 /*yield*/, this.renderStack(child)];
  477. case 16:
  478. _p.sent();
  479. _p.label = 17;
  480. case 17:
  481. _f++;
  482. return [3 /*break*/, 15];
  483. case 18:
  484. _h = 0, _j = stack.inlineLevel;
  485. _p.label = 19;
  486. case 19:
  487. if (!(_h < _j.length)) return [3 /*break*/, 22];
  488. child = _j[_h];
  489. return [4 /*yield*/, this.renderNode(child)];
  490. case 20:
  491. _p.sent();
  492. _p.label = 21;
  493. case 21:
  494. _h++;
  495. return [3 /*break*/, 19];
  496. case 22:
  497. _k = 0, _l = stack.zeroOrAutoZIndexOrTransformedOrOpacity;
  498. _p.label = 23;
  499. case 23:
  500. if (!(_k < _l.length)) return [3 /*break*/, 26];
  501. child = _l[_k];
  502. return [4 /*yield*/, this.renderStack(child)];
  503. case 24:
  504. _p.sent();
  505. _p.label = 25;
  506. case 25:
  507. _k++;
  508. return [3 /*break*/, 23];
  509. case 26:
  510. _m = 0, _o = stack.positiveZIndex;
  511. _p.label = 27;
  512. case 27:
  513. if (!(_m < _o.length)) return [3 /*break*/, 30];
  514. child = _o[_m];
  515. return [4 /*yield*/, this.renderStack(child)];
  516. case 28:
  517. _p.sent();
  518. _p.label = 29;
  519. case 29:
  520. _m++;
  521. return [3 /*break*/, 27];
  522. case 30: return [2 /*return*/];
  523. }
  524. });
  525. });
  526. };
  527. CanvasRenderer.prototype.mask = function (paths) {
  528. this.ctx.beginPath();
  529. this.ctx.moveTo(0, 0);
  530. this.ctx.lineTo(this.canvas.width, 0);
  531. this.ctx.lineTo(this.canvas.width, this.canvas.height);
  532. this.ctx.lineTo(0, this.canvas.height);
  533. this.ctx.lineTo(0, 0);
  534. this.formatPath(paths.slice(0).reverse());
  535. this.ctx.closePath();
  536. };
  537. CanvasRenderer.prototype.path = function (paths) {
  538. this.ctx.beginPath();
  539. this.formatPath(paths);
  540. this.ctx.closePath();
  541. };
  542. CanvasRenderer.prototype.formatPath = function (paths) {
  543. var _this = this;
  544. paths.forEach(function (point, index) {
  545. var start = bezier_curve_1.isBezierCurve(point) ? point.start : point;
  546. if (index === 0) {
  547. _this.ctx.moveTo(start.x, start.y);
  548. }
  549. else {
  550. _this.ctx.lineTo(start.x, start.y);
  551. }
  552. if (bezier_curve_1.isBezierCurve(point)) {
  553. _this.ctx.bezierCurveTo(point.startControl.x, point.startControl.y, point.endControl.x, point.endControl.y, point.end.x, point.end.y);
  554. }
  555. });
  556. };
  557. CanvasRenderer.prototype.renderRepeat = function (path, pattern, offsetX, offsetY) {
  558. this.path(path);
  559. this.ctx.fillStyle = pattern;
  560. this.ctx.translate(offsetX, offsetY);
  561. this.ctx.fill();
  562. this.ctx.translate(-offsetX, -offsetY);
  563. };
  564. CanvasRenderer.prototype.resizeImage = function (image, width, height) {
  565. if (image.width === width && image.height === height) {
  566. return image;
  567. }
  568. var canvas = this.canvas.ownerDocument.createElement('canvas');
  569. canvas.width = width;
  570. canvas.height = height;
  571. var ctx = canvas.getContext('2d');
  572. ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, width, height);
  573. return canvas;
  574. };
  575. CanvasRenderer.prototype.renderBackgroundImage = function (container) {
  576. return __awaiter(this, void 0, void 0, function () {
  577. var index, _loop_1, this_1, _i, _a, backgroundImage;
  578. return __generator(this, function (_b) {
  579. switch (_b.label) {
  580. case 0:
  581. index = container.styles.backgroundImage.length - 1;
  582. _loop_1 = function (backgroundImage) {
  583. var image, url, e_4, _a, path, x, y, width, height, pattern, _b, path, x, y, width, height, _c, lineLength, x0, x1, y0, y1, canvas, ctx, gradient_2, pattern, _d, path, left, top_1, width, height, position, x, y, _e, rx, ry, radialGradient_1, midX, midY, f, invF;
  584. return __generator(this, function (_f) {
  585. switch (_f.label) {
  586. case 0:
  587. if (!(backgroundImage.type === image_1.CSSImageType.URL)) return [3 /*break*/, 5];
  588. image = void 0;
  589. url = backgroundImage.url;
  590. _f.label = 1;
  591. case 1:
  592. _f.trys.push([1, 3, , 4]);
  593. return [4 /*yield*/, this_1.options.cache.match(url)];
  594. case 2:
  595. image = _f.sent();
  596. return [3 /*break*/, 4];
  597. case 3:
  598. e_4 = _f.sent();
  599. logger_1.Logger.getInstance(this_1.options.id).error("Error loading background-image " + url);
  600. return [3 /*break*/, 4];
  601. case 4:
  602. if (image) {
  603. _a = background_1.calculateBackgroundRendering(container, index, [
  604. image.width,
  605. image.height,
  606. image.width / image.height
  607. ]), path = _a[0], x = _a[1], y = _a[2], width = _a[3], height = _a[4];
  608. pattern = this_1.ctx.createPattern(this_1.resizeImage(image, width, height), 'repeat');
  609. this_1.renderRepeat(path, pattern, x, y);
  610. }
  611. return [3 /*break*/, 6];
  612. case 5:
  613. if (image_1.isLinearGradient(backgroundImage)) {
  614. _b = background_1.calculateBackgroundRendering(container, index, [null, null, null]), path = _b[0], x = _b[1], y = _b[2], width = _b[3], height = _b[4];
  615. _c = gradient_1.calculateGradientDirection(backgroundImage.angle, width, height), lineLength = _c[0], x0 = _c[1], x1 = _c[2], y0 = _c[3], y1 = _c[4];
  616. canvas = document.createElement('canvas');
  617. canvas.width = width;
  618. canvas.height = height;
  619. ctx = canvas.getContext('2d');
  620. gradient_2 = ctx.createLinearGradient(x0, y0, x1, y1);
  621. gradient_1.processColorStops(backgroundImage.stops, lineLength).forEach(function (colorStop) {
  622. return gradient_2.addColorStop(colorStop.stop, color_1.asString(colorStop.color));
  623. });
  624. ctx.fillStyle = gradient_2;
  625. ctx.fillRect(0, 0, width, height);
  626. if (width > 0 && height > 0) {
  627. pattern = this_1.ctx.createPattern(canvas, 'repeat');
  628. this_1.renderRepeat(path, pattern, x, y);
  629. }
  630. }
  631. else if (image_1.isRadialGradient(backgroundImage)) {
  632. _d = background_1.calculateBackgroundRendering(container, index, [
  633. null,
  634. null,
  635. null
  636. ]), path = _d[0], left = _d[1], top_1 = _d[2], width = _d[3], height = _d[4];
  637. position = backgroundImage.position.length === 0 ? [length_percentage_1.FIFTY_PERCENT] : backgroundImage.position;
  638. x = length_percentage_1.getAbsoluteValue(position[0], width);
  639. y = length_percentage_1.getAbsoluteValue(position[position.length - 1], height);
  640. _e = gradient_1.calculateRadius(backgroundImage, x, y, width, height), rx = _e[0], ry = _e[1];
  641. if (rx > 0 && rx > 0) {
  642. radialGradient_1 = this_1.ctx.createRadialGradient(left + x, top_1 + y, 0, left + x, top_1 + y, rx);
  643. gradient_1.processColorStops(backgroundImage.stops, rx * 2).forEach(function (colorStop) {
  644. return radialGradient_1.addColorStop(colorStop.stop, color_1.asString(colorStop.color));
  645. });
  646. this_1.path(path);
  647. this_1.ctx.fillStyle = radialGradient_1;
  648. if (rx !== ry) {
  649. midX = container.bounds.left + 0.5 * container.bounds.width;
  650. midY = container.bounds.top + 0.5 * container.bounds.height;
  651. f = ry / rx;
  652. invF = 1 / f;
  653. this_1.ctx.save();
  654. this_1.ctx.translate(midX, midY);
  655. this_1.ctx.transform(1, 0, 0, f, 0, 0);
  656. this_1.ctx.translate(-midX, -midY);
  657. this_1.ctx.fillRect(left, invF * (top_1 - midY) + midY, width, height * invF);
  658. this_1.ctx.restore();
  659. }
  660. else {
  661. this_1.ctx.fill();
  662. }
  663. }
  664. }
  665. _f.label = 6;
  666. case 6:
  667. index--;
  668. return [2 /*return*/];
  669. }
  670. });
  671. };
  672. this_1 = this;
  673. _i = 0, _a = container.styles.backgroundImage.slice(0).reverse();
  674. _b.label = 1;
  675. case 1:
  676. if (!(_i < _a.length)) return [3 /*break*/, 4];
  677. backgroundImage = _a[_i];
  678. return [5 /*yield**/, _loop_1(backgroundImage)];
  679. case 2:
  680. _b.sent();
  681. _b.label = 3;
  682. case 3:
  683. _i++;
  684. return [3 /*break*/, 1];
  685. case 4: return [2 /*return*/];
  686. }
  687. });
  688. });
  689. };
  690. CanvasRenderer.prototype.renderBorder = function (color, side, curvePoints) {
  691. return __awaiter(this, void 0, void 0, function () {
  692. return __generator(this, function (_a) {
  693. this.path(border_1.parsePathForBorder(curvePoints, side));
  694. this.ctx.fillStyle = color_1.asString(color);
  695. this.ctx.fill();
  696. return [2 /*return*/];
  697. });
  698. });
  699. };
  700. CanvasRenderer.prototype.renderNodeBackgroundAndBorders = function (paint) {
  701. return __awaiter(this, void 0, void 0, function () {
  702. var styles, hasBackground, borders, backgroundPaintingArea, side, _i, borders_1, border;
  703. var _this = this;
  704. return __generator(this, function (_a) {
  705. switch (_a.label) {
  706. case 0:
  707. this.applyEffects(paint.effects, 2 /* BACKGROUND_BORDERS */);
  708. styles = paint.container.styles;
  709. hasBackground = !color_1.isTransparent(styles.backgroundColor) || styles.backgroundImage.length;
  710. borders = [
  711. { style: styles.borderTopStyle, color: styles.borderTopColor },
  712. { style: styles.borderRightStyle, color: styles.borderRightColor },
  713. { style: styles.borderBottomStyle, color: styles.borderBottomColor },
  714. { style: styles.borderLeftStyle, color: styles.borderLeftColor }
  715. ];
  716. backgroundPaintingArea = calculateBackgroundCurvedPaintingArea(background_1.getBackgroundValueForIndex(styles.backgroundClip, 0), paint.curves);
  717. if (!(hasBackground || styles.boxShadow.length)) return [3 /*break*/, 2];
  718. this.ctx.save();
  719. this.path(backgroundPaintingArea);
  720. this.ctx.clip();
  721. if (!color_1.isTransparent(styles.backgroundColor)) {
  722. this.ctx.fillStyle = color_1.asString(styles.backgroundColor);
  723. this.ctx.fill();
  724. }
  725. return [4 /*yield*/, this.renderBackgroundImage(paint.container)];
  726. case 1:
  727. _a.sent();
  728. this.ctx.restore();
  729. styles.boxShadow
  730. .slice(0)
  731. .reverse()
  732. .forEach(function (shadow) {
  733. _this.ctx.save();
  734. var borderBoxArea = bound_curves_1.calculateBorderBoxPath(paint.curves);
  735. var maskOffset = shadow.inset ? 0 : MASK_OFFSET;
  736. var shadowPaintingArea = path_1.transformPath(borderBoxArea, -maskOffset + (shadow.inset ? 1 : -1) * shadow.spread.number, (shadow.inset ? 1 : -1) * shadow.spread.number, shadow.spread.number * (shadow.inset ? -2 : 2), shadow.spread.number * (shadow.inset ? -2 : 2));
  737. if (shadow.inset) {
  738. _this.path(borderBoxArea);
  739. _this.ctx.clip();
  740. _this.mask(shadowPaintingArea);
  741. }
  742. else {
  743. _this.mask(borderBoxArea);
  744. _this.ctx.clip();
  745. _this.path(shadowPaintingArea);
  746. }
  747. _this.ctx.shadowOffsetX = shadow.offsetX.number + maskOffset;
  748. _this.ctx.shadowOffsetY = shadow.offsetY.number;
  749. _this.ctx.shadowColor = color_1.asString(shadow.color);
  750. _this.ctx.shadowBlur = shadow.blur.number;
  751. _this.ctx.fillStyle = shadow.inset ? color_1.asString(shadow.color) : 'rgba(0,0,0,1)';
  752. _this.ctx.fill();
  753. _this.ctx.restore();
  754. });
  755. _a.label = 2;
  756. case 2:
  757. side = 0;
  758. _i = 0, borders_1 = borders;
  759. _a.label = 3;
  760. case 3:
  761. if (!(_i < borders_1.length)) return [3 /*break*/, 7];
  762. border = borders_1[_i];
  763. if (!(border.style !== border_style_1.BORDER_STYLE.NONE && !color_1.isTransparent(border.color))) return [3 /*break*/, 5];
  764. return [4 /*yield*/, this.renderBorder(border.color, side, paint.curves)];
  765. case 4:
  766. _a.sent();
  767. _a.label = 5;
  768. case 5:
  769. side++;
  770. _a.label = 6;
  771. case 6:
  772. _i++;
  773. return [3 /*break*/, 3];
  774. case 7: return [2 /*return*/];
  775. }
  776. });
  777. });
  778. };
  779. CanvasRenderer.prototype.render = function (element) {
  780. return __awaiter(this, void 0, void 0, function () {
  781. var stack;
  782. return __generator(this, function (_a) {
  783. switch (_a.label) {
  784. case 0:
  785. if (this.options.backgroundColor) {
  786. this.ctx.fillStyle = color_1.asString(this.options.backgroundColor);
  787. this.ctx.fillRect(this.options.x - this.options.scrollX, this.options.y - this.options.scrollY, this.options.width, this.options.height);
  788. }
  789. stack = stacking_context_1.parseStackingContexts(element);
  790. return [4 /*yield*/, this.renderStack(stack)];
  791. case 1:
  792. _a.sent();
  793. this.applyEffects([], 2 /* BACKGROUND_BORDERS */);
  794. return [2 /*return*/, this.canvas];
  795. }
  796. });
  797. });
  798. };
  799. return CanvasRenderer;
  800. }());
  801. exports.CanvasRenderer = CanvasRenderer;
  802. var isTextInputElement = function (container) {
  803. if (container instanceof textarea_element_container_1.TextareaElementContainer) {
  804. return true;
  805. }
  806. else if (container instanceof select_element_container_1.SelectElementContainer) {
  807. return true;
  808. }
  809. else if (container instanceof input_element_container_1.InputElementContainer && container.type !== input_element_container_1.RADIO && container.type !== input_element_container_1.CHECKBOX) {
  810. return true;
  811. }
  812. return false;
  813. };
  814. var calculateBackgroundCurvedPaintingArea = function (clip, curves) {
  815. switch (clip) {
  816. case background_clip_1.BACKGROUND_CLIP.BORDER_BOX:
  817. return bound_curves_1.calculateBorderBoxPath(curves);
  818. case background_clip_1.BACKGROUND_CLIP.CONTENT_BOX:
  819. return bound_curves_1.calculateContentBoxPath(curves);
  820. case background_clip_1.BACKGROUND_CLIP.PADDING_BOX:
  821. default:
  822. return bound_curves_1.calculatePaddingBoxPath(curves);
  823. }
  824. };
  825. var canvasTextAlign = function (textAlign) {
  826. switch (textAlign) {
  827. case text_align_1.TEXT_ALIGN.CENTER:
  828. return 'center';
  829. case text_align_1.TEXT_ALIGN.RIGHT:
  830. return 'right';
  831. case text_align_1.TEXT_ALIGN.LEFT:
  832. default:
  833. return 'left';
  834. }
  835. };
  836. //# sourceMappingURL=canvas-renderer.js.map