使用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>
相关推荐
Martina_03211 小时前
AI生成3D场景的霓虹灯一开就糊成光团?用6步检查Emissive、Bloom与曝光
人工智能·3d·ai·自然语言处理·游戏引擎·材质·贴图
子兮曰3 小时前
Chrome 权限元素实战:144 与 151 的渐进增强写法
前端·javascript·chrome
强尼银手3 小时前
我花一天做了个格斗游戏原型,判定全对,然后被「美术」劝退了
前端·javascript
总要学点什么5 小时前
第98篇:三维特效-材质线效果——给一条线换十种材质,虚线的图案只填了一半
开发语言·前端·javascript·ecmascript·gis·webgl·材质
OpsEye5 小时前
混合云 AI 架构,如何统一做敏感内容拦截?
javascript·ai编程
Funlang7 小时前
给机器写的 JavaScript 造个笼子
开发语言·javascript·ecmascript
古茗前端团队7 小时前
由 key 引发的思考
前端·javascript·react.js
kyriewen8 小时前
我扫了 422 个仓库,近一半 CI 在裸装依赖
前端·javascript·程序员
vipxieliang12 小时前
JavaScript 迭代器与生成器:控制异步与惰性求值
前端·javascript
Hilaku12 小时前
Event Loop 这篇你看完就不用再看别的了!
前端·javascript·程序员