0
# Canvas Context Mock
1
2
Complete implementation of CanvasRenderingContext2D with all standard drawing methods, transformations, and properties. The mock provides comprehensive error handling that matches browser behavior, including proper TypeError, DOMException, and RangeError throwing for invalid inputs.
3
4
## Capabilities
5
6
### Drawing Operations
7
8
Methods for filling and stroking rectangles and paths.
9
10
```javascript { .api }
11
/**
12
* Fills a rectangle with the current fillStyle
13
* @param x - The x-axis coordinate of the rectangle's starting point
14
* @param y - The y-axis coordinate of the rectangle's starting point
15
* @param width - The rectangle's width
16
* @param height - The rectangle's height
17
*/
18
fillRect(x: number, y: number, width: number, height: number): void;
19
20
/**
21
* Strokes a rectangle with the current strokeStyle
22
* @param x - The x-axis coordinate of the rectangle's starting point
23
* @param y - The y-axis coordinate of the rectangle's starting point
24
* @param width - The rectangle's width
25
* @param height - The rectangle's height
26
*/
27
strokeRect(x: number, y: number, width: number, height: number): void;
28
29
/**
30
* Clears the specified rectangular area, making it fully transparent
31
* @param x - The x-axis coordinate of the rectangle's starting point
32
* @param y - The y-axis coordinate of the rectangle's starting point
33
* @param width - The rectangle's width
34
* @param height - The rectangle's height
35
*/
36
clearRect(x: number, y: number, width: number, height: number): void;
37
38
/**
39
* Fills the current path with the current fillStyle
40
* @param fillRule - Algorithm to determine inside vs outside of path
41
*/
42
fill(fillRule?: CanvasFillRule): void;
43
44
/**
45
* Fills the specified path with the current fillStyle
46
* @param path - Path2D object to fill
47
* @param fillRule - Algorithm to determine inside vs outside of path
48
*/
49
fill(path: Path2D, fillRule?: CanvasFillRule): void;
50
51
/**
52
* Strokes the current path with the current strokeStyle
53
*/
54
stroke(): void;
55
56
/**
57
* Strokes the specified path with the current strokeStyle
58
* @param path - Path2D object to stroke
59
*/
60
stroke(path: Path2D): void;
61
```
62
63
### Path Construction
64
65
Methods for building and modifying drawing paths.
66
67
```javascript { .api }
68
/**
69
* Starts a new path by emptying the list of sub-paths
70
*/
71
beginPath(): void;
72
73
/**
74
* Adds a straight line from current point to the start of current sub-path
75
*/
76
closePath(): void;
77
78
/**
79
* Moves the starting point of a new sub-path to specified coordinates
80
* @param x - The x-axis coordinate of the point
81
* @param y - The y-axis coordinate of the point
82
*/
83
moveTo(x: number, y: number): void;
84
85
/**
86
* Connects the last point in the sub-path to specified coordinates with a straight line
87
* @param x - The x-axis coordinate of the line's end point
88
* @param y - The y-axis coordinate of the line's end point
89
*/
90
lineTo(x: number, y: number): void;
91
92
/**
93
* Adds a circular arc to the current path
94
* @param x - The x-axis coordinate of the arc's center
95
* @param y - The y-axis coordinate of the arc's center
96
* @param radius - The arc's radius (must be non-negative)
97
* @param startAngle - The angle at which the arc starts in radians
98
* @param endAngle - The angle at which the arc ends in radians
99
* @param anticlockwise - If true, draws the arc counter-clockwise
100
* @throws {TypeError} If fewer than 5 arguments provided
101
* @throws {DOMException} If radius is negative
102
*/
103
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;
104
105
/**
106
* Adds an arc to the current path using control points and radius
107
* @param x1 - The x-axis coordinate of the first control point
108
* @param y1 - The y-axis coordinate of the first control point
109
* @param x2 - The x-axis coordinate of the second control point
110
* @param y2 - The y-axis coordinate of the second control point
111
* @param radius - The arc's radius
112
*/
113
arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void;
114
115
/**
116
* Adds a quadratic Bézier curve to the current path
117
* @param cpx - The x-axis coordinate of the control point
118
* @param cpy - The y-axis coordinate of the control point
119
* @param x - The x-axis coordinate of the end point
120
* @param y - The y-axis coordinate of the end point
121
*/
122
quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void;
123
124
/**
125
* Adds a cubic Bézier curve to the current path
126
* @param cp1x - The x-axis coordinate of the first control point
127
* @param cp1y - The y-axis coordinate of the first control point
128
* @param cp2x - The x-axis coordinate of the second control point
129
* @param cp2y - The y-axis coordinate of the second control point
130
* @param x - The x-axis coordinate of the end point
131
* @param y - The y-axis coordinate of the end point
132
*/
133
bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void;
134
135
/**
136
* Adds a rectangle to the current path
137
* @param x - The x-axis coordinate of the rectangle's starting point
138
* @param y - The y-axis coordinate of the rectangle's starting point
139
* @param width - The rectangle's width
140
* @param height - The rectangle's height
141
*/
142
rect(x: number, y: number, width: number, height: number): void;
143
144
/**
145
* Adds a rounded rectangle to the current path
146
* @param x - The x-axis coordinate of the rectangle's starting point
147
* @param y - The y-axis coordinate of the rectangle's starting point
148
* @param width - The rectangle's width
149
* @param height - The rectangle's height
150
* @param radii - Corner radius or array of radii
151
*/
152
roundRect(x: number, y: number, width: number, height: number, radii: number | number[]): void;
153
154
/**
155
* Adds an ellipse to the current path
156
* @param x - The x-axis coordinate of the ellipse's center
157
* @param y - The y-axis coordinate of the ellipse's center
158
* @param radiusX - The ellipse's major-axis radius
159
* @param radiusY - The ellipse's minor-axis radius
160
* @param rotation - The rotation of the ellipse in radians
161
* @param startAngle - The starting angle in radians
162
* @param endAngle - The ending angle in radians
163
* @param anticlockwise - If true, draws counter-clockwise
164
*/
165
ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;
166
```
167
168
### Text Rendering
169
170
Methods for drawing and measuring text.
171
172
```javascript { .api }
173
/**
174
* Fills text with the current fillStyle
175
* @param text - The text string to render
176
* @param x - The x-axis coordinate of the text's starting point
177
* @param y - The y-axis coordinate of the text's starting point
178
* @param maxWidth - Optional maximum width for text
179
*/
180
fillText(text: string, x: number, y: number, maxWidth?: number): void;
181
182
/**
183
* Strokes text with the current strokeStyle
184
* @param text - The text string to render
185
* @param x - The x-axis coordinate of the text's starting point
186
* @param y - The y-axis coordinate of the text's starting point
187
* @param maxWidth - Optional maximum width for text
188
*/
189
strokeText(text: string, x: number, y: number, maxWidth?: number): void;
190
191
/**
192
* Returns TextMetrics object containing measurements of the specified text
193
* @param text - The text string to measure
194
* @returns TextMetrics object with text measurements
195
*/
196
measureText(text: string): TextMetrics;
197
```
198
199
### Image Drawing
200
201
Methods for drawing images onto the canvas.
202
203
```javascript { .api }
204
/**
205
* Draws an image at the specified position
206
* @param image - The image source to draw
207
* @param dx - The x-axis coordinate of destination's top-left corner
208
* @param dy - The y-axis coordinate of destination's top-left corner
209
*/
210
drawImage(image: CanvasImageSource, dx: number, dy: number): void;
211
212
/**
213
* Draws an image scaled to specified size at the specified position
214
* @param image - The image source to draw
215
* @param dx - The x-axis coordinate of destination's top-left corner
216
* @param dy - The y-axis coordinate of destination's top-left corner
217
* @param dw - The width to draw the image in the destination canvas
218
* @param dh - The height to draw the image in the destination canvas
219
*/
220
drawImage(image: CanvasImageSource, dx: number, dy: number, dw: number, dh: number): void;
221
222
/**
223
* Draws a portion of an image scaled to specified size at the specified position
224
* @param image - The image source to draw
225
* @param sx - The x-axis coordinate of the top-left corner of the sub-rectangle of source image
226
* @param sy - The y-axis coordinate of the top-left corner of the sub-rectangle of source image
227
* @param sw - The width of the sub-rectangle of the source image
228
* @param sh - The height of the sub-rectangle of the source image
229
* @param dx - The x-axis coordinate of destination's top-left corner
230
* @param dy - The y-axis coordinate of destination's top-left corner
231
* @param dw - The width to draw the image in the destination canvas
232
* @param dh - The height to draw the image in the destination canvas
233
*/
234
drawImage(image: CanvasImageSource, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void;
235
```
236
237
### Transformations
238
239
Methods for modifying the transformation matrix.
240
241
```javascript { .api }
242
/**
243
* Adds scaling transformation to the transformation matrix
244
* @param x - Scaling factor in the horizontal direction
245
* @param y - Scaling factor in the vertical direction
246
*/
247
scale(x: number, y: number): void;
248
249
/**
250
* Adds rotation transformation to the transformation matrix
251
* @param angle - The rotation angle in radians
252
*/
253
rotate(angle: number): void;
254
255
/**
256
* Adds translation transformation to the transformation matrix
257
* @param x - Distance to move in the horizontal direction
258
* @param y - Distance to move in the vertical direction
259
*/
260
translate(x: number, y: number): void;
261
262
/**
263
* Multiplies the current transformation with the specified matrix
264
* @param a - Horizontal scaling factor
265
* @param b - Horizontal skewing factor
266
* @param c - Vertical skewing factor
267
* @param d - Vertical scaling factor
268
* @param e - Horizontal translation factor
269
* @param f - Vertical translation factor
270
*/
271
transform(a: number, b: number, c: number, d: number, e: number, f: number): void;
272
273
/**
274
* Resets the current transformation to the identity matrix and then multiplies with specified matrix
275
* @param a - Horizontal scaling factor
276
* @param b - Horizontal skewing factor
277
* @param c - Vertical skewing factor
278
* @param d - Vertical scaling factor
279
* @param e - Horizontal translation factor
280
* @param f - Vertical translation factor
281
*/
282
setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void;
283
284
/**
285
* Resets the current transformation to the identity matrix and then multiplies with specified matrix
286
* @param transform - DOMMatrix2DInit object representing the transformation
287
*/
288
setTransform(transform?: DOMMatrix2DInit): void;
289
290
/**
291
* Resets the current transformation to the identity matrix
292
*/
293
resetTransform(): void;
294
295
/**
296
* Gets the current transformation matrix
297
* @returns DOMMatrix representing the current transformation
298
*/
299
getTransform(): DOMMatrix;
300
```
301
302
### State Management
303
304
Methods for saving and restoring canvas state.
305
306
```javascript { .api }
307
/**
308
* Saves the current drawing state to a stack
309
*/
310
save(): void;
311
312
/**
313
* Restores the most recently saved drawing state from the stack
314
*/
315
restore(): void;
316
```
317
318
### Line and Path Utilities
319
320
Methods for working with line styles and path operations.
321
322
```javascript { .api }
323
/**
324
* Sets the line dash pattern
325
* @param segments - Array of numbers specifying dash and gap lengths
326
*/
327
setLineDash(segments: number[]): void;
328
329
/**
330
* Returns the current line dash pattern
331
* @returns Array representing the line dash pattern
332
*/
333
getLineDash(): number[];
334
335
/**
336
* Tests whether the specified point is inside the current path
337
* @param x - The x-axis coordinate of the point
338
* @param y - The y-axis coordinate of the point
339
* @returns True if point is inside the path
340
*/
341
isPointInPath(x: number, y: number): boolean;
342
343
/**
344
* Tests whether the specified point is inside the specified path
345
* @param path - Path2D object to test
346
* @param x - The x-axis coordinate of the point
347
* @param y - The y-axis coordinate of the point
348
* @returns True if point is inside the path
349
*/
350
isPointInPath(path: Path2D, x: number, y: number): boolean;
351
352
/**
353
* Tests whether the specified point is inside the stroke of the current path
354
* @param x - The x-axis coordinate of the point
355
* @param y - The y-axis coordinate of the point
356
* @returns True if point is in the stroke
357
*/
358
isPointInStroke(x: number, y: number): boolean;
359
360
/**
361
* Tests whether the specified point is inside the stroke of the specified path
362
* @param path - Path2D object to test
363
* @param x - The x-axis coordinate of the point
364
* @param y - The y-axis coordinate of the point
365
* @returns True if point is in the stroke
366
*/
367
isPointInStroke(path: Path2D, x: number, y: number): boolean;
368
```
369
370
### Clipping
371
372
Methods for creating clipping regions.
373
374
```javascript { .api }
375
/**
376
* Creates a clipping path from the current path
377
* @param fillRule - Algorithm to determine inside vs outside of path
378
*/
379
clip(fillRule?: CanvasFillRule): void;
380
381
/**
382
* Creates a clipping path from the specified path
383
* @param path - Path2D object to use as clipping path
384
* @param fillRule - Algorithm to determine inside vs outside of path
385
*/
386
clip(path: Path2D, fillRule?: CanvasFillRule): void;
387
```
388
389
### Gradient and Pattern Creation
390
391
Methods for creating gradients and patterns.
392
393
```javascript { .api }
394
/**
395
* Creates a linear gradient along the line connecting two points
396
* @param x0 - The x-axis coordinate of the start point
397
* @param y0 - The y-axis coordinate of the start point
398
* @param x1 - The x-axis coordinate of the end point
399
* @param y1 - The y-axis coordinate of the end point
400
* @returns CanvasGradient object
401
*/
402
createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient;
403
404
/**
405
* Creates a radial gradient between two circles
406
* @param x0 - The x-axis coordinate of the start circle's center
407
* @param y0 - The y-axis coordinate of the start circle's center
408
* @param r0 - The radius of the start circle
409
* @param x1 - The x-axis coordinate of the end circle's center
410
* @param y1 - The y-axis coordinate of the end circle's center
411
* @param r1 - The radius of the end circle
412
* @returns CanvasGradient object
413
*/
414
createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient;
415
416
/**
417
* Creates a pattern using the specified image and repetition
418
* @param image - The image source for the pattern
419
* @param repetition - How to repeat the pattern
420
* @returns CanvasPattern object or null
421
*/
422
createPattern(image: CanvasImageSource, repetition: string | null): CanvasPattern | null;
423
```
424
425
### Image Data Operations
426
427
Methods for working with pixel data.
428
429
```javascript { .api }
430
/**
431
* Returns ImageData object representing pixel data for specified area
432
* @param sx - The x-axis coordinate of the top-left corner of rectangle
433
* @param sy - The y-axis coordinate of the top-left corner of rectangle
434
* @param sw - The width of the rectangle
435
* @param sh - The height of the rectangle
436
* @returns ImageData object containing pixel data
437
*/
438
getImageData(sx: number, sy: number, sw: number, sh: number): ImageData;
439
440
/**
441
* Paints data from ImageData object onto the canvas
442
* @param imagedata - ImageData object containing the pixel data
443
* @param dx - Horizontal position at which to place the image data
444
* @param dy - Vertical position at which to place the image data
445
*/
446
putImageData(imagedata: ImageData, dx: number, dy: number): void;
447
448
/**
449
* Paints data from ImageData object onto the canvas with dirty rectangle
450
* @param imagedata - ImageData object containing the pixel data
451
* @param dx - Horizontal position at which to place the image data
452
* @param dy - Vertical position at which to place the image data
453
* @param dirtyX - Horizontal position of the top-left corner of dirty rectangle
454
* @param dirtyY - Vertical position of the top-left corner of dirty rectangle
455
* @param dirtyWidth - Width of the dirty rectangle
456
* @param dirtyHeight - Height of the dirty rectangle
457
*/
458
putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number): void;
459
460
/**
461
* Creates ImageData object with specified dimensions
462
* @param width - The width of the new ImageData object
463
* @param height - The height of the new ImageData object
464
* @returns New ImageData object
465
*/
466
createImageData(width: number, height: number): ImageData;
467
468
/**
469
* Creates ImageData object with same dimensions as specified ImageData
470
* @param imagedata - ImageData object to copy dimensions from
471
* @returns New ImageData object with same dimensions
472
*/
473
createImageData(imagedata: ImageData): ImageData;
474
```
475
476
### Hit Region Management
477
478
Methods for managing hit regions for accessibility and event handling.
479
480
```javascript { .api }
481
/**
482
* Adds a hit region to the canvas for accessibility and event handling
483
* @param options - Configuration object for the hit region
484
* @throws {DOMException} If both id and control are null
485
* @throws {TypeError} If fillRule is not a valid CanvasFillRule
486
*/
487
addHitRegion(options?: {
488
path?: Path2D;
489
fillRule?: CanvasFillRule;
490
id?: string;
491
parentID?: string;
492
cursor?: string;
493
control?: Element;
494
label?: string;
495
role?: string;
496
}): void;
497
498
/**
499
* Clears all hit regions from the canvas
500
*/
501
clearHitRegions(): void;
502
503
/**
504
* Removes a specific hit region by its identifier
505
* @param id - The identifier of the hit region to remove
506
*/
507
removeHitRegion(id: string): void;
508
```
509
510
### Accessibility and Focus Management
511
512
Methods for managing focus and accessibility features.
513
514
```javascript { .api }
515
/**
516
* Draws a focus ring around the current path if the element has focus
517
* @param element - The element to check for focus
518
*/
519
drawFocusIfNeeded(element: Element): void;
520
521
/**
522
* Draws a focus ring around the specified path if the element has focus
523
* @param path - Path2D object defining the focus area
524
* @param element - The element to check for focus
525
*/
526
drawFocusIfNeeded(path: Path2D, element: Element): void;
527
528
/**
529
* Scrolls the current path into view if necessary
530
*/
531
scrollPathIntoView(): void;
532
533
/**
534
* Scrolls the specified path into view if necessary
535
* @param path - Path2D object to scroll into view
536
*/
537
scrollPathIntoView(path: Path2D): void;
538
```
539
540
## Context Properties
541
542
All standard CanvasRenderingContext2D properties are available with proper getters and setters:
543
544
**Canvas and Context Properties:**
545
- **canvas**: The associated HTMLCanvasElement (read-only)
546
- **currentTransform**: Current transformation matrix as DOMMatrix (getter/setter)
547
548
**Style Properties:**
549
- **fillStyle**: Fill color, gradient, or pattern
550
- **strokeStyle**: Stroke color, gradient, or pattern
551
- **globalAlpha**: Global transparency level
552
- **globalCompositeOperation**: Compositing operation type
553
554
**Line Style Properties:**
555
- **lineWidth**: Line width for strokes
556
- **lineCap**: Line ending style ("butt", "round", "square")
557
- **lineJoin**: Line join style ("bevel", "round", "miter")
558
- **miterLimit**: Miter limit for line joins
559
- **lineDashOffset**: Offset for line dash pattern
560
561
**Text Properties:**
562
- **font**: Text font specification
563
- **textAlign**: Horizontal text alignment
564
- **textBaseline**: Vertical text alignment
565
- **direction**: Text direction ("ltr", "rtl", "inherit")
566
567
**Image Properties:**
568
- **imageSmoothingEnabled**: Whether image smoothing is enabled
569
- **imageSmoothingQuality**: Quality of image smoothing
570
571
**Shadow Properties:**
572
- **shadowOffsetX**: Horizontal shadow offset
573
- **shadowOffsetY**: Vertical shadow offset
574
- **shadowBlur**: Shadow blur level
575
- **shadowColor**: Shadow color
576
577
**Filter Properties:**
578
- **filter**: CSS filter effects (e.g., "blur(5px)", "grayscale(100%)", "none")