未捕获的ReferenceError:未在Chrome的编码上定义draw

时间:2019-01-26 12:55:24

标签: javascript canvas

实际上,我不明白为什么未定义draw。也就是说,我编写了第一个代码,但是没有用,所以我认为我一定犯了错误。所以我在网上学习了一个教程,同样的问题,画图没有定义,然后我用一个示例代码直接在应用程序上移动了三角形并将其放在一个新的白色文件中,甚至在示例文件当然可以完美运行。

这就是我在本教程中使用的代码,它允许您画一条线!

function Line(x0, y0, x1, y1, color) {
  this.x0 = x0;
  this.y0 = y0;
  this.x1 = x1;
  this.y1 = y1;
  this.color = color;
  this.draw = function() {
    draw.line(this.x0, this.y0, this.x1, this.y1, this.color, 3);
  }
}

function randomInt(size) {
  return parseInt(Math.random() * size);
}

var line = new Line(randomInt(500), randomInt(500), 200, 200, 'green');
line.draw();

var x = 300;
var y = 300;

1 个答案:

答案 0 :(得分:2)

我已经重写了draw()方法。

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let cw = canvas.width = 500,
  cx = cw / 2;
let ch = canvas.height = 500,
  cy = ch / 2;



function Line(x0, y0, x1, y1, color) {
  this.x0 = x0;
  this.y0 = y0;
  this.x1 = x1;
  this.y1 = y1;
  this.color = color;
  this.draw = function() {
    ctx.beginPath();
    ctx.strokeStyle = this.color;
    ctx.moveTo(this.x0, this.y0,)
    ctx.lineTo(this.x1, this.y1);
    ctx.stroke();
  }
}

function randomInt(size) {
  return parseInt(Math.random() * size);
}

var line = new Line(randomInt(500), randomInt(500), 200, 200, 'green');
line.draw();
canvas {
  border:1px solid
}
<canvas id="canvas"></canvas>