or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

browser-rendering.mdconfiguration.mdcore-generation.mdindex.mdserver-operations.mdstring-rendering.md

browser-rendering.mddocs/

0

# Browser Canvas Rendering

1

2

Browser-specific QR code rendering functionality for HTML5 canvas elements and data URL generation. These functions provide client-side QR code generation and display capabilities.

3

4

## Capabilities

5

6

### Canvas Rendering

7

8

Renders QR codes directly to HTML5 canvas elements.

9

10

```javascript { .api }

11

/**

12

* Draws QR code to an existing canvas element

13

* @param {HTMLCanvasElement} canvasElement - Canvas to draw on

14

* @param {string|Array} text - Text to encode or segments

15

* @param {Object} options - Rendering options

16

* @param {Function} callback - Completion callback

17

*/

18

function toCanvas(canvasElement, text, options, callback);

19

20

/**

21

* Creates a new canvas element with QR code

22

* @param {string|Array} text - Text to encode or segments

23

* @param {Object} options - Rendering options

24

* @param {Function} callback - Callback with (error, canvas)

25

*/

26

function toCanvas(text, options, callback);

27

```

28

29

**Usage Examples:**

30

31

```javascript

32

// Draw to existing canvas

33

const canvas = document.getElementById('qr-canvas');

34

QRCode.toCanvas(canvas, 'Hello World', function (error) {

35

if (error) console.error(error);

36

console.log('QR code drawn to canvas');

37

});

38

39

// Create new canvas

40

QRCode.toCanvas('Hello World', { width: 256 }, function (error, canvas) {

41

if (error) console.error(error);

42

document.body.appendChild(canvas);

43

});

44

45

// With custom styling

46

QRCode.toCanvas(canvas, 'Styled QR', {

47

color: {

48

dark: '#000080', // Dark blue modules

49

light: '#FFFFFF' // White background

50

},

51

width: 300,

52

margin: 2

53

}, function (error) {

54

if (error) console.error(error);

55

});

56

57

// Using Promises

58

try {

59

const canvas = await QRCode.toCanvas('Hello World');

60

document.body.appendChild(canvas);

61

} catch (error) {

62

console.error(error);

63

}

64

```

65

66

### Data URL Generation

67

68

Generates data URLs containing QR code images for use in img elements or direct display.

69

70

```javascript { .api }

71

/**

72

* Generates data URL from text using new canvas

73

* @param {string|Array} text - Text to encode or segments

74

* @param {Object} options - Generation options

75

* @param {Function} callback - Callback with (error, url)

76

* @returns {Promise<string>} Data URL when using promises

77

*/

78

function toDataURL(text, options, callback);

79

80

/**

81

* Generates data URL using existing canvas

82

* @param {HTMLCanvasElement} canvasElement - Canvas to use

83

* @param {string|Array} text - Text to encode or segments

84

* @param {Object} options - Generation options

85

* @param {Function} callback - Callback with (error, url)

86

* @returns {Promise<string>} Data URL when using promises

87

*/

88

function toDataURL(canvasElement, text, options, callback);

89

```

90

91

**Usage Examples:**

92

93

```javascript

94

// Generate PNG data URL

95

QRCode.toDataURL('Hello World', function (err, url) {

96

if (err) throw err;

97

98

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

99

img.src = url;

100

document.body.appendChild(img);

101

});

102

103

// Generate JPEG with quality setting

104

QRCode.toDataURL('Hello World', {

105

type: 'image/jpeg',

106

rendererOpts: {

107

quality: 0.8

108

}

109

}, function (err, url) {

110

console.log(url); // data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ...

111

});

112

113

// Generate WebP format

114

QRCode.toDataURL('Hello World', {

115

type: 'image/webp',

116

rendererOpts: {

117

quality: 0.9

118

}

119

}, function (err, url) {

120

console.log(url); // data:image/webp;base64,UklGRj4...

121

});

122

123

// Using existing canvas

124

const canvas = document.getElementById('temp-canvas');

125

QRCode.toDataURL(canvas, 'Hello', { width: 200 }, function (err, url) {

126

// Canvas is reused, URL contains the QR code

127

});

128

129

// Using Promises

130

try {

131

const url = await QRCode.toDataURL('Hello World', {

132

color: { dark: '#FF0000' },

133

width: 300

134

});

135

console.log('Data URL:', url);

136

} catch (err) {

137

console.error(err);

138

}

139

```

140

141

## Browser-Specific Options

142

143

### Image Format Options

144

145

Configure output image format and quality for data URLs:

146

147

```javascript { .api }

148

interface DataURLOptions {

149

/** Image MIME type */

150

type?: 'image/png' | 'image/jpeg' | 'image/webp'; // Default: 'image/png'

151

152

/** Format-specific rendering options */

153

rendererOpts?: {

154

/** Image quality for JPEG/WebP (0.0 to 1.0) */

155

quality?: number; // Default: 0.92

156

};

157

}

158

```

159

160

**Examples:**

161

162

```javascript

163

// High-quality JPEG

164

const jpegUrl = await QRCode.toDataURL('text', {

165

type: 'image/jpeg',

166

rendererOpts: { quality: 0.95 }

167

});

168

169

// Compressed WebP

170

const webpUrl = await QRCode.toDataURL('text', {

171

type: 'image/webp',

172

rendererOpts: { quality: 0.7 }

173

});

174

175

// PNG (default, no quality setting)

176

const pngUrl = await QRCode.toDataURL('text', {

177

type: 'image/png'

178

});

179

```

180

181

### Canvas Rendering Options

182

183

Standard rendering options apply to both canvas and data URL functions:

184

185

```javascript

186

// Size and scaling

187

QRCode.toCanvas(canvas, 'text', {

188

width: 400, // Force specific width in pixels

189

scale: 8, // Scale factor (alternative to width)

190

margin: 4 // Quiet zone size in modules

191

});

192

193

// Colors

194

QRCode.toCanvas(canvas, 'text', {

195

color: {

196

dark: '#000000FF', // Dark modules (RGBA hex)

197

light: '#FFFFFFFF' // Light modules (RGBA hex)

198

}

199

});

200

201

// Custom colors with transparency

202

QRCode.toCanvas(canvas, 'text', {

203

color: {

204

dark: '#FF0000FF', // Red modules

205

light: '#00000000' // Transparent background

206

}

207

});

208

```

209

210

## Module Bundler Integration

211

212

### Webpack/Browserify

213

214

```javascript

215

// ES6 imports

216

import QRCode from 'qrcode';

217

218

// CommonJS

219

const QRCode = require('qrcode');

220

221

// Usage in modern frameworks

222

const generateQR = async (text) => {

223

try {

224

const canvas = await QRCode.toCanvas(text, { width: 256 });

225

return canvas;

226

} catch (err) {

227

throw new Error(`QR generation failed: ${err.message}`);

228

}

229

};

230

```

231

232

### React Integration Example

233

234

```javascript

235

import React, { useEffect, useRef } from 'react';

236

import QRCode from 'qrcode';

237

238

function QRCodeComponent({ text, options = {} }) {

239

const canvasRef = useRef();

240

241

useEffect(() => {

242

if (canvasRef.current && text) {

243

QRCode.toCanvas(canvasRef.current, text, options, (error) => {

244

if (error) console.error('QR Code error:', error);

245

});

246

}

247

}, [text, options]);

248

249

return <canvas ref={canvasRef} />;

250

}

251

```

252

253

### Vue Integration Example

254

255

```javascript

256

import QRCode from 'qrcode';

257

258

export default {

259

mounted() {

260

this.generateQR();

261

},

262

methods: {

263

async generateQR() {

264

try {

265

const canvas = this.$refs.qrCanvas;

266

await QRCode.toCanvas(canvas, this.qrText, this.qrOptions);

267

} catch (err) {

268

console.error(err);

269

}

270

}

271

}

272

};

273

```

274

275

## Precompiled Bundle Usage

276

277

For direct browser usage without bundlers:

278

279

```html

280

<!DOCTYPE html>

281

<html>

282

<head>

283

<title>QR Code Example</title>

284

</head>

285

<body>

286

<canvas id="qr-canvas"></canvas>

287

<img id="qr-image" />

288

289

<!-- Include QRCode library -->

290

<script src="/node_modules/qrcode/build/qrcode.js"></script>

291

<!-- Or from CDN -->

292

<!-- <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.4/build/qrcode.min.js"></script> -->

293

294

<script>

295

// QRCode is now available globally

296

const canvas = document.getElementById('qr-canvas');

297

const img = document.getElementById('qr-image');

298

299

// Draw to canvas

300

QRCode.toCanvas(canvas, 'Hello World', function (error) {

301

if (error) console.error(error);

302

console.log('Canvas QR code generated');

303

});

304

305

// Generate image data URL

306

QRCode.toDataURL('Hello World', function (error, url) {

307

if (error) console.error(error);

308

img.src = url;

309

});

310

</script>

311

</body>

312

</html>

313

```

314

315

## Error Handling

316

317

Browser rendering functions can encounter specific errors:

318

319

```javascript

320

// Canvas context errors

321

QRCode.toCanvas(invalidCanvas, 'text', function (err) {

322

if (err) {

323

console.log(err.message); // Canvas-related error

324

}

325

});

326

327

// Image format errors

328

QRCode.toDataURL('text', { type: 'invalid/format' }, function (err, url) {

329

if (err) {

330

console.log(err.message); // Unsupported image format

331

}

332

});

333

334

// Insufficient canvas size

335

QRCode.toCanvas(smallCanvas, 'large text', { width: 1000 }, function (err) {

336

if (err) {

337

console.log(err.message); // Canvas size limitations

338

}

339

});

340

```

341

342

## Browser Compatibility

343

344

The browser rendering functions support:

345

346

- **Internet Explorer 10+**

347

- **Safari 5.1+**

348

- **All evergreen browsers** (Chrome, Firefox, Edge, Safari, Opera)

349

350

Features used:

351

- HTML5 Canvas API

352

- Canvas 2D rendering context

353

- Data URL generation (`canvas.toDataURL()`)

354

- Promise support (when not using callbacks)