【问题标题】:Canvas tag - rectangle not showing up画布标签 - 矩形未显示
【发布时间】:2021-04-02 05:17:35
【问题描述】:

我正在学习画布标签。我尝试了一个简单的想法,即在画布内绘制一个矩形。虽然我可以看到画布,但看不到显示的矩形。我尝试使用 z-index 将我的主画布推到后面。还是什么都没有。

let draw = getElementById('myCanvas');
let ctx = draw.getContext('2d') // creating the rectangle 
ctx.fillStyle = 'grey';
ctx.fillRect(75, 75, 150, 150);
#myCanvas {
  position: fixed;
  top: 0;
  left: 0;
  background-color: black;
  border: 2px solid red;
  z-index: -1
}
<canvas id="myCanvas" width="300" height="300" />

【问题讨论】:

    标签: javascript html css canvas


    【解决方案1】:

    getElementById() 需要 document

    let draw = document.getElementById('myCanvas');

    更多关于getElementById()的信息:W3Schools

    z-index: -1 没有任何影响。此外,在“开发者工具”中打开控制台(单击F12)将有助于您下次调试此错误。

    let draw = document.getElementById('myCanvas');
    let ctx = draw.getContext('2d') // creating the rectangle 
    ctx.fillStyle = 'grey';
    ctx.fillRect(75, 75, 150, 150);
    #myCanvas {
      position: fixed;
      top: 0;
      left: 0;
      background-color: black;
      border: 2px solid red;
      /*z-index: -1*/
    }
    <canvas id="myCanvas" width="300" height="300" />

    【讨论】:

      猜你喜欢
      • 2017-03-08
      • 2021-11-29
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多