gpt4 book ai didi

javascript - 是否可以在元素内的 Canvas 上绘制?

转载 作者:行者123 更新时间:2023-11-30 15:00:23 26 4
gpt4 key购买 nike

我想在我的 polymer 元素内的 Canvas 上绘制一个形状。问题是我在初始化自定义元素之前运行了 Canvas 绘图代码。我尝试了 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 内的 Canvas 上绘图?我是 Polymer 的新手,没有太多经验。

最佳答案

document.getElementById 用于访问您的 dom 之外的元素。你需要使用 this.$ 来获取元素

要获取 Canvas ,您可以使用:

this.$["myCanvas"]

代替:

document.getElementById("myCanvas")

关于javascript - 是否可以在元素内的 Canvas 上绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46619330/

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