当我使用console.log()
时,我会得到画布的上下文。
但是,当我在我的Rectangle类moveTo(10,10)
中使用时;我得到ctx is undefined
。
我怎样才能让它发挥作用?
class Shape {
constructor(ctx) {
this.draw(ctx);
}
draw(ctx) {
this.ctx = ctx;
}
}
class BaseShape extends Shape {
constructor(color) {
super();
this.color = color;
}
}
class Rectangle extends BaseShape {
constructor(color) {
super(color);
}
}
var c = document.getElementById("canvas");
var x = c.getContext("2d");
var rec = new Rectangle("green");
rec.draw(x);
console.log(rec);
矩形类
class Rectangle extends BaseShape {
constructor(color) {
super(color);
}
draw(ctx) {
ctx.moveTo(10, 10);
ctx.lineTo(10, 100);
ctx.stroke();
ctx.strokeStyle = color;
}
}
答案 0 :(得分:1)
当您创建Rectangle
类(new Rectangle("green")
)的实例时,Rectangle
构造函数会调用BaseShape
构造函数,该构造函数会调用Shape
构造函数< em>没有参数(因此ctx
变为undefined
),调用Rectangle.prototype.draw()
方法。由于ctx
为undefined
,您会收到错误。
答案 1 :(得分:1)
您不应将上下文保存到对象。我会将它传递给draw
方法。 Java的JComponent.paintComponent
方法采用Graphics
参数。
因此,在JavaScript中,您应该将CanvasRenderingContext2D
传递给draw方法。
我在下面提供了例如正方形和三角形的示例形状。
class AbstractShape {
constructor(origin) {
this.origin = origin;
}
}
class DrawableShape extends AbstractShape {
constructor(origin, color, fill) {
super(origin);
this.color = color || '#000';
this.fill = fill || '#FFF';
}
draw(ctx) {
ctx.save();
ctx.strokeStyle = this.color;
ctx.fillStyle = this.fill;
ctx.imageSmoothingEnabled = true;
this.onRedraw(ctx);
ctx.restore();
}
}
class Rectangle extends DrawableShape {
constructor(origin, width, height, color, fill) {
super(origin, color, fill);
this.width = width;
this.height = height;
}
onRedraw(ctx) {
ctx.beginPath();
ctx.moveTo(this.origin.x, this.origin.y);
ctx.lineTo(this.origin.x + this.width, this.origin.y);
ctx.lineTo(this.origin.x + this.width, this.origin.y + this.height);
ctx.lineTo(this.origin.x, this.origin.y + this.height);
ctx.lineTo(this.origin.x, this.origin.y);
ctx.fill();
ctx.stroke();
}
}
class Square extends Rectangle {
constructor(origin, size, color, fill) {
super(origin, size, size, color, fill);
}
}
class Triangle extends DrawableShape {
constructor(origin, width, height, color, fill) {
super(origin, color, fill);
this.width = width;
this.height = height;
}
onRedraw(ctx) {
ctx.beginPath();
ctx.moveTo(this.origin.x + this.width / 2, this.origin.y);
ctx.lineTo(this.origin.x + this.width, this.origin.y + this.height);
ctx.lineTo(this.origin.x, this.origin.y + this.height);
ctx.lineTo(this.origin.x + this.width / 2, this.origin.y);
ctx.fill();
ctx.stroke();
}
}
class EquilateralTriangle extends Triangle {
constructor(origin, size, color, fill) {
super(origin, size * 1.1339741, size, color, fill);
}
}
var ctx = document.getElementById('draw').getContext('2d');
var rec = new Rectangle({ x : 10, y : 10 }, 60, 100, '#F00', '#0FF');
var tri = new EquilateralTriangle({ x : 100, y : 10 }, 100, '#00F', '#FF0');
var sqa = new Square({ x : 240, y : 10 }, 100);
rec.draw(ctx);
tri.draw(ctx);
sqa.draw(ctx);
<canvas id="draw" width="400" height="300"></canvas>