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.html;
16  
17  import static org.htmlunit.BrowserVersionFeatures.JS_CANVAS_DATA_URL_CHROME_PNG;
18  import static org.htmlunit.BrowserVersionFeatures.JS_CANVAS_RESIZE_RESETS_ORIGIN_CLEAN;
19  
20  import org.htmlunit.html.HtmlCanvas;
21  import org.htmlunit.javascript.HtmlUnitScriptable;
22  import org.htmlunit.javascript.JavaScriptEngine;
23  import org.htmlunit.javascript.configuration.JsxClass;
24  import org.htmlunit.javascript.configuration.JsxConstructor;
25  import org.htmlunit.javascript.configuration.JsxFunction;
26  import org.htmlunit.javascript.configuration.JsxGetter;
27  import org.htmlunit.javascript.configuration.JsxSetter;
28  import org.htmlunit.javascript.host.canvas.CanvasRenderingContext2D;
29  import org.htmlunit.javascript.host.dom.DOMException;
30  
31  /**
32   * The JavaScript object {@code HTMLCanvasElement}.
33   *
34   * @author Ahmed Ashour
35   * @author Ronald Brill
36   * @author Frank Danek
37   *
38   * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement">MDN Documentation</a>
39   */
40  @JsxClass(domClass = HtmlCanvas.class)
41  public class HTMLCanvasElement extends HTMLElement {
42  
43      private CanvasRenderingContext2D context2d_;
44      // false as soon as cross-origin data was drawn into the canvas; see resetBitmap()
45      private boolean originClean_ = true;
46  
47      /**
48       * JavaScript constructor.
49       */
50      @Override
51      @JsxConstructor
52      public void jsConstructor() {
53          super.jsConstructor();
54      }
55  
56      /**
57       * Returns the {@code width} property.
58       * @return the {@code width} property
59       */
60      @JsxGetter
61      public int getWidth() {
62          final String value = getDomNodeOrDie().getAttributeDirect("width");
63          final Integer intValue = getValue(value);
64          if (intValue != null) {
65              return intValue;
66          }
67          return 300;
68      }
69  
70      static Integer getValue(final String value) {
71          int index = -1;
72          while (index + 1 < value.length() && Character.isDigit(value.charAt(index + 1))) {
73              index++;
74          }
75          if (index != -1) {
76              return Integer.parseInt(value.substring(0, index + 1));
77          }
78          return null;
79      }
80  
81      /**
82       * Sets the {@code width} property.
83       * @param width the {@code width} property value
84       */
85      @JsxSetter
86      public void setWidth(final int width) {
87          getDomNodeOrDie().setAttribute("width", Integer.toString(width));
88      }
89  
90      /**
91       * Returns the {@code height} property.
92       * @return the {@code height} property
93       */
94      @JsxGetter
95      public int getHeight() {
96          final String value = getDomNodeOrDie().getAttributeDirect("height");
97          final Integer intValue = getValue(value);
98          if (intValue != null) {
99              return intValue;
100         }
101         return 150;
102     }
103 
104     /**
105      * Sets the {@code height} property.
106      * @param height the {@code height} property value
107      */
108     @JsxSetter
109     public void setHeight(final int height) {
110         getDomNodeOrDie().setAttribute("height", Integer.toString(height));
111     }
112 
113     /**
114      * Resets the bitmap after the width or height attribute was set (also to the current value).
115      * Like the browsers, the bitmap is cleared and the drawing state of the context is reset.
116      * <p>Chrome and Edge reset the origin-clean flag also; there is no cross-origin content
117      * left. Firefox keeps the flag. Resetting the flag without clearing the bitmap would make
118      * the old (cross-origin) content readable again, therefore both are done here.</p>
119      */
120     public void resetBitmap() {
121         if (context2d_ != null) {
122             context2d_.resetBitmap();
123         }
124         if (getBrowserVersion().hasFeature(JS_CANVAS_RESIZE_RESETS_ORIGIN_CLEAN)) {
125             originClean_ = true;
126         }
127     }
128 
129     /**
130      * Gets the context.
131      * @param contextId the context id
132      * @return an object that exposes an API for drawing on the canvas,
133      *         or null if the given context ID is not supported
134      */
135     @JsxFunction
136     public HtmlUnitScriptable getContext(final String contextId) {
137         if ("2d".equals(contextId)) {
138             if (context2d_ == null) {
139                 final CanvasRenderingContext2D context = new CanvasRenderingContext2D(this);
140                 context.setParentScope(getParentScope());
141                 context.setPrototype(getPrototype(context.getClass()));
142                 context2d_ = context;
143             }
144             return context2d_;
145         }
146         return null;
147     }
148 
149     /**
150      * Returns the origin-clean flag of the canvas. The flag is set to false if cross-origin
151      * data (e.g. an image of another origin) is drawn into the canvas; the content of such
152      * a canvas can't be read back by script.
153      *
154      * @return the origin-clean flag
155      * @see <a href="https://html.spec.whatwg.org/multipage/canvas.html#security-with-canvas-elements">
156      *     HTML Living Standard - Security with canvas elements</a>
157      */
158     public boolean isOriginClean() {
159         return originClean_;
160     }
161 
162     /**
163      * Sets the origin-clean flag of the canvas to false (cross-origin data was drawn into
164      * the canvas). Depending on the browser, setting the size of the canvas resets the
165      * flag (see {@link #resetBitmap()}).
166      */
167     public void setOriginCleanFalse() {
168         originClean_ = false;
169     }
170 
171     /**
172      * Gets the data: URL representation of the canvas element.
173      * Here we return an empty image.
174      * @param type the type (optional)
175      * @return the data URL
176      */
177     @JsxFunction
178     public String toDataURL(final Object type) {
179         if (!originClean_) {
180             throw JavaScriptEngine.asJavaScriptException(this,
181                     "Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.",
182                     DOMException.SECURITY_ERR);
183         }
184 
185         if (context2d_ != null) {
186             final String typeInUse;
187             if (JavaScriptEngine.isUndefined(type)) {
188                 typeInUse = null;
189             }
190             else {
191                 typeInUse = JavaScriptEngine.toString(type);
192             }
193             return context2d_.toDataURL(typeInUse);
194         }
195 
196         if (getBrowserVersion().hasFeature(JS_CANVAS_DATA_URL_CHROME_PNG)) {
197             return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAEYklEQVR4Xu3UAQkAAAwCwdm/"
198                 + "9HI83BLIOdw5AgQIRAQWySkmAQIEzmB5AgIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYO"
199                 + "VqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1"
200                 + "OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamK"
201                 + "kEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWC"
202                 + "EiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCV"
203                 + "AwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgI"
204                 + "DB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg"
205                 + "+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbL"
206                 + "DxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8"
207                 + "gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QI"
208                 + "BARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAg"
209                 + "YyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZ"
210                 + "AYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgI"
211                 + "GK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDF"
212                 + "amKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlACBB1YxAJfjJb2jA"
213                 + "AAAAElFTkSuQmCC";
214         }
215 
216         return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAAxUlEQVR4nO3BMQEAAADCoPVPbQhf"
217             + "oAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
218             + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
219             + "AAAAAAAAAAAAAAAAAAAAAAAAAAAOA1v9QAATX68/0AAAAASUVORK5CYII=";
220     }
221 }