gpt4 book ai didi

javascript - 无法使用 Javascript 访问 Polymer 自定义元素内的 Canvas 元素

转载 作者:数据小太阳 更新时间:2023-10-29 04:07:06 25 4
gpt4 key购买 nike

我正在使用 Google 的 Polymer-Project Web-Components Library。我想构建一个包含 Canvas 元素的自定义标签,并通过 javascript 从自定义元素中访问它。但我无法使用 document.querySelector 或 document.getElementById 访问它 - 对类似问题的任何提示或经验表示赞赏。

这是我的来源:

<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>

console.log 输出总是返回一个 NULL/空集合,这与我在生命周期的哪一部分尝试调用 Canvas 无关。我的错误在哪里,我做错了什么?

最好的问候,卢波

最佳答案

document.getElementsByTagName('canvas')document.querySelector('.leinwand') 正在主文档中寻找节点。您想在元素的影子 dom 中查询:

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

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

我正在使用 Polymer 的 automatic node finding对于第一个例子。第二个显示了如何使用 this.shadowRoot 来“限定”shadow dom 中的 qS/qSA。

演示:http://jsbin.com/bogorose/1/edit

关于javascript - 无法使用 Javascript 访问 Polymer 自定义元素内的 Canvas 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24306771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com