使用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>
相关推荐
IT乐手1 小时前
Claude Code + Qwen 的配置方法
javascript·claude
子兮曰3 小时前
DeepSeek TUI:原生 Rust 打造的终端 AI 编码 Agent
前端·javascript·后端
暗不需求3 小时前
# 深入 React Todos:从零实现一个状态提升与本地持久化的待办应用
javascript·react.js·全栈
子兮曰3 小时前
深入 Superpowers:180k Stars 的开源 AI 编程方法论是如何工作的
前端·javascript·后端
隔壁的大叔3 小时前
Markdown 渲染如何穿插自定义组件
前端·javascript·vue.js
薯老板4 小时前
JavaScript原型,原型链
javascript
愚者Pro4 小时前
Flutter基础学习
前端·javascript·vue.js
时光足迹5 小时前
Tiptap 简单编辑器模版
前端·javascript·react.js
吴声子夜歌5 小时前
Vue3——使用Mock.js
javascript·vue·mock.js
时光足迹5 小时前
ThreeJS之GUI控制器
前端·javascript·three.js