View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.javascript.host.canvas;
16  
17  import java.io.IOException;
18  import java.util.Locale;
19  
20  import org.apache.commons.lang3.StringUtils;
21  import org.apache.commons.logging.Log;
22  import org.apache.commons.logging.LogFactory;
23  import org.htmlunit.corejs.javascript.Context;
24  import org.htmlunit.corejs.javascript.Function;
25  import org.htmlunit.corejs.javascript.Scriptable;
26  import org.htmlunit.corejs.javascript.VarScope;
27  import org.htmlunit.html.HtmlImage;
28  import org.htmlunit.javascript.HtmlUnitScriptable;
29  import org.htmlunit.javascript.JavaScriptEngine;
30  import org.htmlunit.javascript.configuration.JsxClass;
31  import org.htmlunit.javascript.configuration.JsxConstructor;
32  import org.htmlunit.javascript.configuration.JsxFunction;
33  import org.htmlunit.javascript.configuration.JsxGetter;
34  import org.htmlunit.javascript.configuration.JsxSetter;
35  import org.htmlunit.javascript.host.dom.DOMException;
36  import org.htmlunit.javascript.host.html.HTMLCanvasElement;
37  import org.htmlunit.javascript.host.html.HTMLImageElement;
38  import org.htmlunit.platform.Platform;
39  import org.htmlunit.platform.canvas.rendering.RenderingBackend;
40  import org.htmlunit.platform.canvas.rendering.RenderingBackend.LineCap;
41  import org.htmlunit.platform.canvas.rendering.RenderingBackend.LineJoin;
42  import org.htmlunit.platform.canvas.rendering.RenderingBackend.TextAlign;
43  import org.htmlunit.platform.canvas.rendering.RenderingBackend.TextBaseline;
44  import org.htmlunit.platform.canvas.rendering.RenderingBackend.WindingRule;
45  import org.htmlunit.protocol.data.DataURLConnection;
46  import org.htmlunit.util.MimeType;
47  
48  /**
49   * A JavaScript object for {@code CanvasRenderingContext2D}.
50   *
51   * @author Ahmed Ashour
52   * @author Marc Guillemot
53   * @author Frank Danek
54   * @author Ronald Brill
55   *
56   * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D">MDN Documentation</a>
57   */
58  @JsxClass
59  public class CanvasRenderingContext2D extends HtmlUnitScriptable {
60  
61      private static final Log LOG = LogFactory.getLog(CanvasRenderingContext2D.class);
62  
63      private HTMLCanvasElement canvas_;
64      private RenderingBackend renderingBackend_;
65  
66      /**
67       * Default constructor.
68       */
69      public CanvasRenderingContext2D() {
70          super();
71      }
72  
73      /**
74       * JavaScript constructor.
75       */
76      @JsxConstructor
77      public void jsConstructor() {
78          // nothing to do
79      }
80  
81      /**
82       * Constructs in association with {@link HTMLCanvasElement}.
83       * @param canvas the {@link HTMLCanvasElement}
84       */
85      public CanvasRenderingContext2D(final HTMLCanvasElement canvas) {
86          super();
87          canvas_ = canvas;
88          renderingBackend_ = null;
89      }
90  
91      /**
92       * Discards the current bitmap (and the drawing state); the next drawing operation
93       * creates a new, empty bitmap using the current size of the canvas.
94       * Called if the size of the canvas changes.
95       */
96      public void resetBitmap() {
97          renderingBackend_ = null;
98      }
99  
100     private RenderingBackend getRenderingBackend() {
101         if (renderingBackend_ == null) {
102             final int imageWidth = Math.max(1, canvas_.getWidth());
103             final int imageHeight = Math.max(1, canvas_.getHeight());
104 
105             renderingBackend_ = Platform.getRenderingBackend(imageWidth, imageHeight);
106         }
107         return renderingBackend_;
108     }
109 
110     /**
111      * Specifies the alpha (transparency) value that is applied to shapes and images
112      * before they are drawn onto the canvas.
113      * @return the {@code globalAlpha} property
114      */
115     @JsxGetter
116     public double getGlobalAlpha() {
117         return getRenderingBackend().getGlobalAlpha();
118     }
119 
120     /**
121      * Sets the {@code globalAlpha} property.
122      * @param globalAlpha the {@code globalAlpha} property value
123      */
124     @JsxSetter
125     public void setGlobalAlpha(final double globalAlpha) {
126         getRenderingBackend().setGlobalAlpha(globalAlpha);
127     }
128 
129     /**
130      * Returns the {@code fillStyle} property.
131      * @return the {@code fillStyle} property
132      */
133     @JsxGetter
134     public HtmlUnitScriptable getFillStyle() {
135         LOG.info("CanvasRenderingContext2D.getFillStyle() not yet implemented");
136         return null;
137     }
138 
139     /**
140      * Sets the {@code fillStyle} property.
141      * @param fillStyle the {@code fillStyle} property value
142      */
143     @JsxSetter
144     public void setFillStyle(final String fillStyle) {
145         getRenderingBackend().setFillStyle(fillStyle);
146     }
147 
148     /**
149      * Returns the {@code strokeStyle} property.
150      * @return the {@code strokeStyle} property
151      */
152     @JsxGetter
153     public HtmlUnitScriptable getStrokeStyle() {
154         LOG.info("CanvasRenderingContext2D.getStrokeStyle() not yet implemented");
155         return null;
156     }
157 
158     /**
159      * Sets the {@code strokeStyle} property.
160      * @param strokeStyle the {@code strokeStyle} property value
161      */
162     @JsxSetter
163     public void setStrokeStyle(final String strokeStyle) {
164         getRenderingBackend().setStrokeStyle(strokeStyle);
165     }
166 
167     /**
168      * Returns the {@code lineWidth} property.
169      * @return the {@code lineWidth} property
170      */
171     @JsxGetter
172     public double getLineWidth() {
173         return getRenderingBackend().getLineWidth();
174     }
175 
176     /**
177      * Sets the {@code lineWidth} property.
178      * @param lineWidth the {@code lineWidth} property value
179      */
180     @JsxSetter
181     public void setLineWidth(final Object lineWidth) {
182         if (!JavaScriptEngine.isUndefined(lineWidth)) {
183             final double width = JavaScriptEngine.toNumber(lineWidth);
184             if (!Double.isNaN(width)) {
185                 getRenderingBackend().setLineWidth((float) width);
186             }
187         }
188     }
189 
190     /**
191      * Draws an arc.
192      * @param x the x
193      * @param y the y
194      * @param radius the radius
195      * @param startAngle the start angle
196      * @param endAngle the end angle
197      * @param anticlockwise is anti-clockwise
198      */
199     @JsxFunction
200     public void arc(final double x, final double y, final double radius, final double startAngle,
201                 final double endAngle, final boolean anticlockwise) {
202         getRenderingBackend().arc(x, y, radius, startAngle, endAngle, anticlockwise);
203     }
204 
205     /**
206      * Draws an arc.
207      * @param x1 the x1
208      * @param y1 the y1
209      * @param x2 the x2
210      * @param y2 the y2
211      * @param radius the radius
212      */
213     @JsxFunction
214     public void arcTo(final double x1, final double y1, final double x2, final double y2,
215                 final double radius) {
216         LOG.info("CanvasRenderingContext2D.arcTo() not yet implemented");
217     }
218 
219     /**
220      * Begins the subpaths.
221      */
222     @JsxFunction
223     public void beginPath() {
224         getRenderingBackend().beginPath();
225     }
226 
227     /**
228      * Draws a cubic Bézier curve.
229      * @param cp1x the cp1x
230      * @param cp1y the cp1y
231      * @param cp2x the cp2x
232      * @param cp2y the cp2y
233      * @param x the x
234      * @param y the y
235      */
236     @JsxFunction
237     public void bezierCurveTo(final double cp1x, final double cp1y, final double cp2x, final double cp2y,
238             final double x, final double y) {
239         getRenderingBackend().bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
240     }
241 
242     /**
243      * Clears the specified rectangular area.
244      * @param x the x
245      * @param y the y
246      * @param w the width
247      * @param h the height
248      */
249     @JsxFunction
250     public void clearRect(final double x, final double y, final double w, final double h) {
251         getRenderingBackend().clearRect(x, y, w, h);
252     }
253 
254     /**
255      * Creates a new clipping region.
256      * @param context the JavaScript context
257      * @param scope the scope
258      * @param thisObj the scriptable
259      * @param args the arguments passed into the method
260      * @param function the function
261      */
262     @JsxFunction
263     public static void clip(final Context context, final VarScope scope,
264             final Scriptable thisObj, final Object[] args, final Function function) {
265         if (!(thisObj instanceof CanvasRenderingContext2D canvas)) {
266             throw JavaScriptEngine.reportRuntimeError(
267                     "CanvasRenderingContext2D.clip() failed - this is not a CanvasRenderingContext2D");
268         }
269 
270         RenderingBackend.WindingRule windingRule = WindingRule.NON_ZERO;
271         if (args.length == 1) {
272             final String windingRuleParam = JavaScriptEngine.toString(args[0]);
273             if ("evenodd".contentEquals(windingRuleParam)) {
274                 windingRule = WindingRule.EVEN_ODD;
275             }
276             canvas.getRenderingBackend().clip(windingRule, null);
277             return;
278         }
279 
280         if (args.length > 1) {
281             if (!(args[0] instanceof Path2D)) {
282                 throw JavaScriptEngine.reportRuntimeError(
283                         "CanvasRenderingContext2D.clip() failed - the first parameter has to be a Path2D");
284             }
285 
286             final String windingRuleParam = JavaScriptEngine.toString(args[1]);
287             if ("evenodd".contentEquals(windingRuleParam)) {
288                 windingRule = WindingRule.EVEN_ODD;
289             }
290 
291             LOG.info("CanvasRenderingContext2D.clip(path, fillRule) not yet implemented");
292             // canvas.getRenderingBackend().clip(windingRule, (Path2D) args[0]);
293             return;
294         }
295 
296         canvas.getRenderingBackend().clip(WindingRule.NON_ZERO, null);
297     }
298 
299     /**
300      * Closes the current subpath.
301      */
302     @JsxFunction
303     public void closePath() {
304         getRenderingBackend().closePath();
305     }
306 
307     /**
308      * Returns the {@code ImageData} object.
309      * This may accept a variable number of arguments.
310      * @param context the JavaScript context
311      * @param scope the scope
312      * @param thisObj the scriptable
313      * @param args the arguments passed into the method
314      * @param function the function
315      * @return the {@code ImageData} object
316      */
317     @JsxFunction
318     public static ImageData createImageData(final Context context, final VarScope scope,
319             final Scriptable thisObj, final Object[] args, final Function function) {
320         if (!(thisObj instanceof CanvasRenderingContext2D canvas)) {
321             throw JavaScriptEngine.reportRuntimeError(
322                     "CanvasRenderingContext2D.createImageData() failed - this is not a CanvasRenderingContext2D");
323         }
324 
325         if (args.length > 0 && args[0] instanceof ImageData imageDataParameter) {
326             final ImageData imageData = new ImageData(null,
327                     0, 0, imageDataParameter.getWidth(), imageDataParameter.getHeight());
328             imageData.setParentScope(scope);
329             imageData.setPrototype(canvas.getPrototype(imageData.getClass()));
330             return imageData;
331         }
332 
333         if (args.length > 1) {
334             final int width = Math.abs((int) JavaScriptEngine.toInteger(args, 0));
335             final int height = Math.abs((int) JavaScriptEngine.toInteger(args, 1));
336             final ImageData imageData = new ImageData(null, 0, 0, width, height);
337             imageData.setParentScope(canvas.getParentScope());
338             imageData.setPrototype(canvas.getPrototype(imageData.getClass()));
339             return imageData;
340         }
341 
342         throw JavaScriptEngine.reportRuntimeError(
343                 "CanvasRenderingContext2D.createImageData() failed - "
344                 + "wrong parameters given (" + StringUtils.join(args, ", ") + ")");
345     }
346 
347     /**
348      * Creates linear gradient.
349      * @param x0 the x0
350      * @param y0 the y0
351      * @param x1 the x1
352      * @param y1 the y1
353      * @return the new CanvasGradient
354      */
355     @JsxFunction
356     public CanvasGradient createLinearGradient(final double x0, final double y0, final double x1,
357             final Object y1) {
358         final CanvasGradient canvasGradient = new CanvasGradient();
359         canvasGradient.setParentScope(getParentScope());
360         canvasGradient.setPrototype(getPrototype(canvasGradient.getClass()));
361         return canvasGradient;
362     }
363 
364     /**
365      * Creates a pattern.
366      */
367     @JsxFunction
368     public void createPattern() {
369         LOG.info("CanvasRenderingContext2D.createPattern() not yet implemented");
370     }
371 
372     /**
373      * Creates a gradient.
374      * @param x0 the x axis of the coordinate of the start circle
375      * @param y0 the y axis of the coordinate of the start circle
376      * @param r0 the radius of the start circle
377      * @param x1 the x axis of the coordinate of the end circle
378      * @param y1 the y axis of the coordinate of the end circle
379      * @param r1 the radius of the end circle
380      * @return the new CanvasGradient
381      */
382     @JsxFunction
383     public CanvasGradient createRadialGradient(final double x0, final double y0,
384                             final double r0, final double x1, final double y1, final double r1) {
385         final CanvasGradient canvasGradient = new CanvasGradient();
386         canvasGradient.setParentScope(getParentScope());
387         canvasGradient.setPrototype(getPrototype(canvasGradient.getClass()));
388         return canvasGradient;
389     }
390 
391     /**
392      * Draws images onto the canvas.
393      *
394      * @param image an element to draw into the context
395      * @param sx the X coordinate of the top left corner of the sub-rectangle of the source image
396      *        to draw into the destination context
397      * @param sy the Y coordinate of the top left corner of the sub-rectangle of the source image
398      *        to draw into the destination context
399      * @param sWidth the width of the sub-rectangle of the source image to draw into the destination context
400      * @param sHeight the height of the sub-rectangle of the source image to draw into the destination context
401      * @param dx the X coordinate in the destination canvas at which to place the top-left corner of the source image
402      * @param dy the Y coordinate in the destination canvas at which to place the top-left corner of the source image
403      * @param dWidth the width to draw the image in the destination canvas. This allows scaling of the drawn image
404      * @param dHeight the height to draw the image in the destination canvas. This allows scaling of the drawn image
405      */
406     @JsxFunction
407     @SuppressWarnings("unused")
408     public void drawImage(final Object image, final int sx, final int sy, final Object sWidth, final Object sHeight,
409             final Object dx, final Object dy, final Object dWidth, final Object dHeight) {
410 
411         if (image instanceof HTMLCanvasElement canvasElem && !canvasElem.isOriginClean()) {
412             // drawing a tainted canvas taints this canvas
413             canvas_.setOriginCleanFalse();
414         }
415 
416         if (image instanceof HTMLImageElement imageElem) {
417             try {
418                 final HtmlImage htmlImage = (HtmlImage) imageElem.getDomNodeOrDie();
419                 if (htmlImage.isBroken()) {
420                     throw JavaScriptEngine.asJavaScriptException(this,
421                             "Failed to execute 'drawImage' on 'CanvasRenderingContext2D': "
422                                     + "The HTMLImageElement provided is in the 'broken' state.",
423                             DOMException.INVALID_STATE_ERR);
424                 }
425                 final org.htmlunit.platform.image.ImageData imageData = htmlImage.getImageData();
426 
427                 // image data of another origin taints the canvas
428                 if (htmlImage.isCorsCrossOrigin()) {
429                     canvas_.setOriginCleanFalse();
430                 }
431 
432                 // 3 arguments
433                 //   void ctx.drawImage(image, dx, dy);
434                 if (JavaScriptEngine.isUndefined(sWidth)) {
435                     getRenderingBackend().drawImage(imageData, 0, 0, null, null, sx, sy, null, null);
436                 }
437 
438                 // 5 arguments
439                 //   void ctx.drawImage(image, dx, dy, dWidth, dHeight);
440                 else if (JavaScriptEngine.isUndefined(dx)) {
441                     final int dWidthI = JavaScriptEngine.toInt32(sWidth);
442                     final int dHeightI = JavaScriptEngine.toInt32(sHeight);
443 
444                     getRenderingBackend().drawImage(imageData, 0, 0, null, null, sx, sy, dWidthI, dHeightI);
445                 }
446 
447                 // all 9 arguments
448                 //   void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
449                 else {
450                     final int sWidthI = JavaScriptEngine.toInt32(sWidth);
451                     final int sHeightI = JavaScriptEngine.toInt32(sHeight);
452 
453                     final int dxI = JavaScriptEngine.toInt32(dx);
454                     final int dyI = JavaScriptEngine.toInt32(dy);
455                     final int dWidthI = JavaScriptEngine.toInt32(dWidth);
456                     final int dHeightI = JavaScriptEngine.toInt32(dHeight);
457 
458                     getRenderingBackend().drawImage(imageData,
459                             sx, sy, sWidthI, sHeightI, dxI, dyI, dWidthI, dHeightI);
460                 }
461             }
462             catch (final IOException ex) {
463                 LOG.info("There is no ImageReader available for your image with src '" + imageElem.getSrc() + "'. "
464                         + "Please have a look at https://www.htmlunit.org/images-howto.html "
465                         + "for a possible solution.");
466             }
467         }
468     }
469 
470     /**
471      * Returns the Data URL.
472      *
473      * @param type an optional type
474      * @return the dataURL
475      */
476     public String toDataURL(final String type) {
477         try {
478             final String mimeType = type == null ? MimeType.IMAGE_PNG : type;
479             return DataURLConnection.DATA_PREFIX + mimeType + ";base64,"
480                     + getRenderingBackend().encodeToString(mimeType);
481         }
482         catch (final IOException ex) {
483             throw JavaScriptEngine.throwAsScriptRuntimeEx(ex);
484         }
485     }
486 
487     /**
488      * Paints the specified ellipse.
489      * @param x the x
490      * @param y the y
491      * @param radiusX the radiusX
492      * @param radiusY the radiusY
493      * @param rotation the rotation
494      * @param startAngle the startAngle
495      * @param endAngle the endAngle
496      * @param anticlockwise the anticlockwise
497      */
498     @JsxFunction
499     public void ellipse(final double x, final double y,
500                     final double radiusX, final double radiusY,
501                     final double rotation, final double startAngle, final double endAngle,
502                     final boolean anticlockwise) {
503         getRenderingBackend().ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise);
504     }
505 
506     /**
507      * Fills the shape.
508      * @param context the context
509      * @param scope the scope
510      * @param thisObj this object
511      * @param args the arguments
512      * @param function the function
513      */
514     @JsxFunction
515     public static void fill(final Context context, final VarScope scope,
516             final Scriptable thisObj, final Object[] args, final Function function) {
517         if (!(thisObj instanceof CanvasRenderingContext2D renderingCtx)) {
518             throw JavaScriptEngine.reportRuntimeError(
519                     "CanvasRenderingContext2D.fill() failed - this is not a CanvasRenderingContext2D");
520         }
521 
522         // Determine which argument (if any) is the fill rule string.
523         // Signature 1: fill(optional CanvasFillRule fillRule)
524         // Signature 2: fill(Path2D path, optional CanvasFillRule fillRule)
525         String fillRuleStr = null;
526         if (args.length > 1) {
527             fillRuleStr = JavaScriptEngine.toString(args[1]);
528         }
529         else if (args.length > 0) {
530             fillRuleStr = JavaScriptEngine.toString(args[0]);
531         }
532 
533         RenderingBackend.WindingRule windingRule = RenderingBackend.WindingRule.NON_ZERO;
534         if (fillRuleStr != null) {
535             if ("evenodd".equals(fillRuleStr)) {
536                 windingRule = RenderingBackend.WindingRule.EVEN_ODD;
537             }
538             else if (!"nonzero".equals(fillRuleStr)) {
539                 // Per spec: unrecognised values are ignored entirely.
540                 // Since fill() has no persistent fill-rule state, we just
541                 // use the default nonzero — which is already set above.
542                 // Log it for debugging purposes.
543                 if (LOG.isWarnEnabled()) {
544                     LOG.warn("fill() called with unrecognised fillRule: '" + fillRuleStr + "', using 'nonzero'.");
545                 }
546             }
547         }
548 
549         renderingCtx.getRenderingBackend().fill(windingRule);
550     }
551 
552     /**
553      * Paints the specified rectangular area.
554      * @param x the x
555      * @param y the y
556      * @param w the width
557      * @param h the height
558      */
559     @JsxFunction
560     public void fillRect(final int x, final int y, final int w, final int h) {
561         getRenderingBackend().fillRect(x, y, w, h);
562     }
563 
564     /**
565      * Fills a given text at the given (x, y) position.
566      * @param text the text
567      * @param x the x
568      * @param y the y
569      */
570     @JsxFunction
571     public void fillText(final String text, final double x, final double y) {
572         getRenderingBackend().fillText(text, x, y);
573     }
574 
575     /**
576      * Returns the {@code ImageData} object.
577      * @param sx x
578      * @param sy y
579      * @param sw width
580      * @param sh height
581      * @return the {@code ImageData} object
582      */
583     @JsxFunction
584     public ImageData getImageData(final int sx, final int sy, final int sw, final int sh) {
585         if (!canvas_.isOriginClean()) {
586             throw JavaScriptEngine.asJavaScriptException(this,
587                     "Failed to execute 'getImageData' on 'CanvasRenderingContext2D': "
588                             + "The canvas has been tainted by cross-origin data.",
589                     DOMException.SECURITY_ERR);
590         }
591 
592         final ImageData imageData = new ImageData(getRenderingBackend(), sx, sy, sw, sh);
593         imageData.setParentScope(getParentScope());
594         imageData.setPrototype(getPrototype(imageData.getClass()));
595         return imageData;
596     }
597 
598     /**
599      * Dummy placeholder.
600      */
601     @JsxFunction(functionName = "getLineDash")
602     public void lineDash() {
603         LOG.info("CanvasRenderingContext2D.getLineDash() not yet implemented");
604     }
605 
606     /**
607      * Dummy placeholder.
608      */
609     @JsxFunction(functionName = "getLineData")
610     public void lineData() {
611         LOG.info("CanvasRenderingContext2D.getLineData() not yet implemented");
612     }
613 
614     /**
615      * Dummy placeholder.
616      */
617     @JsxFunction
618     public void isPointInPath() {
619         LOG.info("CanvasRenderingContext2D.isPointInPath() not yet implemented");
620     }
621 
622     /**
623      * Connect the last point to the given point.
624      * @param x the x
625      * @param y the y
626      */
627     @JsxFunction
628     public void lineTo(final double x, final double y) {
629         getRenderingBackend().lineTo(x, y);
630     }
631 
632     /**
633      * Calculate TextMetrics for the given text.
634      * @param text the text to measure
635      * @return the text metrics
636      */
637     @JsxFunction
638     public TextMetrics measureText(final Object text) {
639         if (text == null || JavaScriptEngine.isUndefined(text)) {
640             throw JavaScriptEngine.typeError("Missing argument for CanvasRenderingContext2D.measureText().");
641         }
642 
643         final String textValue = JavaScriptEngine.toString(text);
644 
645         // TODO take font into account
646         final int width = textValue.length() * getBrowserVersion().getPixelsPerChar();
647 
648         final TextMetrics metrics = new TextMetrics(width);
649         metrics.setParentScope(getParentScope());
650         metrics.setPrototype(getPrototype(metrics.getClass()));
651         return metrics;
652     }
653 
654     /**
655      * Creates a new subpath.
656      * @param x the x
657      * @param y the y
658      */
659     @JsxFunction
660     public void moveTo(final double x, final double y) {
661         getRenderingBackend().moveTo(x, y);
662     }
663 
664     /**
665      * Paints data from the given ImageData object onto the canvas.
666      * @param imageData an ImageData object containing the array of pixel values
667      * @param dx horizontal position (x coordinate) at which to place the image data in the destination canvas
668      * @param dy vertical position (y coordinate) at which to place the image data in the destination canvas
669      * @param dirtyX horizontal position (x coordinate) of the top-left corner
670      *        from which the image data will be extracted. Defaults to 0.
671      * @param dirtyY vertical position (y coordinate) of the top-left corner
672      *        from which the image data will be extracted. Defaults to 0.
673      * @param dirtyWidth width of the rectangle to be painted.
674      *        Defaults to the width of the image data.
675      * @param dirtyHeight height of the rectangle to be painted.
676      *        Defaults to the height of the image data.
677      */
678     @JsxFunction
679     public void putImageData(final ImageData imageData,
680                 final int dx, final int dy, final Object dirtyX, final Object dirtyY,
681                 final Object dirtyWidth, final Object dirtyHeight) {
682         int dirtyXArg = 0;
683         int dirtyYArg = 0;
684         int dirtyWidthArg = imageData.getWidth();
685         int dirtyHeightArg = imageData.getHeight();
686 
687         if (!JavaScriptEngine.isUndefined(dirtyX)) {
688             dirtyXArg = (int) JavaScriptEngine.toInteger(dirtyX);
689 
690             if (JavaScriptEngine.isUndefined(dirtyY)
691                     || JavaScriptEngine.isUndefined(dirtyWidth)
692                     || JavaScriptEngine.isUndefined(dirtyHeight)) {
693                 throw JavaScriptEngine.reportRuntimeError(
694                         "CanvasRenderingContext2D.putImageData() failed - seven parameters expected");
695             }
696             dirtyYArg = (int) JavaScriptEngine.toInteger(dirtyY);
697             dirtyWidthArg = (int) JavaScriptEngine.toInteger(dirtyWidth);
698             dirtyHeightArg = (int) JavaScriptEngine.toInteger(dirtyHeight);
699         }
700 
701         getRenderingBackend().putImageData(
702                 imageData.getData().getBuffer().getByteBuffer(), imageData.getWidth(), imageData.getHeight(),
703                 dx, dy, dirtyXArg, dirtyYArg, dirtyWidthArg, dirtyHeightArg);
704     }
705 
706     /**
707      * Draws a quadratic Bézier curve.
708      * @param controlPointX the x-coordinate of the control point
709      * @param controlPointY the y-coordinate of the control point
710      * @param endPointX the x-coordinate of the end point
711      * @param endPointY the y-coordinate of the end point
712      */
713     @JsxFunction
714     public void quadraticCurveTo(final double controlPointX, final double controlPointY,
715             final double endPointX, final double endPointY) {
716         getRenderingBackend().quadraticCurveTo(controlPointX, controlPointY, endPointX, endPointY);
717     }
718 
719     /**
720      * Renders a rectangle.
721      * @param x the x
722      * @param y the y
723      * @param w the width
724      * @param h the height
725      */
726     @JsxFunction
727     public void rect(final double x, final double y, final double w, final double h) {
728         getRenderingBackend().rect(x, y, w, h);
729     }
730 
731     /**
732      * Pops state stack and restore state.
733      */
734     @JsxFunction
735     public void restore() {
736         getRenderingBackend().restore();
737     }
738 
739     /**
740      * Adds a rotation to the transformation matrix.
741      * @param angle the angle
742      */
743     @JsxFunction
744     public void rotate(final double angle) {
745         getRenderingBackend().rotate(angle);
746     }
747 
748     /**
749      * Pushes state on state stack.
750      */
751     @JsxFunction
752     public void save() {
753         getRenderingBackend().save();
754     }
755 
756     /**
757      * Changes the transformation matrix to apply a scaling transformation with the given characteristics.
758      * @param x the scale factor in the horizontal direction
759      * @param y the scale factor in the vertical direction
760      */
761     @JsxFunction
762     public void scale(final Object x, final Object y) {
763         LOG.info("CanvasRenderingContext2D.scale() not yet implemented");
764     }
765 
766     /**
767      * Dummy placeholder.
768      */
769     @JsxFunction
770     public void setLineDash() {
771         LOG.info("CanvasRenderingContext2D.setLineDash() not yet implemented");
772     }
773 
774     /**
775      * Resets (overrides) the current transformation to the identity matrix,
776      * and then invokes a transformation described by the arguments of this method.
777      * This lets you scale, rotate, translate (move), and skew the context.
778      * @param m11 Horizontal scaling. A value of 1 results in no scaling
779      * @param m12 Vertical skewing
780      * @param m21 Horizontal skewing
781      * @param m22 Vertical scaling. A value of 1 results in no scaling
782      * @param dx Horizontal translation (moving)
783      * @param dy Vertical translation (moving).
784      */
785     @JsxFunction
786     public void setTransform(final double m11, final double m12,
787                     final double m21, final double m22, final double dx, final double dy) {
788         getRenderingBackend().setTransform(m11, m12, m21, m22, dx, dy);
789     }
790 
791     /**
792      * Calculates the strokes of all the subpaths of the current path.
793      */
794     @JsxFunction
795     public void stroke() {
796         getRenderingBackend().stroke();
797     }
798 
799     /**
800      * Strokes the specified rectangular area.
801      * @param x the x
802      * @param y the y
803      * @param w the width
804      * @param h the height
805      */
806     @JsxFunction
807     public void strokeRect(final double x, final double y, final double w, final double h) {
808         getRenderingBackend().strokeRect(x, y, w, h);
809     }
810 
811     /**
812      * Dummy placeholder.
813      */
814     @JsxFunction
815     public void strokeText() {
816         LOG.info("CanvasRenderingContext2D.strokeText() not yet implemented");
817     }
818 
819     /**
820      * Multiplies the current transformation with the matrix described by the
821      * arguments of this method. This lets you scale, rotate, translate (move),
822      * and skew the context.
823      * @param m11 Horizontal scaling. A value of 1 results in no scaling
824      * @param m12 Vertical skewing
825      * @param m21 Horizontal skewing
826      * @param m22 Vertical scaling. A value of 1 results in no scaling
827      * @param dx Horizontal translation (moving)
828      * @param dy Vertical translation (moving).
829      */
830     @JsxFunction
831     public void transform(final double m11, final double m12,
832                     final double m21, final double m22, final double dx, final double dy) {
833         getRenderingBackend().transform(m11, m12, m21, m22, dx, dy);
834     }
835 
836     /**
837      * Changes the transformation matrix to apply a translation transformation with the given characteristics.
838      * @param x the translation distance in the horizontal direction
839      * @param y the translation distance in the vertical direction
840      */
841     @JsxFunction
842     public void translate(final double x, final double y) {
843         getRenderingBackend().translate(x, y);
844     }
845 
846     /**
847      * Returns the associated {@link HTMLCanvasElement}.
848      * @return the associated {@link HTMLCanvasElement}
849      */
850     @JsxGetter
851     public HTMLCanvasElement getCanvas() {
852         return canvas_;
853     }
854 
855     /**
856      * Returns the the shape used to join two line segments where they meet.
857      * There are three possible values for this property: "round", "bevel",
858      * and "miter". The default is "miter".
859      *
860      * @return the the shape used to join two line segments
861      */
862     @JsxGetter
863     public String getLineJoin() {
864         switch (getRenderingBackend().getLineJoin()) {
865             case ROUND:
866                 return "round";
867             case BEVEL:
868                 return "bevel";
869             default:
870                 return "miter";
871         }
872     }
873 
874     /**
875      * Sets the {@code lineJoin} property.
876      * @param lineJoin the {@code lineJoin} property value
877      */
878     @JsxSetter
879     public void setLineJoin(final String lineJoin) {
880         switch (lineJoin) {
881             case "round":
882                 getRenderingBackend().setLineJoin(LineJoin.ROUND);
883                 break;
884             case "bevel":
885                 getRenderingBackend().setLineJoin(LineJoin.BEVEL);
886                 break;
887             case "miter":
888                 getRenderingBackend().setLineJoin(LineJoin.MITER);
889                 break;
890             default:
891                 // ignore invalid values per spec
892         }
893     }
894 
895     /**
896      * Returns the the shape used to join two line segments where they meet.
897      * There are three possible values for this property: "round", "bevel",
898      * and "miter". The default is "miter".
899      *
900      * @return the the shape used to join two line segments
901      */
902     @JsxGetter
903     public String getLineCap() {
904         switch (getRenderingBackend().getLineCap()) {
905             case BUTT:
906                 return "butt";
907             case ROUND:
908                 return "round";
909             default:
910                 return "square";
911         }
912     }
913 
914     /**
915      * Sets the {@code lineCap} property.
916      * @param lineCap the {@code lineCap} property value
917      */
918     @JsxSetter
919     public void setLineCap(final String lineCap) {
920         switch (lineCap) {
921             case "butt":
922                 getRenderingBackend().setLineCap(LineCap.BUTT);
923                 break;
924             case "round":
925                 getRenderingBackend().setLineCap(LineCap.ROUND);
926                 break;
927             case "square":
928                 getRenderingBackend().setLineCap(LineCap.SQUARE);
929                 break;
930             default:
931                 // ignore invalid values per spec
932         }
933     }
934 
935     /**
936      * Returns the text alignment used when drawing text. The possible values are
937      * "start", "end", "left", "right" and "center". The default is "start".
938      *
939      * @return the text alignment
940      */
941     @JsxGetter
942     public String getTextAlign() {
943         return getRenderingBackend().getTextAlign().name().toLowerCase(Locale.ROOT);
944     }
945 
946     /**
947      * Sets the {@code textAlign} property; invalid values are ignored.
948      * @param textAlign the {@code textAlign} property value
949      */
950     @JsxSetter
951     public void setTextAlign(final String textAlign) {
952         switch (textAlign) {
953             case "start":
954                 getRenderingBackend().setTextAlign(TextAlign.START);
955                 break;
956             case "end":
957                 getRenderingBackend().setTextAlign(TextAlign.END);
958                 break;
959             case "left":
960                 getRenderingBackend().setTextAlign(TextAlign.LEFT);
961                 break;
962             case "right":
963                 getRenderingBackend().setTextAlign(TextAlign.RIGHT);
964                 break;
965             case "center":
966                 getRenderingBackend().setTextAlign(TextAlign.CENTER);
967                 break;
968             default:
969                 // ignore invalid values per spec
970         }
971     }
972 
973     /**
974      * Returns the text baseline used when drawing text. The possible values are
975      * "top", "hanging", "middle", "alphabetic", "ideographic" and "bottom".
976      * The default is "alphabetic".
977      *
978      * @return the text baseline
979      */
980     @JsxGetter
981     public String getTextBaseline() {
982         return getRenderingBackend().getTextBaseline().name().toLowerCase(Locale.ROOT);
983     }
984 
985     /**
986      * Sets the {@code textBaseline} property; invalid values are ignored.
987      * @param textBaseline the {@code textBaseline} property value
988      */
989     @JsxSetter
990     public void setTextBaseline(final String textBaseline) {
991         switch (textBaseline) {
992             case "top":
993                 getRenderingBackend().setTextBaseline(TextBaseline.TOP);
994                 break;
995             case "hanging":
996                 getRenderingBackend().setTextBaseline(TextBaseline.HANGING);
997                 break;
998             case "middle":
999                 getRenderingBackend().setTextBaseline(TextBaseline.MIDDLE);
1000                 break;
1001             case "alphabetic":
1002                 getRenderingBackend().setTextBaseline(TextBaseline.ALPHABETIC);
1003                 break;
1004             case "ideographic":
1005                 getRenderingBackend().setTextBaseline(TextBaseline.IDEOGRAPHIC);
1006                 break;
1007             case "bottom":
1008                 getRenderingBackend().setTextBaseline(TextBaseline.BOTTOM);
1009                 break;
1010             default:
1011                 // ignore invalid values per spec
1012         }
1013     }
1014 }