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

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


基于软件渲染原理的代码

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)



    
    
    
    ColorRect
    


    
    


基于canvas的代码

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);  



    
    
    
    Document
    


    
    

你可能感兴趣的:(网站,ui组件研究,javascript,游戏引擎,godot)