or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-html2canvas

JavaScript library for taking screenshots of web pages or DOM elements directly in the browser

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/html2canvas@1.4.x

To install, run

npx @tessl/cli install tessl/npm-html2canvas@1.4.0

0

# html2canvas

1

2

html2canvas is a JavaScript library that enables taking "screenshots" of web pages or specific DOM elements directly in the browser without requiring server-side rendering. The library reads the DOM structure and applied CSS styles to recreate the visual representation as a canvas element, providing a client-side solution for generating images from HTML content.

3

4

## Package Information

5

6

- **Package Name**: html2canvas

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install html2canvas`

10

11

## Core Imports

12

13

```typescript

14

import html2canvas from "html2canvas";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const html2canvas = require("html2canvas");

21

```

22

23

## Basic Usage

24

25

```typescript

26

import html2canvas from "html2canvas";

27

28

// Take a screenshot of the entire body

29

html2canvas(document.body).then(function(canvas) {

30

document.body.appendChild(canvas);

31

});

32

33

// Take a screenshot of a specific element

34

const element = document.getElementById('myElement');

35

html2canvas(element).then(function(canvas) {

36

// Use the canvas (e.g., convert to image, save, etc.)

37

const imgData = canvas.toDataURL('image/png');

38

console.log(imgData);

39

});

40

41

// With options

42

html2canvas(document.body, {

43

width: 1920,

44

height: 1080,

45

scale: 1,

46

backgroundColor: '#ffffff',

47

useCORS: true,

48

allowTaint: false

49

}).then(function(canvas) {

50

document.body.appendChild(canvas);

51

});

52

```

53

54

## Architecture

55

56

html2canvas is built around several key components:

57

58

- **Main Function**: The primary `html2canvas()` function that orchestrates the screenshot process

59

- **Document Cloning**: Creates an isolated copy of the DOM for rendering without affecting the original page

60

- **CSS Processing**: Parses and processes CSS styles, including complex properties like gradients, transforms, and filters

61

- **Canvas Rendering**: Converts the processed DOM and styles into canvas drawing operations

62

- **Resource Handling**: Manages images, fonts, and other external resources with CORS and proxy support

63

- **Promise-Based API**: Asynchronous operation using modern Promise patterns

64

65

## Capabilities

66

67

### Screenshot Capture

68

69

The core functionality for capturing DOM elements as canvas images.

70

71

```typescript { .api }

72

/**

73

* Renders the specified HTML element to a canvas

74

* @param element - The DOM element to render

75

* @param options - Configuration options for rendering

76

* @returns Promise that resolves to an HTMLCanvasElement containing the rendered image

77

*/

78

function html2canvas(

79

element: HTMLElement,

80

options?: Partial<Options>

81

): Promise<HTMLCanvasElement>;

82

```

83

84

### Configuration Options

85

86

Comprehensive options interface for customizing the rendering behavior.

87

88

```typescript { .api }

89

type Options = CloneOptions & WindowOptions & RenderOptions & ContextOptions & {

90

/** Background color override for the rendered canvas */

91

backgroundColor?: string | null;

92

/** Use SVG foreignObject rendering instead of canvas rendering */

93

foreignObjectRendering?: boolean;

94

/** Whether to remove the temporary iframe container after rendering (default: true) */

95

removeContainer?: boolean;

96

};

97

```

98

99

### Clone Options

100

101

Options for controlling DOM element cloning behavior.

102

103

```typescript { .api }

104

interface CloneOptions {

105

/** Function to determine which elements should be ignored during cloning */

106

ignoreElements?: (element: Element) => boolean;

107

/** Callback executed after the document is cloned but before rendering */

108

onclone?: (document: Document, element: HTMLElement) => void;

109

/** Allow tainted images to be used in rendering */

110

allowTaint?: boolean;

111

}

112

```

113

114

### Window Options

115

116

Options for controlling viewport and scrolling behavior.

117

118

```typescript { .api }

119

interface WindowOptions {

120

/** Horizontal scroll offset (default: window.pageXOffset) */

121

scrollX?: number;

122

/** Vertical scroll offset (default: window.pageYOffset) */

123

scrollY?: number;

124

/** Window width for rendering (default: window.innerWidth) */

125

windowWidth?: number;

126

/** Window height for rendering (default: window.innerHeight) */

127

windowHeight?: number;

128

}

129

```

130

131

### Render Options

132

133

Options for controlling canvas rendering output.

134

135

```typescript { .api }

136

interface RenderOptions {

137

/** Device pixel ratio for high-DPI rendering (default: window.devicePixelRatio || 1) */

138

scale?: number;

139

/** Existing canvas element to render onto */

140

canvas?: HTMLCanvasElement;

141

/** X coordinate offset for rendering (default: 0) */

142

x?: number;

143

/** Y coordinate offset for rendering (default: 0) */

144

y?: number;

145

/** Width of the rendered output (default: calculated from element) */

146

width?: number;

147

/** Height of the rendered output (default: calculated from element) */

148

height?: number;

149

}

150

```

151

152

### Context Options

153

154

Options for controlling execution context and caching.

155

156

```typescript { .api }

157

type ContextOptions = {

158

/** Enable debug logging (default: true) */

159

logging?: boolean;

160

/** Custom cache instance for resources */

161

cache?: Cache;

162

} & ResourceOptions;

163

164

interface ResourceOptions {

165

/** Timeout for loading images in milliseconds (default: 15000) */

166

imageTimeout?: number;

167

/** Use CORS for cross-origin images (default: false) */

168

useCORS?: boolean;

169

/** Allow tainted canvas for cross-origin content (default: false) */

170

allowTaint?: boolean;

171

/** Proxy URL for loading cross-origin resources */

172

proxy?: string;

173

}

174

175

interface Cache {

176

/** Add an image to the cache for reuse */

177

addImage(src: string): Promise<void>;

178

/** Get a cached resource by source URL */

179

match(src: string): Promise<any>;

180

/** Check if a resource exists in the cache */

181

has(src: string): boolean;

182

}

183

```

184

185

## Advanced Usage Examples

186

187

### High-DPI Screenshots

188

189

```typescript

190

// Capture at 2x resolution for high-DPI displays

191

html2canvas(element, {

192

scale: 2,

193

width: element.offsetWidth * 2,

194

height: element.offsetHeight * 2

195

}).then(canvas => {

196

// Canvas will be 2x the size with crisp rendering

197

const ctx = canvas.getContext('2d');

198

ctx.scale(0.5, 0.5); // Scale down for display if needed

199

});

200

```

201

202

### Cross-Origin Images

203

204

```typescript

205

// Handle cross-origin images with CORS

206

html2canvas(element, {

207

useCORS: true,

208

allowTaint: false

209

}).then(canvas => {

210

// Canvas will include cross-origin images that support CORS

211

});

212

213

// Alternative: Use proxy for cross-origin content

214

html2canvas(element, {

215

proxy: 'https://your-proxy-server.com/proxy',

216

allowTaint: false

217

}).then(canvas => {

218

// Proxy server will fetch cross-origin resources

219

});

220

```

221

222

### Custom Element Filtering

223

224

```typescript

225

// Ignore specific elements during rendering

226

html2canvas(document.body, {

227

ignoreElements: (element) => {

228

// Skip elements with data-html2canvas-ignore attribute

229

return element.hasAttribute('data-html2canvas-ignore') ||

230

element.classList.contains('no-screenshot');

231

}

232

}).then(canvas => {

233

// Filtered elements won't appear in the screenshot

234

});

235

```

236

237

### Post-Clone DOM Manipulation

238

239

```typescript

240

// Modify the cloned document before rendering

241

html2canvas(element, {

242

onclone: (clonedDoc, clonedElement) => {

243

// Remove sensitive information from clone

244

const sensitiveElements = clonedDoc.querySelectorAll('.sensitive-data');

245

sensitiveElements.forEach(el => el.textContent = '[REDACTED]');

246

247

// Modify styles for better screenshot appearance

248

clonedElement.style.transform = 'none';

249

clonedElement.style.position = 'static';

250

}

251

}).then(canvas => {

252

// Screenshot will reflect the modifications made to the clone

253

});

254

```

255

256

### Converting to Different Formats

257

258

```typescript

259

html2canvas(element).then(canvas => {

260

// Convert to PNG data URL

261

const pngDataUrl = canvas.toDataURL('image/png');

262

263

// Convert to JPEG with quality setting

264

const jpegDataUrl = canvas.toDataURL('image/jpeg', 0.8);

265

266

// Convert to Blob for file operations

267

canvas.toBlob(blob => {

268

// Create download link

269

const url = URL.createObjectURL(blob);

270

const a = document.createElement('a');

271

a.href = url;

272

a.download = 'screenshot.png';

273

a.click();

274

URL.revokeObjectURL(url);

275

}, 'image/png');

276

});

277

```

278

279

## Error Handling

280

281

html2canvas operations can fail for various reasons. Always handle Promise rejections:

282

283

```typescript

284

html2canvas(element, options)

285

.then(canvas => {

286

// Success - use the canvas

287

console.log('Screenshot captured successfully');

288

})

289

.catch(error => {

290

// Handle errors

291

console.error('Screenshot failed:', error);

292

293

// Common error scenarios:

294

// - Element not attached to document

295

// - Security restrictions on cross-origin content

296

// - Invalid options or element

297

// - Browser compatibility issues

298

});

299

```

300

301

## Browser Compatibility

302

303

- **Modern Browsers**: Full support in Chrome, Firefox, Safari, Edge

304

- **Legacy Support**: IE9+ with Promise polyfill required

305

- **Mobile**: iOS Safari 6+, Android Chrome

306

- **Features**: Some CSS properties may have limited support depending on browser

307

308

## Limitations

309

310

- **No Server-Side**: Only works in browser environments, not Node.js

311

- **CSS Property Support**: Not all CSS properties are fully supported

312

- **Cross-Origin**: Requires CORS headers or proxy for external resources

313

- **Performance**: Large or complex DOM structures may be slow to render

314

- **Accuracy**: Output may differ from actual browser rendering in some cases