使用js原生customElements.define()API 实现类似godot游戏引擎的colorRect类

一共有两个方案,一个是基于div和css的dom渲染,一个是基于canvas的硬件绘图


基于软件渲染原理的代码

javascript 复制代码
class ColorRect extends HTMLElement
{
    constructor()
    {
        super()
    }
    connectedCallback()
    {
        // 请修改参数
        this.style.display = "inline-block"
        this.style.backgroundColor = "blue"
        this.style.width = "100px"
        this.style.height = "80px"
    }

}
customElements.define("color-rect",ColorRect)
html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ColorRect</title>
    <script src="ColorRectComponent.js"></script>
</head>
<body>
    <!-- 请在js进行方块大小和颜色的赋值 -->
    <color-rect></color-rect>
</body>
</html>

基于canvas的代码

javascript 复制代码
class ColorRect extends HTMLElement {
    constructor() {
      super();
      this.canvas = document.createElement("canvas");
    }
  
    connectedCallback() {
      this.appendChild(this.canvas);
  
      // 设置canvas的样式和属性
      this.canvas.style.display = "inline-block";
      this.canvas.style.backgroundColor = "blue";
      this.canvas.width = 100;
      this.canvas.height = 80;
  
      // 在canvas上绘制内容
      const ctx = this.canvas.getContext("2d");
      ctx.fillStyle = "black";
      ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    }
  }
  
  customElements.define("color-rect", ColorRect);  
html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="ColorRectCanvasComponent.js"></script>
</head>
<body>
    <color-rect></color-rect>
    <!-- <canvas width="100px" height="50px"></canvas> -->
</body>
</html>
相关推荐
wshzd3 小时前
LLM之Agent(104)|DeepSeek-Harness(十三)ReactLoopAgent 总览:kick → turn → step
开发语言·前端·javascript
天天喝旺仔5 小时前
浏览器渲染原理:从解析 HTML/CSS、构建渲染树到重排重绘与首屏优化
前端·javascript·css·性能优化·html
一线灵6 小时前
跨平台游戏引擎 Axmol-2.11.5 发布
游戏引擎·lua
Days20506 小时前
时间胶囊项目正式发布
javascript·gpt·php
淡海水6 小时前
16-01-C#数据结构源码-附录A-术语表
unity·c#·游戏引擎·il2cpp
朱 欢 庆6 小时前
el-table-v2 虚拟表格组件
前端·javascript·vue.js
OpsEye6 小时前
企业大模型用量成本该如何监控和管控?
javascript·ai编程
杨利杰YJlio6 小时前
ITSK 万能驱动 26V5:新驱动批量更新
前端·javascript·后端
y = xⁿ7 小时前
关于Agent智能体开发
开发语言·前端·javascript
淡海水7 小时前
16-03-C#数据结构源码-附录C-参考资源
unity·c#·游戏引擎·il2cpp