html2canvas-pro
Version:
Screenshots with JavaScript. Next generation!
539 lines • 28 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CanvasRenderer = void 0;
const stacking_context_1 = require("../stacking-context");
const color_utilities_1 = require("../../css/types/color-utilities");
const path_1 = require("../path");
const bound_curves_1 = require("../bound-curves");
const bezier_curve_1 = require("../bezier-curve");
const vector_1 = require("../vector");
const background_1 = require("../background");
const text_1 = require("../../css/layout/text");
const image_element_container_1 = require("../../dom/replaced-elements/image-element-container");
const box_sizing_1 = require("../box-sizing");
const canvas_element_container_1 = require("../../dom/replaced-elements/canvas-element-container");
const svg_element_container_1 = require("../../dom/replaced-elements/svg-element-container");
const bitwise_1 = require("../../core/bitwise");
const length_percentage_1 = require("../../css/types/length-percentage");
const font_metrics_1 = require("../font-metrics");
const bounds_1 = require("../../css/layout/bounds");
const image_rendering_1 = require("../../css/property-descriptors/image-rendering");
const line_height_1 = require("../../css/property-descriptors/line-height");
const input_element_container_1 = require("../../dom/replaced-elements/input-element-container");
const textarea_element_container_1 = require("../../dom/elements/textarea-element-container");
const select_element_container_1 = require("../../dom/elements/select-element-container");
const iframe_element_container_1 = require("../../dom/replaced-elements/iframe-element-container");
const renderer_1 = require("../renderer");
const background_renderer_1 = require("./background-renderer");
const border_renderer_1 = require("./border-renderer");
const effects_renderer_1 = require("./effects-renderer");
const text_renderer_1 = require("./text-renderer");
const MASK_OFFSET = 10000;
class CanvasRenderer extends renderer_1.Renderer {
constructor(context, options) {
super(context, options);
this.canvas = options.canvas ? options.canvas : document.createElement('canvas');
this.ctx = this.canvas.getContext('2d');
if (!options.canvas) {
this.canvas.width = Math.floor(options.width * options.scale);
this.canvas.height = Math.floor(options.height * options.scale);
this.canvas.style.width = `${options.width}px`;
this.canvas.style.height = `${options.height}px`;
}
this.fontMetrics = new font_metrics_1.FontMetrics(document);
this.ctx.scale(this.options.scale, this.options.scale);
this.ctx.translate(-options.x, -options.y);
this.ctx.textBaseline = 'bottom';
// Set image smoothing options
if (options.imageSmoothing !== undefined) {
this.ctx.imageSmoothingEnabled = options.imageSmoothing;
}
if (options.imageSmoothingQuality) {
this.ctx.imageSmoothingQuality = options.imageSmoothingQuality;
}
// Initialize specialized renderers
this.backgroundRenderer = new background_renderer_1.BackgroundRenderer({
ctx: this.ctx,
context: this.context,
canvas: this.canvas,
options: {
width: options.width,
height: options.height,
scale: options.scale
}
});
this.borderRenderer = new border_renderer_1.BorderRenderer({ ctx: this.ctx }, {
path: (paths) => this.path(paths),
formatPath: (paths) => this.formatPath(paths)
});
this.effectsRenderer = new effects_renderer_1.EffectsRenderer({ ctx: this.ctx }, { path: (paths) => this.path(paths) });
this.textRenderer = new text_renderer_1.TextRenderer({
ctx: this.ctx,
context: this.context,
options: { scale: options.scale }
});
this.context.logger.debug(`Canvas renderer initialized (${options.width}x${options.height}) with scale ${options.scale}`);
}
async renderStack(stack) {
const styles = stack.element.container.styles;
if (styles.isVisible()) {
await this.renderStackContent(stack);
}
}
async renderNode(paint) {
if ((0, bitwise_1.contains)(paint.container.flags, 16 /* FLAGS.DEBUG_RENDER */)) {
debugger;
}
if (paint.container.styles.isVisible()) {
await this.renderNodeBackgroundAndBorders(paint);
await this.renderNodeContent(paint);
}
}
/**
* Helper method to render text with paint order support
* Reduces code duplication in line-clamp and normal rendering
*/
// Helper method to truncate text and add ellipsis if needed
renderReplacedElement(container, curves, image) {
const intrinsicWidth = image.naturalWidth || container.intrinsicWidth;
const intrinsicHeight = image.naturalHeight || container.intrinsicHeight;
if (image && intrinsicWidth > 0 && intrinsicHeight > 0) {
const box = (0, box_sizing_1.contentBox)(container);
const path = (0, bound_curves_1.calculatePaddingBoxPath)(curves);
this.path(path);
this.ctx.save();
this.ctx.clip();
let sx = 0, sy = 0, sw = intrinsicWidth, sh = intrinsicHeight, dx = box.left, dy = box.top, dw = box.width, dh = box.height;
const { objectFit } = container.styles;
const boxRatio = dw / dh;
const imgRatio = sw / sh;
if (objectFit === 2 /* OBJECT_FIT.CONTAIN */) {
if (imgRatio > boxRatio) {
dh = dw / imgRatio;
dy += (box.height - dh) / 2;
}
else {
dw = dh * imgRatio;
dx += (box.width - dw) / 2;
}
}
else if (objectFit === 4 /* OBJECT_FIT.COVER */) {
if (imgRatio > boxRatio) {
sw = sh * boxRatio;
sx += (intrinsicWidth - sw) / 2;
}
else {
sh = sw / boxRatio;
sy += (intrinsicHeight - sh) / 2;
}
}
else if (objectFit === 8 /* OBJECT_FIT.NONE */) {
if (sw > dw) {
sx += (sw - dw) / 2;
sw = dw;
}
else {
dx += (dw - sw) / 2;
dw = sw;
}
if (sh > dh) {
sy += (sh - dh) / 2;
sh = dh;
}
else {
dy += (dh - sh) / 2;
dh = sh;
}
}
else if (objectFit === 16 /* OBJECT_FIT.SCALE_DOWN */) {
const containW = imgRatio > boxRatio ? dw : dh * imgRatio;
const noneW = sw > dw ? sw : dw;
if (containW < noneW) {
if (imgRatio > boxRatio) {
dh = dw / imgRatio;
dy += (box.height - dh) / 2;
}
else {
dw = dh * imgRatio;
dx += (box.width - dw) / 2;
}
}
else {
if (sw > dw) {
sx += (sw - dw) / 2;
sw = dw;
}
else {
dx += (dw - sw) / 2;
dw = sw;
}
if (sh > dh) {
sy += (sh - dh) / 2;
sh = dh;
}
else {
dy += (dh - sh) / 2;
dh = sh;
}
}
}
this.ctx.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);
this.ctx.restore();
}
}
async renderNodeContent(paint) {
this.effectsRenderer.applyEffects(paint.getEffects(4 /* EffectTarget.CONTENT */));
const container = paint.container;
const curves = paint.curves;
const styles = container.styles;
// Use content box for text overflow calculation (excludes padding and border)
// This matches browser behavior where text-overflow uses the content width
const textBounds = (0, box_sizing_1.contentBox)(container);
for (const child of container.textNodes) {
await this.textRenderer.renderTextNode(child, styles, textBounds);
}
if (container instanceof image_element_container_1.ImageElementContainer) {
try {
const image = await this.context.cache.match(container.src);
// Apply image smoothing based on CSS image-rendering property and global options
const prevSmoothing = this.ctx.imageSmoothingEnabled;
// CSS image-rendering property overrides global settings
if (styles.imageRendering === image_rendering_1.IMAGE_RENDERING.PIXELATED ||
styles.imageRendering === image_rendering_1.IMAGE_RENDERING.CRISP_EDGES) {
this.context.logger.debug(`Disabling image smoothing for ${container.src} due to CSS image-rendering: ${styles.imageRendering === image_rendering_1.IMAGE_RENDERING.PIXELATED ? 'pixelated' : 'crisp-edges'}`);
this.ctx.imageSmoothingEnabled = false;
}
else if (styles.imageRendering === image_rendering_1.IMAGE_RENDERING.SMOOTH) {
this.context.logger.debug(`Enabling image smoothing for ${container.src} due to CSS image-rendering: smooth`);
this.ctx.imageSmoothingEnabled = true;
}
// IMAGE_RENDERING.AUTO: keep current global setting
this.renderReplacedElement(container, curves, image);
// Restore previous smoothing state
this.ctx.imageSmoothingEnabled = prevSmoothing;
}
catch (e) {
this.context.logger.error(`Error loading image ${container.src}`);
}
}
if (container instanceof canvas_element_container_1.CanvasElementContainer) {
this.renderReplacedElement(container, curves, container.canvas);
}
if (container instanceof svg_element_container_1.SVGElementContainer) {
try {
const image = await this.context.cache.match(container.svg);
this.renderReplacedElement(container, curves, image);
}
catch (e) {
this.context.logger.error(`Error loading svg ${container.svg.substring(0, 255)}`);
}
}
if (container instanceof iframe_element_container_1.IFrameElementContainer && container.tree) {
const iframeRenderer = new CanvasRenderer(this.context, {
scale: this.options.scale,
backgroundColor: container.backgroundColor,
x: 0,
y: 0,
width: container.width,
height: container.height
});
const canvas = await iframeRenderer.render(container.tree);
if (container.width && container.height) {
this.ctx.drawImage(canvas, 0, 0, container.width, container.height, container.bounds.left, container.bounds.top, container.bounds.width, container.bounds.height);
}
}
if (container instanceof input_element_container_1.InputElementContainer) {
const size = Math.min(container.bounds.width, container.bounds.height);
if (container.type === input_element_container_1.CHECKBOX) {
if (container.checked) {
this.ctx.save();
this.path([
new vector_1.Vector(container.bounds.left + size * 0.39363, container.bounds.top + size * 0.79),
new vector_1.Vector(container.bounds.left + size * 0.16, container.bounds.top + size * 0.5549),
new vector_1.Vector(container.bounds.left + size * 0.27347, container.bounds.top + size * 0.44071),
new vector_1.Vector(container.bounds.left + size * 0.39694, container.bounds.top + size * 0.5649),
new vector_1.Vector(container.bounds.left + size * 0.72983, container.bounds.top + size * 0.23),
new vector_1.Vector(container.bounds.left + size * 0.84, container.bounds.top + size * 0.34085),
new vector_1.Vector(container.bounds.left + size * 0.39363, container.bounds.top + size * 0.79)
]);
this.ctx.fillStyle = (0, color_utilities_1.asString)(input_element_container_1.INPUT_COLOR);
this.ctx.fill();
this.ctx.restore();
}
}
else if (container.type === input_element_container_1.RADIO) {
if (container.checked) {
this.ctx.save();
this.ctx.beginPath();
this.ctx.arc(container.bounds.left + size / 2, container.bounds.top + size / 2, size / 4, 0, Math.PI * 2, true);
this.ctx.fillStyle = (0, color_utilities_1.asString)(input_element_container_1.INPUT_COLOR);
this.ctx.fill();
this.ctx.restore();
}
}
}
if (isTextInputElement(container) && container.value.length) {
const [font, fontFamily, fontSize] = this.textRenderer.createFontStyle(styles);
const { baseline } = this.fontMetrics.getMetrics(fontFamily, fontSize);
this.ctx.font = font;
// Fix for Issue #92: Use placeholder color when rendering placeholder text
const isPlaceholder = container instanceof input_element_container_1.InputElementContainer && container.isPlaceholder;
this.ctx.fillStyle = isPlaceholder ? (0, color_utilities_1.asString)(input_element_container_1.PLACEHOLDER_COLOR) : (0, color_utilities_1.asString)(styles.color);
this.ctx.textBaseline = 'alphabetic';
this.ctx.textAlign = canvasTextAlign(container.styles.textAlign);
const bounds = (0, box_sizing_1.contentBox)(container);
let x = 0;
switch (container.styles.textAlign) {
case 1 /* TEXT_ALIGN.CENTER */:
x += bounds.width / 2;
break;
case 2 /* TEXT_ALIGN.RIGHT */:
x += bounds.width;
break;
}
// Fix for Issue #92: Position text vertically centered in single-line input
// Only apply vertical centering for InputElementContainer, not for textarea or select
let verticalOffset = 0;
if (container instanceof input_element_container_1.InputElementContainer) {
const fontSizeValue = (0, length_percentage_1.getAbsoluteValue)(styles.fontSize, 0);
verticalOffset = (bounds.height - fontSizeValue) / 2;
}
// Create text bounds with horizontal and vertical offsets
// Height is not modified as it doesn't affect text rendering position
const textBounds = bounds.add(x, verticalOffset, 0, 0);
this.ctx.save();
this.path([
new vector_1.Vector(bounds.left, bounds.top),
new vector_1.Vector(bounds.left + bounds.width, bounds.top),
new vector_1.Vector(bounds.left + bounds.width, bounds.top + bounds.height),
new vector_1.Vector(bounds.left, bounds.top + bounds.height)
]);
this.ctx.clip();
this.textRenderer.renderTextWithLetterSpacing(new text_1.TextBounds(container.value, textBounds), styles.letterSpacing, baseline);
this.ctx.restore();
this.ctx.textBaseline = 'alphabetic';
this.ctx.textAlign = 'left';
}
if ((0, bitwise_1.contains)(container.styles.display, 2048 /* DISPLAY.LIST_ITEM */)) {
if (container.styles.listStyleImage !== null) {
const img = container.styles.listStyleImage;
if (img.type === 0 /* CSSImageType.URL */) {
let image;
const url = img.url;
try {
image = await this.context.cache.match(url);
this.ctx.drawImage(image, container.bounds.left - (image.width + 10), container.bounds.top);
}
catch (e) {
this.context.logger.error(`Error loading list-style-image ${url}`);
}
}
}
else if (paint.listValue && container.styles.listStyleType !== -1 /* LIST_STYLE_TYPE.NONE */) {
const [font] = this.textRenderer.createFontStyle(styles);
this.ctx.font = font;
this.ctx.fillStyle = (0, color_utilities_1.asString)(styles.color);
this.ctx.textBaseline = 'middle';
this.ctx.textAlign = 'right';
const bounds = new bounds_1.Bounds(container.bounds.left, container.bounds.top + (0, length_percentage_1.getAbsoluteValue)(container.styles.paddingTop, container.bounds.width), container.bounds.width, (0, line_height_1.computeLineHeight)(styles.lineHeight, styles.fontSize.number) / 2 + 1);
this.textRenderer.renderTextWithLetterSpacing(new text_1.TextBounds(paint.listValue, bounds), styles.letterSpacing, (0, line_height_1.computeLineHeight)(styles.lineHeight, styles.fontSize.number) / 2 + 2);
this.ctx.textBaseline = 'bottom';
this.ctx.textAlign = 'left';
}
}
}
async renderStackContent(stack) {
if ((0, bitwise_1.contains)(stack.element.container.flags, 16 /* FLAGS.DEBUG_RENDER */)) {
debugger;
}
// https://www.w3.org/TR/css-position-3/#painting-order
// 1. the background and borders of the element forming the stacking context.
await this.renderNodeBackgroundAndBorders(stack.element);
// 2. the child stacking contexts with negative stack levels (most negative first).
for (const child of stack.negativeZIndex) {
await this.renderStack(child);
}
// 3. For all its in-flow, non-positioned, block-level descendants in tree order:
await this.renderNodeContent(stack.element);
for (const child of stack.nonInlineLevel) {
await this.renderNode(child);
}
// 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.
for (const child of stack.nonPositionedFloats) {
await this.renderStack(child);
}
// 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
for (const child of stack.nonPositionedInlineLevel) {
await this.renderStack(child);
}
for (const child of stack.inlineLevel) {
await this.renderNode(child);
}
// 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
for (const child of stack.zeroOrAutoZIndexOrTransformedOrOpacity) {
await this.renderStack(child);
}
// 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.
for (const child of stack.positiveZIndex) {
await this.renderStack(child);
}
}
mask(paths) {
this.ctx.beginPath();
this.ctx.moveTo(0, 0);
// Use logical dimensions (options.width/height) instead of canvas pixel dimensions
// because context has already been scaled by this.options.scale
// Fix for Issue #126: Using canvas pixel dimensions causes broken output
this.ctx.lineTo(this.options.width, 0);
this.ctx.lineTo(this.options.width, this.options.height);
this.ctx.lineTo(0, this.options.height);
this.ctx.lineTo(0, 0);
this.formatPath(paths.slice(0).reverse());
this.ctx.closePath();
}
path(paths) {
this.ctx.beginPath();
this.formatPath(paths);
this.ctx.closePath();
}
formatPath(paths) {
paths.forEach((point, index) => {
const start = (0, bezier_curve_1.isBezierCurve)(point) ? point.start : point;
if (index === 0) {
this.ctx.moveTo(start.x, start.y);
}
else {
this.ctx.lineTo(start.x, start.y);
}
if ((0, bezier_curve_1.isBezierCurve)(point)) {
this.ctx.bezierCurveTo(point.startControl.x, point.startControl.y, point.endControl.x, point.endControl.y, point.end.x, point.end.y);
}
});
}
async renderNodeBackgroundAndBorders(paint) {
this.effectsRenderer.applyEffects(paint.getEffects(2 /* EffectTarget.BACKGROUND_BORDERS */));
const styles = paint.container.styles;
const hasBackground = !(0, color_utilities_1.isTransparent)(styles.backgroundColor) || styles.backgroundImage.length;
const borders = [
{ 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((0, background_1.getBackgroundValueForIndex)(styles.backgroundClip, 0), paint.curves);
if (hasBackground || styles.boxShadow.length) {
this.ctx.save();
this.path(backgroundPaintingArea);
this.ctx.clip();
if (!(0, color_utilities_1.isTransparent)(styles.backgroundColor)) {
this.ctx.fillStyle = (0, color_utilities_1.asString)(styles.backgroundColor);
this.ctx.fill();
}
await this.backgroundRenderer.renderBackgroundImage(paint.container);
this.ctx.restore();
styles.boxShadow
.slice(0)
.reverse()
.forEach((shadow) => {
this.ctx.save();
const borderBoxArea = (0, bound_curves_1.calculateBorderBoxPath)(paint.curves);
const maskOffset = shadow.inset ? 0 : MASK_OFFSET;
const shadowPaintingArea = (0, 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));
if (shadow.inset) {
this.path(borderBoxArea);
this.ctx.clip();
this.mask(shadowPaintingArea);
}
else {
this.mask(borderBoxArea);
this.ctx.clip();
this.path(shadowPaintingArea);
}
this.ctx.shadowOffsetX = shadow.offsetX.number + maskOffset;
this.ctx.shadowOffsetY = shadow.offsetY.number;
this.ctx.shadowColor = (0, color_utilities_1.asString)(shadow.color);
this.ctx.shadowBlur = shadow.blur.number;
this.ctx.fillStyle = shadow.inset ? (0, color_utilities_1.asString)(shadow.color) : 'rgba(0,0,0,1)';
this.ctx.fill();
this.ctx.restore();
});
}
let side = 0;
for (const border of borders) {
if (border.style !== 0 /* BORDER_STYLE.NONE */ && !(0, color_utilities_1.isTransparent)(border.color) && border.width > 0) {
if (border.style === 2 /* BORDER_STYLE.DASHED */) {
await this.borderRenderer.renderDashedDottedBorder(border.color, border.width, side, paint.curves, 2 /* BORDER_STYLE.DASHED */);
}
else if (border.style === 3 /* BORDER_STYLE.DOTTED */) {
await this.borderRenderer.renderDashedDottedBorder(border.color, border.width, side, paint.curves, 3 /* BORDER_STYLE.DOTTED */);
}
else if (border.style === 4 /* BORDER_STYLE.DOUBLE */) {
await this.borderRenderer.renderDoubleBorder(border.color, border.width, side, paint.curves);
}
else {
await this.borderRenderer.renderSolidBorder(border.color, side, paint.curves);
}
}
side++;
}
}
async render(element) {
if (this.options.backgroundColor) {
this.ctx.fillStyle = (0, color_utilities_1.asString)(this.options.backgroundColor);
this.ctx.fillRect(this.options.x, this.options.y, this.options.width, this.options.height);
}
const stack = (0, stacking_context_1.parseStackingContexts)(element);
await this.renderStack(stack);
this.effectsRenderer.applyEffects([]);
return this.canvas;
}
}
exports.CanvasRenderer = CanvasRenderer;
const isTextInputElement = (container) => {
if (container instanceof textarea_element_container_1.TextareaElementContainer) {
return true;
}
else if (container instanceof select_element_container_1.SelectElementContainer) {
return true;
}
else if (container instanceof input_element_container_1.InputElementContainer && container.type !== input_element_container_1.RADIO && container.type !== input_element_container_1.CHECKBOX) {
return true;
}
return false;
};
const calculateBackgroundCurvedPaintingArea = (clip, curves) => {
switch (clip) {
case 0 /* BACKGROUND_CLIP.BORDER_BOX */:
return (0, bound_curves_1.calculateBorderBoxPath)(curves);
case 2 /* BACKGROUND_CLIP.CONTENT_BOX */:
return (0, bound_curves_1.calculateContentBoxPath)(curves);
case 1 /* BACKGROUND_CLIP.PADDING_BOX */:
default:
return (0, bound_curves_1.calculatePaddingBoxPath)(curves);
}
};
const canvasTextAlign = (textAlign) => {
switch (textAlign) {
case 1 /* TEXT_ALIGN.CENTER */:
return 'center';
case 2 /* TEXT_ALIGN.RIGHT */:
return 'right';
case 0 /* TEXT_ALIGN.LEFT */:
default:
return 'left';
}
};
//# sourceMappingURL=canvas-renderer.js.map