javascript - 使用类的HTML5 Canvas形状(需要Node.js)

标签 javascript node.js html5-canvas electron

目前,我有此代码,但在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/

相关文章:

javascript - Node/Tedious 未触发 "done"事件

javascript - Dojo 本地化 - 当本地化字符串包含单引号时,data-dojo-props 失败

javascript - 内容太长,如何在console.log()中显示完整的内容?

node.js - 由于releaseStage/notifyReleaseStages配置而未发送报告

javascript - 用于匹配有效 JavaScript 命名空间的正则表达式

javascript - 数据表排序数字无法正常工作

node.js - 如何将 node-webkit 与快速服务器一起使用?

javascript - HTML5 - createPattern(..) - 动态位置(x,y)

javascript - 绘图应用程序 - 通过单击工具更改光标

javascript - 始终将 Canvas 形状显示在另一个形状之上