使用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>
相关推荐
Hilaku几秒前
工作 5 年后,决定你薪资上限的究竟是什么?
前端·javascript·程序员
weixin_BYSJ198713 分钟前
springboot校园自习室管理小程序---附源码32142
java·javascript·spring boot·python·django·flask·php
gis开发之家1 小时前
《Vue3 从入门到大神40篇》Vue3 源码详解(十):diff 算法全解析 —— 为什么 Vue3 比 Vue2 更快?
javascript·算法·typescript·前端框架·vue3·vue3源码
海带紫菜菠萝汤2 小时前
WebCodecs API 实战:浏览器原生视频编解码的原理与性能测试
前端·javascript·音视频·视频编解码
前端炒粉4 小时前
简易实现ssr
开发语言·前端·javascript
meilindehuzi_a5 小时前
Node.js + LangChain.js + Milvus 实战:从 EPUB 入库到《天龙八部》RAG 问答系统
javascript·langchain·node.js
勇往直前plus5 小时前
Vue3(篇四)单页面应用到路由管理
javascript·typescript·前端框架·vue
Python私教7 小时前
Godot 4 CharacterBody2D 角色移动:输入、碰撞与八方向控制实战
人工智能·游戏引擎·godot·gdscript·游戏开发
不简说7 小时前
JS 代码技巧 vol.9 — 20 个设计模式在真实项目里的应用
前端·javascript·github
勇往直前plus7 小时前
Vue3(篇三) Element Plus
前端·javascript·typescript·vue