【问题标题】:ctx in javascript canvas is undefinedjavascript canvas 中的 ctx 未定义
【发布时间】:2021-06-09 18:28:15
【问题描述】:

我正在尝试写一些东西来制作康托集的不同迭代。我复制并删除了一些代码,但我不明白为什么会出现这个未定义的错误。

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
    border:1px solid #d3d3d3;
    background-color: #f1f1f1;
    padding-left: 0;
    padding-right: 0;
    margin-left: auto;
    margin-right: auto;
    display: block;
}
</style>
</head>
<body onload="startGame()">

<script>
//var n=10;

function startGame() {
    sheet.start();
   
}

var sheet = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 726;
        this.canvas.height = 680;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
    }
}


    ctx = sheet.context;    
    ctx.beginPath();
    ctx.moveTo(0,0);
    ctx.lineTo(100,100);
    ctx.stroke();
    

</script>
</body>
</html>

但我有一个非常相似的代码示例,它不会让我发布,因为它说它主要是代码。但是我们将不胜感激,因为这个 ctx undefined 是我经常遇到的一个错误,而且我不太确定这意味着什么。我一直用它在画布上画东西,从不关心了解它的含义。

【问题讨论】:

  • 您需要向我们展示您的代码,我们无法通过读心术来调试它。
  • 它不让我发布它,因为它说它主要是代码

标签: javascript html canvas html5-canvas


【解决方案1】:

简答

ctx 未定义,因为对象 sheet 没有名为 context 的属性。

因此ctx = sheet.context; 将失败。

稍长一点的回答

var sheet = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 726;
        this.canvas.height = 680;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
    }
}

您正在声明一个具有两个属性的对象:canvasstart。一旦您在对象上调用 start() 函数,它就会尝试将其 canvas 属性的宽度设置为 726 - 问题是,工作表之前不会调用它自己的属性 canvas,因此 document.createElement("canvas") 永远不会执行。

解决方法很简单:最初将 canvas 设置为 undefined,然后在 start 函数中创建实际的 canvas 元素。尽管如此,您仍然没有上下文属性,因此也将其添加到工作表对象中。

这是一个例子:

var sheet = {
  canvas: undefined,
  context: undefined,
  start: function() {
    this.canvas = document.createElement("canvas");
    this.canvas.width = 200;
    this.canvas.height = 200;
    this.context = this.canvas.getContext("2d");
    document.body.insertBefore(this.canvas, document.body.childNodes[0]);
  }
}

sheet.start();

var ctx = sheet.context;
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.stroke();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-21
    • 1970-01-01
    相关资源
    最近更新 更多