目前,我有此代码,但在Lab4.js中的s.Draw();
处未绘制形状
我在index.html中有这个:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Лабораторна 4</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<canvas id="canvas"></canvas>
<script src="Lab4.js"></script>
</body>
</html>
在Lab4.js中:
window.addEventListener('load', () => {
const { Shape, EllipseShape } = require("./Shape.js");
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
let s = new EllipseShape(200, 200, 400, 400, 'green', true)
s.Draw();
});
在Shape.js中:
class Shape {
constructror(lastMouseX, lastMouseY, mouseX, mouseY) {
this.lastMouseX = lastMouseX;
this.lastMouseY = lastMouseY;
this.mouseX = mouseX;
this.mouseY = mouseY;
}
}
class EllipseShape extends Shape {
constructor(lastMouseX, lastMouseY, mouseX, mouseY, color, fill) {
super(lastMouseX);
super(lastMouseY);
super(mouseX);
super(mouseY);
this.color = color;
this.fill = fill;
}
Draw() {
const width = this.mouseX - this.lastMouseX;
const height = this.mouseY - this.lastMouseY;
const rw = Math.abs(width / 2);
const rh = Math.abs(height / 2);
const centerX = this.mouseX - width / 2;
const centerY = this.mouseY - height / 2;
ctx.beginPath();
ctx.setLineDash([]);
ctx.ellipse(centerX, centerY, rw, rh, 0, 0, 2 * Math.PI);
ctx.strokeStyle = 'black';
ctx.lineWidth = 5;
ctx.stroke();
if (this.fill = true) {
ctx.fillStyle = this.color;
ctx.fill();
}
}
}
module.exports = Shape, EllipseShape;
最佳答案
我相信ctx
在Lab4.js中未全局设置,因此在Shape.js中使用ctx
不能按预期工作。在尝试绘制椭圆的窗口中查看是否可以阅读任何控制台消息(Richt单击>检查>控制台选项卡),它应该尝试告诉您ctx
未定义。
关于javascript - 使用类的HTML5 Canvas形状(需要Node.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59429317/