Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access Canvas Element inside Polymer custom-element with Javascript

i am playing around with the Polymer-Project Web-Components Library from Google. I want to build a custom-tag with an canvas element included and access it from within the custom-element via javascript. but i just cant access it with document.querySelector or document.getElementById - any hint or experience with a similar problem is appreciated.

Here's my source:

<polymer-element name="sprite-canvas">
<template>
<style>
.leinwand {
 width:200px;
 height:200px;
 background-color: lightblue;
 }
 </style>
<canvas class="leinwand" width="200" height="200"></canvas>
</template>
<script>

Polymer('sprite-canvas', {
leinwand : null,
ready: function() {  
console.log(document.getElementsByTagName('canvas'));
console.log(document.querySelector('.leinwand'));
},
domReady: function() {
console.log(document.getElementsByTagName('canvas'));
console.log(document.querySelector('.leinwand'));
},
detached: function() { },
});
</script>    

The console.log output always returns a NULL / empty collection, doesnt matter at which part of the life-cycle i try to call the canvas. Where's my mistake and what am i doing wrong?

Best regards, Lupo

like image 561
Lupo Avatar asked Jun 19 '14 12:06

Lupo


1 Answers

document.getElementsByTagName('canvas') and document.querySelector('.leinwand') are looking for nodes in the main document. You want to query inside your element's shadow dom:

<canvas id="c" class="leinwand" width="200" height="200"></canvas>

console.log(this.$.c);
console.log(this.shadowRoot.querySelector('.leinwand'));

I'm using Polymer's automatic node finding for the first example. The second shows how you can use this.shadowRoot to "scope" qS/qSA inside the shadow dom.

Demo: http://jsbin.com/bogorose/1/edit

like image 191
ebidel Avatar answered Sep 24 '22 04:09

ebidel