使用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>
相关推荐
七号练习生.c9 分钟前
JavaScript基础入门
开发语言·javascript·ecmascript
baozj32 分钟前
🚀 手动改 500 个文件?不存在的!我用 AST 撸了个 Vue 国际化神器
前端·javascript·vue.js
molly cheung1 小时前
FetchAPI 请求流式数据 基本用法
javascript·fetch·请求取消·流式·流式数据·流式请求取消
Mintopia2 小时前
🧠 量子计算对AIGC的潜在影响:Web技术的未来可能性
前端·javascript·aigc
忧郁的蛋~2 小时前
.NET异步编程中内存泄漏的终极解决方案
开发语言·前端·javascript·.net
水月wwww2 小时前
vue学习之组件与标签
前端·javascript·vue.js·学习·vue
顾安r2 小时前
11.8 脚本网页 塔防游戏
服务器·前端·javascript·游戏·html
爱吃甜品的糯米团子3 小时前
JavaScript 正则表达式:选择、分组与引用深度解析
前端·javascript·正则表达式
星尘库4 小时前
抖音自动化-实现给特定用户发私信
前端·javascript·自动化
Jonathan Star4 小时前
Next.js、NestJS、Nuxt.js 是 **Node.js 生态中针对不同场景的框架**
开发语言·javascript·node.js