当我使用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;
}
}
型
3条答案
按热度按时间sc4hvdpw1#
当创建
Rectangle
类(new Rectangle("green")
)的示例时,Rectangle
构造函数调用BaseShape
构造函数,后者调用Shape
构造函数 *,不带参数 *(因此ctx
变为undefined
),后者调用Rectangle.prototype.draw()
方法。因为ctx
是undefined
,所以会得到一个错误。wlp8pajw2#
不应将上下文保存到对象。我会把它传递给
draw
方法。Java的JComponent.paintComponent
方法接受一个Graphics
参数。因此,在JavaScript中,您应该将
CanvasRenderingContext2D
传递到draw方法中。我在下面提供了正方形和三角形等示例形状。
个字符
nzk0hqpo3#
使用ES6新语法和特性:写一个脚本来创建不同的形状(矩形,正方形,圆形),使它们都从形状类继承。a.每个形状包含两个函数来计算其面积和其参数。B.通过重写toString()在控制台中显示区域和每个对象参数。c.在外部文件中创建类,并将其导入到模块中以创建对象。