2

I want create my own element inherited canvas with dart.

Here is my HTML code:

 <x-canvas> </x-canvas>

Here is my DART code:

class XCanvas extends HtmlElement with CanvasElement{

    int myOwnProperty = 1;

    XCanvas.created() : super.created(){

    }

}

void main(){
    document.registerElement("x-canvas", XCanvas);

    var ctx = query("x-canvas").getContext('2d'); // ctx from x-canvas element
}

The occured error:

main.dart:23 Exception: 'package:mypackage/main.dart': error: line 38 pos 2: constructor 'CanvasElement.internal_' is illegal in mixin class CanvasElement
}
 ^
'package:mypackage/main.dart': error: line 11 pos 37: mixin class 'CanvasElement' must not have constructors
class XCanvas extends HtmlElement with CanvasElement{
                                ^
Chr
  • 184
  • 13

1 Answers1

4

The class for the custom element should be

import 'dart:html';

class XCanvas extends CanvasElement{
  int myOwnProperty = 1;

  XCanvas.created() : super.created();
}

and register it with

document.registerElement("x-canvas", XCanvas, extendsTag: 'canvas');

To create an instance use

<canvas is="x-canvas"></canvas>

or

var anchor = querySelector('#anchor');
anchor.append(new Element.tag('canvas', 'x-canvas'));

See also

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 2
    I upvoted your already-great answer but I just wanted to add that the reason the `is` syntax is necessary is because `` is a [replaced element](https://developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element). – Patrick Roberts Aug 31 '17 at 07:39
  • @PatrickRoberts thanks :) Are you sure? As far as I know the `is` is required if you depend on the implementation of a specific native tag, like the ` – Günter Zöchbauer Aug 31 '17 at 07:43
  • I can't recall where I read it, but I suspect it was in a github discussion of the specification for web components before it was finalized, so it might not be entirely accurate, but my understanding was that if you inherited from an element that wasn't replaced, you did not need to use the `is` syntax. I was not aware it simply inherited the implementation from `
    `.
    – Patrick Roberts Aug 31 '17 at 07:45
  • `
    ` might not be 100% accurate from a technical point of view, the default behavior is **just like a** `
    ` element with a different tag name (they could also just extend the same internal class or similar). I know for sure that you need `is` for input elements like `
    – Günter Zöchbauer Aug 31 '17 at 07:50
  • 1
    I just checked [the specification](https://html.spec.whatwg.org/multipage/custom-elements.html#custom-elements-customized-builtin-example). According to it, by default a custom element without the `is` syntax simply inherits functionality from `HTMLElement`. – Patrick Roberts Aug 31 '17 at 07:50