」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用 Three.js 的太陽能係統

使用 Three.js 的太陽能係統

發佈於2024-11-04
瀏覽:650

Hi! Today, I’m going to build a solar system using Three.js. But before we begin, you should know that the inspiration for this article came from a client's representative whose project I’m currently working on. Yes, that's you—the one who believes the Earth is flat.

JavaScript/Node has largest ecosystem of libraries that cover enormous amount of feature that simplifies your development, so I always can choose which one is better for you purpose. However If we are talking about 3D graphics there is not that much cool options and three.js is probably the best amoug them all and has the biggest comunity.

So let's dive in Three.js and build the Solar system using it. In this article I will cover:

  • Init Project and Scene
  • Creating Sun
  • Creating Planets
  • Deploying to GitHub Pages

Init Project and Scene

First things first: to initialize the project, I'm using Vite and installing the Three.js dependency. Now, the question is how to set up Three.js. For this, you'll need three things: a scene, a camera, and a renderer. I'm also using the built-in addon, OrbitControls, which allows me to navigate within the scene. After starting the app, a black screen should appear.

import { Scene, WebGLRenderer, PerspectiveCamera } from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";

const w = window.innerWidth;
const h = window.innerHeight;

const scene = new Scene();
const camera = new PerspectiveCamera(75, w / h, 0.1, 100);
const renderer = new WebGLRenderer();
const controls = new OrbitControls(camera, renderer.domElement);

controls.minDistance = 10;
controls.maxDistance = 60;
camera.position.set(30 * Math.cos(Math.PI / 6), 30 * Math.sin(Math.PI / 6), 40);

renderer.setSize(w, h);
document.body.appendChild(renderer.domElement);

renderer.render(scene, camera);

window.addEventListener("resize", () => {
  const w = window.innerWidth;
  const h = window.innerHeight;
  renderer.setSize(w, h);
  camera.aspect = w / h;
  camera.updateProjectionMatrix();
});

const animate = () => {
  requestAnimationFrame(animate);
  controls.update();
  renderer.render(scene, camera);
};

animate();

You may notice that I'm limiting the zoom via controls and also changing the default angle of the camera. This will be helpful for properly displaying the scene in the next steps.

Now it’s time to add a simple starfield since our solar system should be surrounded by stars. To simplify the explanation, imagine you have a sphere, and you pick 1,000 random points on this sphere. Then, you create stars from these points by mapping a star texture onto them. Finally, I’m adding animation to make all these points spin around the y-axis. With this, the starfield is ready to be added to the scene.

import {
  Group,
  Color,
  Points,
  Vector3,
  TextureLoader,
  PointsMaterial,
  BufferGeometry,
  AdditiveBlending,
  Float32BufferAttribute,
} from "three";

export class Starfield {
  group;
  loader;
  animate;

  constructor({ numStars = 1000 } = {}) {
    this.numStars = numStars;

    this.group = new Group();
    this.loader = new TextureLoader();

    this.createStarfield();

    this.animate = this.createAnimateFunction();
    this.animate();
  }

  createStarfield() {
    let col;
    const verts = [];
    const colors = [];
    const positions = [];

    for (let i = 0; i  {
      requestAnimationFrame(this.animate);
      this.group.rotation.y  = 0.00005;
    };
  }

  getStarfield() {
    return this.group;
  }
}

Adding the starfield is easy, just by using add method in scene class

const starfield = new Starfield().getStarfield();
scene.add(starfield);

As for the textures, you can find all the textures used in this project inside the repository, which is linked at the end of the article. Most of the textures were taken from this site, with the exceptions being the star and planets' rings textures.


Creating Sun

For the sun, I used Icosahedron geometry and mapped a texture onto it. Using Improved Noise, I achieved an effect where the sun pulses, simulating the way a real star emits streams of energy into space. The sun isn't just a figure with a mapped texture; it also needs to be a light source in the scene, so I'm using PointLight to simulate this.

import {
  Mesh,
  Group,
  Color,
  Vector3,
  BackSide,
  PointLight,
  TextureLoader,
  ShaderMaterial,
  AdditiveBlending,
  DynamicDrawUsage,
  MeshBasicMaterial,
  IcosahedronGeometry,
} from "three";
import { ImprovedNoise } from "three/addons/math/ImprovedNoise.js";

export class Sun {
  group;
  loader;
  animate;
  corona;
  sunRim;
  glow;

  constructor() {
    this.sunTexture = "/solar-system-threejs/assets/sun-map.jpg";

    this.group = new Group();
    this.loader = new TextureLoader();

    this.createCorona();
    this.createRim();
    this.addLighting();
    this.createGlow();
    this.createSun();

    this.animate = this.createAnimateFunction();
    this.animate();
  }

  createSun() {
    const map = this.loader.load(this.sunTexture);
    const sunGeometry = new IcosahedronGeometry(5, 12);
    const sunMaterial = new MeshBasicMaterial({
      map,
      emissive: new Color(0xffff99),
      emissiveIntensity: 1.5,
    });
    const sunMesh = new Mesh(sunGeometry, sunMaterial);
    this.group.add(sunMesh);

    this.group.add(this.sunRim);

    this.group.add(this.corona);

    this.group.add(this.glow);

    this.group.userData.update = (t) => {
      this.group.rotation.y = -t / 5;
      this.corona.userData.update(t);
    };
  }

  createCorona() {
    const coronaGeometry = new IcosahedronGeometry(4.9, 12);
    const coronaMaterial = new MeshBasicMaterial({
      color: 0xff0000,
      side: BackSide,
    });
    const coronaMesh = new Mesh(coronaGeometry, coronaMaterial);
    const coronaNoise = new ImprovedNoise();

    let v3 = new Vector3();
    let p = new Vector3();
    let pos = coronaGeometry.attributes.position;
    pos.usage = DynamicDrawUsage;
    const len = pos.count;

    const update = (t) => {
      for (let i = 0; i  {
      const time = t * 0.00051;
      requestAnimationFrame(this.animate);
      this.group.userData.update(time);
    };
  }

  getSun() {
    return this.group;
  }
}

Creating Planets

All planets are built using a similar logic: each planet needs an orbit, a texture, an orbit speed, and a rotation speed. For planets that require them, rings should also be added.

import {
  Mesh,
  Color,
  Group,
  DoubleSide,
  RingGeometry,
  TorusGeometry,
  TextureLoader,
  ShaderMaterial,
  SRGBColorSpace,
  AdditiveBlending,
  MeshPhongMaterial,
  MeshBasicMaterial,
  IcosahedronGeometry,
} from "three";

export class Planet {
  group;
  loader;
  animate;
  planetGroup;
  planetGeometry;

  constructor({
    orbitSpeed = 1,
    orbitRadius = 1,
    orbitRotationDirection = "clockwise",

    planetSize = 1,
    planetAngle = 0,
    planetRotationSpeed = 1,
    planetRotationDirection = "clockwise",
    planetTexture = "/solar-system-threejs/assets/mercury-map.jpg",

    rimHex = 0x0088ff,
    facingHex = 0x000000,

    rings = null,
  } = {}) {
    this.orbitSpeed = orbitSpeed;
    this.orbitRadius = orbitRadius;
    this.orbitRotationDirection = orbitRotationDirection;

    this.planetSize = planetSize;
    this.planetAngle = planetAngle;
    this.planetTexture = planetTexture;
    this.planetRotationSpeed = planetRotationSpeed;
    this.planetRotationDirection = planetRotationDirection;

    this.rings = rings;

    this.group = new Group();
    this.planetGroup = new Group();
    this.loader = new TextureLoader();
    this.planetGeometry = new IcosahedronGeometry(this.planetSize, 12);

    this.createOrbit();
    this.createRings();
    this.createPlanet();
    this.createGlow(rimHex, facingHex);

    this.animate = this.createAnimateFunction();
    this.animate();
  }

  createOrbit() {
    const orbitGeometry = new TorusGeometry(this.orbitRadius, 0.01, 100);
    const orbitMaterial = new MeshBasicMaterial({
      color: 0xadd8e6,
      side: DoubleSide,
    });
    const orbitMesh = new Mesh(orbitGeometry, orbitMaterial);
    orbitMesh.rotation.x = Math.PI / 2;
    this.group.add(orbitMesh);
  }

  createPlanet() {
    const map = this.loader.load(this.planetTexture);
    const planetMaterial = new MeshPhongMaterial({ map });
    planetMaterial.map.colorSpace = SRGBColorSpace;
    const planetMesh = new Mesh(this.planetGeometry, planetMaterial);
    this.planetGroup.add(planetMesh);
    this.planetGroup.position.x = this.orbitRadius - this.planetSize / 9;
    this.planetGroup.rotation.z = this.planetAngle;
    this.group.add(this.planetGroup);
  }

  createGlow(rimHex, facingHex) {
    const uniforms = {
      color1: { value: new Color(rimHex) },
      color2: { value: new Color(facingHex) },
      fresnelBias: { value: 0.2 },
      fresnelScale: { value: 1.5 },
      fresnelPower: { value: 4.0 },
    };

    const vertexShader = `
    uniform float fresnelBias;
    uniform float fresnelScale;
    uniform float fresnelPower;

    varying float vReflectionFactor;

    void main() {
      vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
      vec4 worldPosition = modelMatrix * vec4( position, 1.0 );

      vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );

      vec3 I = worldPosition.xyz - cameraPosition;

      vReflectionFactor = fresnelBias   fresnelScale * pow( 1.0   dot( normalize( I ), worldNormal ), fresnelPower );

      gl_Position = projectionMatrix * mvPosition;
    }
    `;

    const fragmentShader = `
      uniform vec3 color1;
      uniform vec3 color2;

      varying float vReflectionFactor;

      void main() {
        float f = clamp( vReflectionFactor, 0.0, 1.0 );
        gl_FragColor = vec4(mix(color2, color1, vec3(f)), f);
      }
    `;

    const planetGlowMaterial = new ShaderMaterial({
      uniforms,
      vertexShader,
      fragmentShader,
      transparent: true,
      blending: AdditiveBlending,
    });
    const planetGlowMesh = new Mesh(this.planetGeometry, planetGlowMaterial);
    planetGlowMesh.scale.setScalar(1.1);
    this.planetGroup.add(planetGlowMesh);
  }

  createRings() {
    if (!this.rings) return;

    const innerRadius = this.planetSize   0.1;
    const outerRadius = innerRadius   this.rings.ringsSize;

    const ringsGeometry = new RingGeometry(innerRadius, outerRadius, 32);

    const ringsMaterial = new MeshBasicMaterial({
      side: DoubleSide,
      transparent: true,
      map: this.loader.load(this.rings.ringsTexture),
    });

    const ringMeshs = new Mesh(ringsGeometry, ringsMaterial);
    ringMeshs.rotation.x = Math.PI / 2;
    this.planetGroup.add(ringMeshs);
  }

  createAnimateFunction() {
    return () => {
      requestAnimationFrame(this.animate);

      this.updateOrbitRotation();
      this.updatePlanetRotation();
    };
  }

  updateOrbitRotation() {
    if (this.orbitRotationDirection === "clockwise") {
      this.group.rotation.y -= this.orbitSpeed;
    } else if (this.orbitRotationDirection === "counterclockwise") {
      this.group.rotation.y  = this.orbitSpeed;
    }
  }

  updatePlanetRotation() {
    if (this.planetRotationDirection === "clockwise") {
      this.planetGroup.rotation.y -= this.planetRotationSpeed;
    } else if (this.planetRotationDirection === "counterclockwise") {
      this.planetGroup.rotation.y  = this.planetRotationSpeed;
    }
  }

  getPlanet() {
    return this.group;
  }
}

For Earth, I'm extending the Planet class to add extra textures, such as clouds and a night texture for the planet's night side.

import {
  Mesh,
  AdditiveBlending,
  MeshBasicMaterial,
  MeshStandardMaterial,
} from "three";
import { Planet } from "./planet";

export class Earth extends Planet {
  constructor(props) {
    super(props);

    this.createPlanetLights();
    this.createPlanetClouds();
  }

  createPlanetLights() {
    const planetLightsMaterial = new MeshBasicMaterial({
      map: this.loader.load("/solar-system-threejs/assets/earth-map-2.jpg"),
      blending: AdditiveBlending,
    });
    const planetLightsMesh = new Mesh(
      this.planetGeometry,
      planetLightsMaterial
    );
    this.planetGroup.add(planetLightsMesh);

    this.group.add(this.planetGroup);
  }

  createPlanetClouds() {
    const planetCloudsMaterial = new MeshStandardMaterial({
      map: this.loader.load("/solar-system-threejs/assets/earth-map-3.jpg"),
      transparent: true,
      opacity: 0.8,
      blending: AdditiveBlending,
      alphaMap: this.loader.load(
        "/solar-system-threejs/assets/earth-map-4.jpg"
      ),
    });
    const planetCloudsMesh = new Mesh(
      this.planetGeometry,
      planetCloudsMaterial
    );
    planetCloudsMesh.scale.setScalar(1.003);
    this.planetGroup.add(planetCloudsMesh);

    this.group.add(this.planetGroup);
  }
}

By searching on Google for about five minutes, you’ll come across a table with all the necessary values for adding planets to the scene.

Planet Size (diameter) Rotation speed Rotation direction Orbit speed
Mercury 4,880 km 10.83 km/h Counterclockwise 47.87 km/s
Venus 12,104 km 6.52 km/h Clockwise 35.02 km/s
Earth 12,742 km 1674.4 km/h Counterclockwise 29.78 km/s
Mars 6,779 km 866.5 km/h Counterclockwise 24.07 km/s
Jupiter 142,984 km 45,300 km/h Counterclockwise 13.07 km/s
Saturn 120,536 km 35,500 km/h Counterclockwise 9.69 km/s
Uranus 51,118 km 9,320 km/h Clockwise 6.81 km/s
Neptune 49,528 km 9,720 km/h Counterclockwise 5.43 km/s

Now, all the planets and the sun can be added to the scene.

const planets = [
  {
    orbitSpeed: 0.00048,
    orbitRadius: 10,
    orbitRotationDirection: "clockwise",
    planetSize: 0.2,
    planetRotationSpeed: 0.005,
    planetRotationDirection: "counterclockwise",
    planetTexture: "/solar-system-threejs/assets/mercury-map.jpg",
    rimHex: 0xf9cf9f,
  },
  {
    orbitSpeed: 0.00035,
    orbitRadius: 13,
    orbitRotationDirection: "clockwise",
    planetSize: 0.5,
    planetRotationSpeed: 0.0005,
    planetRotationDirection: "clockwise",
    planetTexture: "/solar-system-threejs/assets/venus-map.jpg",
    rimHex: 0xb66f1f,
  },
  {
    orbitSpeed: 0.00024,
    orbitRadius: 19,
    orbitRotationDirection: "clockwise",
    planetSize: 0.3,
    planetRotationSpeed: 0.01,
    planetRotationDirection: "counterclockwise",
    planetTexture: "/solar-system-threejs/assets/mars-map.jpg",
    rimHex: 0xbc6434,
  },
  {
    orbitSpeed: 0.00013,
    orbitRadius: 22,
    orbitRotationDirection: "clockwise",
    planetSize: 1,
    planetRotationSpeed: 0.06,
    planetRotationDirection: "counterclockwise",
    planetTexture: "/solar-system-threejs/assets/jupiter-map.jpg",
    rimHex: 0xf3d6b6,
  },
  {
    orbitSpeed: 0.0001,
    orbitRadius: 25,
    orbitRotationDirection: "clockwise",
    planetSize: 0.8,
    planetRotationSpeed: 0.05,
    planetRotationDirection: "counterclockwise",
    planetTexture: "/solar-system-threejs/assets/saturn-map.jpg",
    rimHex: 0xd6b892,
    rings: {
      ringsSize: 0.5,
      ringsTexture: "/solar-system-threejs/assets/saturn-rings.jpg",
    },
  },
  {
    orbitSpeed: 0.00007,
    orbitRadius: 28,
    orbitRotationDirection: "clockwise",
    planetSize: 0.5,
    planetRotationSpeed: 0.02,
    planetRotationDirection: "clockwise",
    planetTexture: "/solar-system-threejs/assets/uranus-map.jpg",
    rimHex: 0x9ab6c2,
    rings: {
      ringsSize: 0.4,
      ringsTexture: "/solar-system-threejs/assets/uranus-rings.jpg",
    },
  },
  {
    orbitSpeed: 0.000054,
    orbitRadius: 31,
    orbitRotationDirection: "clockwise",
    planetSize: 0.5,
    planetRotationSpeed: 0.02,
    planetRotationDirection: "counterclockwise",
    planetTexture: "/solar-system-threejs/assets/neptune-map.jpg",
    rimHex: 0x5c7ed7,
  },
];

planets.forEach((item) => {
  const planet = new Planet(item).getPlanet();
  scene.add(planet);
});

const earth = new Earth({
  orbitSpeed: 0.00029,
  orbitRadius: 16,
  orbitRotationDirection: "clockwise",
  planetSize: 0.5,
  planetAngle: (-23.4 * Math.PI) / 180,
  planetRotationSpeed: 0.01,
  planetRotationDirection: "counterclockwise",
  planetTexture: "/solar-system-threejs/assets/earth-map-1.jpg",
}).getPlanet();

scene.add(earth);

In result all solar system will look sth like:

Solar system with Three.js

Deploying to GitHub Pages

For deploying to set the correct base in vite.config.js.

If you are deploying to https://.github.io/, or to a custom domain through GitHub Pages, set base to '/'. Alternatively, you can remove base from the configuration, as it defaults to '/'.

If you are deploying to https://.github.io// (eg. your repository is at https://github.com//), then set base to '//'.

Go to your GitHub Pages configuration in the repository settings page and choose the source of deployment as "GitHub Actions", this will lead you to create a workflow that builds and deploys your project, a sample workflow that installs dependencies and builds using npm is provided:

# Simple workflow for deploying static content to GitHub Pages
name: Deploy static content to Pages

on:
  # Runs on pushes targeting the default branch
  push:
    branches: ['main']

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

# Sets the GITHUB_TOKEN permissions to allow deployment to GitHub Pages
permissions:
  contents: read
  pages: write
  id-token: write

# Allow one concurrent deployment
concurrency:
  group: 'pages'
  cancel-in-progress: true

jobs:
  # Single deploy job since we're just deploying
  deploy:
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      - name: Set up Node
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'npm'
      - name: Install dependencies
        run: npm ci
      - name: Build
        run: npm run build
      - name: Setup Pages
        uses: actions/configure-pages@v4
      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3
        with:
          # Upload dist folder
          path: './dist'
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4

That is it. If your deployment has not started automatically you can always start it manually in Actions tab in your repo. Link with deployed project can be found below.


Conclusion

That’s it for today! You can find the link to the entire project below. I hope you found this entertaining and don’t still believe the Earth is flat.
See ya!

Repository link

Deployment link

版本聲明 本文轉載於:https://dev.to/cookiemonsterdev/solar-system-with-threejs-3fe0?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 如何在 PHP 中分解具有多個分隔符號的字串?
    如何在 PHP 中分解具有多個分隔符號的字串?
    Php 分解中的多個分隔符號在 PHP 中分解具有多個分隔符號的字串可能具有挑戰性。為了解決這個問題,可以定義一個自訂函數來執行該任務。一種這樣的實作如下所示:private function multiExplode($delimiters,$string) { $ary = explod...
    程式設計 發佈於2024-11-18
  • Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta:列偏移的刪除和恢復Bootstrap 4 在其Beta 1 版本中引入了重大更改柱子偏移了。然而,隨著 Beta 2 的後續發布,這些變化已經逆轉。 從 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    程式設計 發佈於2024-11-18
  • 您真的可以信任 $_SERVER['REMOTE_ADDR'] 嗎?
    您真的可以信任 $_SERVER['REMOTE_ADDR'] 嗎?
    $_SERVER['REMOTE_ADDR']的可靠性$_SERVER['REMOTE_ADDR']是Web開發中的重要變量,提供發起HTTP 請求的客戶端的IP 位址。然而,有一個常見的誤解,認為該值很容易被欺騙,從而導致對其可信度的擔憂。 $_SERVER[...
    程式設計 發佈於2024-11-18
  • 大批
    大批
    方法是可以在物件上呼叫的 fns 數組是對象,因此它們在 JS 中也有方法。 slice(begin):將陣列的一部分提取到新數組中,而不改變原始數組。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index ...
    程式設計 發佈於2024-11-18
  • 如何使用 PDO 設定連線逾時?
    如何使用 PDO 設定連線逾時?
    使用PDO 設定連線逾時:綜合指南使用PHP 資料物件(PDO) 連線到資料庫時,如果下列情況,在取得例外狀況時會遇到較長的延遲:伺服器不可用可能會令人沮喪。此問題通常在使用 PDO::setAttribute() 方法之前出現。 要建立連線逾時,可以使用替代方法。透過將選項數組傳遞給 PDO 建構...
    程式設計 發佈於2024-11-18
  • 如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    在 PHP 中組合關聯數組在 PHP 中,將兩個關聯數組組合成一個數組是常見任務。考慮以下請求:問題描述:提供的代碼定義了兩個關聯數組,$array1 和 $array2。目標是建立一個新陣列 $array3,它合併兩個陣列中的所有鍵值對。 此外,提供的陣列具有唯一的 ID,而名稱可能重疊。要求是建...
    程式設計 發佈於2024-11-18
  • 如何透過代理伺服器發出CURL請求?
    如何透過代理伺服器發出CURL請求?
    如何透過代理使用CURL透過代理伺服器使用CURL 讓您透過中介建立連線來存取受限內容或繞過地理限制。要實現此目的,請按照下列步驟操作:1。定義目標 URL 和代理設定:將您要存取的目標 URL 指派給 $url 變數。 在 $proxy 中指定代理伺服器和連接埠多變的。使用格式“IP_ADDRES...
    程式設計 發佈於2024-11-18
  • 為什麼 `background-size: cover` 在 Mobile Safari 上失敗以及如何修復?
    為什麼 `background-size: cover` 在 Mobile Safari 上失敗以及如何修復?
    克服背景大小的限制:Mobile Safari 中的覆蓋iOS 設備在實現背景圖像時面臨獨特的挑戰,使用background -size: cover覆蓋整個元素。儘管是預期的行為,但此屬性通常會在這些平台上產生不良結果。 為了解決此問題,出現了一個巧妙的解決方法。透過調整背景附件屬性以在專門針對 ...
    程式設計 發佈於2024-11-18
  • 如何在 CSS 中模糊背景圖片而不影響前景內容?
    如何在 CSS 中模糊背景圖片而不影響前景內容?
    用 CSS 模糊背景:避免內容模糊模糊背景可以增強網站美感並將注意力集中在關鍵內容上。但是,如果模糊無意中影響了內容本身怎麼辦? 在此範例中,嘗試模糊背景圖像,同時保留 span 元素內前景文字的清晰度。為了實現這一點,可以策略性地使用CSS。 關鍵技術是利用:before偽類別來繼承背景影像。引入...
    程式設計 發佈於2024-11-18
  • 如何使用共享相同名稱的行中的資料更新表中的 NULL 值?
    如何使用共享相同名稱的行中的資料更新表中的 NULL 值?
    使用同表同級的資料更新行設想一個具有類似於以下結構的表:ID名稱值1測試1測試VALUE12測試22測試2VALUE21 測試2NULL4NULL4測試NULL. ]1Test3VALUE3VALUE3VALUE3您的任務是使用具有相同「NAME」的其他行的資料填入NULL「VALUE ”單元格(即...
    程式設計 發佈於2024-11-18
  • 如何使用危險的SetInnerHTML在React中安全地渲染HTML字串?
    如何使用危險的SetInnerHTML在React中安全地渲染HTML字串?
    安全地將HTML 字串渲染為HTML在這種情況下,嘗試渲染正常的HTML 內容字串時會出現問題,但它而是顯示為字串而不被解釋為HTML。當angerlySetInnerHTML 中使用的屬性是物件而不是字串時,通常會遇到這種情況。 要解決此問題,請確保 this.props.match.descri...
    程式設計 發佈於2024-11-18
  • 儘管程式碼有效,為什麼 POST 請求無法擷取 PHP 中的輸入?
    儘管程式碼有效,為什麼 POST 請求無法擷取 PHP 中的輸入?
    解決PHP 中的POST 請求故障在提供的程式碼片段中:action=''而不是:action="<?php echo $_SERVER['PHP_SELF'];?>";?>"檢查$_POST數組:表單提交後使用var_dump檢查$_POST 陣列的內容。...
    程式設計 發佈於2024-11-18
  • \"\" 是關閉 HTML Span 標籤的有效方法嗎?
    \"\" 是關閉 HTML Span 標籤的有效方法嗎?
    」是關閉 HTML Span 標籤的有效方法嗎? " />HTML Span可以用「」關閉嗎?用「」鉸鏈關閉HTML Span的有效性XHTML在遵循XML 標準的XHTML中,所有主流瀏覽器都識別「」等自關閉標籤,例如,考慮以下有效的XHTML 代碼:&lt;!DOCTYPE ...
    程式設計 發佈於2024-11-18
  • 如何透過從陣列傳遞參數來排序 Promise 執行?
    如何透過從陣列傳遞參數來排序 Promise 執行?
    透過陣列傳遞參數來順序執行Promise考慮這樣的場景:您有一個值數組(例如,myArray)並且需要執行一個Promise-順序地基於函數(例如myPromise),將每個陣列元素作為參數傳遞。如何實現一個「可暫停循環」來確保 Promise 以正確的順序解決? 解決方案:迭代 Promise 執...
    程式設計 發佈於2024-11-18
  • 在 Python 3 中透過 UDP 套接字發送資料時如何修復「TypeError: a bytes-like object is required, not \'str\'\」?
    在 Python 3 中透過 UDP 套接字發送資料時如何修復「TypeError: a bytes-like object is required, not \'str\'\」?
    解碼套接字發送資料以解決'TypeError: a bytes-like object is required, not 'str'試圖修改用戶透過UDP 套接字輸入時,所提供的程式碼會產生錯誤,指示需要類似位元組的物件而不是字串。為了修正這個問題,程式碼需要在發送之前對輸入...
    程式設計 發佈於2024-11-18

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3