我想在Polymer Element中的画布上绘制一个形状。问题是我在初始化自定义元素之前运行画布绘图代码。我尝试了ready
函数,但它仍无效。
这是我的元素代码:
<link rel="import" href="../../bower_components/polymer/polymer-element.html">
<dom-module id="draw-section">
<template>
<style>
.left{position:absolute;
overflow:hidden;
width: calc(100vw - 300px);
height: calc(100vh - 48px);
}
.right{
width: 300px;
height: 100%;
overflow: hidden;
float: right;
}
.right-container{
padding: 14px;
}
#myCanvas{
background: #fafafa;
}
</style>
<canvas class="left" id="myCanvas" width="300" height="300"></canvas>
<div class="right">
<div class="right-container">
Right Container
</div>
</div>
</template>
<script>
class DrawSection extends Polymer.Element {
static get is() {
return 'draw-section';
}
ready() {
super.ready();
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
}
}
window.customElements.define(DrawSection.is, DrawSection);
</script>
</dom-module>
如果我运行此代码,则会出现错误消息:
Uncaught TypeError: Cannot read property 'getContext' of null
at HTMLElement.ready (draw-section.html:40)
at HTMLElement._enableProperties (property-accessors.html:531)
at HTMLElement.connectedCallback (element-mixin.html:630)
at HTMLElement._attachDom (element-mixin.html:690)
at HTMLElement._readyClients (element-mixin.html:663)
at HTMLElement._flushClients (property-effects.html:1518)
at HTMLElement._propertiesChanged (property-effects.html:1644)
at HTMLElement._flushProperties (property-accessors.html:549)
at HTMLElement.ready (property-effects.html:1606)
at HTMLElement.ready (element-mixin.html:649)
是否可以在Polymer Element内的画布上绘图?我是Polymer的新手,我没有多少经验。
答案 0 :(得分:2)
document.getElementById用于访问你的dom元素。 你需要使用这个。$来获取元素
获取画布是你可以使用:
this.$["myCanvas"]
而不是:
document.getElementById("myCanvas")