In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Most people do not understand the knowledge points of this "three.js responsive design method" article, so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "three.js responsive design method" article.
Responsive layout of 1-canvas
The canvas canvas comes in two sizes:
Pixel size, that is, how many pixels are there in the height and width of the canvas canvas? the default is 300mm 150.
Css size, that is, width and height in css
At the front end of web, the responsive layout of dom elements is typically implemented through css.
This is not the case with canvas. The responsive layout of canvas needs to consider its pixel size.
Next, let's talk about the responsive layout of canvas by making the canvas canvas adapt to the size of the browser's window.
1. Copy and paste a copy of the previous RenderStructure.tsx and rename it ResponsiveDesign.tsx to write a responsive layout.
two。 Add the ResponsiveDesign.tsx page to the route.
Src/app.tsx
Import React from "react"; import {useRoutes} from "react-router-dom"; import ". / App.css"; import MainLayout from ". / view/MainLayout"; import Fundamentals from ". / view/Fundamentals"; import ResponsiveDesign from ". / view/ResponsiveDesign" Const App: React.FC = (): JSX.Element = > {const routing = useRoutes ([{path: "/", element:,}, {path: "Fundamentals", element:,}, {path: "ResponsiveDesign", element:,},]); return {routing};}; export default App
3. Cancel the size setting of renderer in ResponsiveDesign.tsx first.
/ / renderer.setSize (innerWidth, innerHeight)
4. Use css to set the size of the canvas canvas and its parent elements to fill the window.
Src/view/ResponsiveDesign
Const ResponsiveDesign: React.FC = (): JSX.Element = > {. Return;}
Src/view/fullScreen.css
Html {height: 100%;} body {margin: 0; overflow: hidden; height: 100%;} # root,.canvasWrapper,canvas {width: 100%; height: 100%;}
3. Import fullScreen.css into ResponsiveDesign.tsx
Import ". / fullScreen.css"
The effect is as follows:
As can be seen from the image above, the boundaries of the cube are aliased, which is caused by the distortion of the bitmap stretched by css. The default size of the canvas canvas is only 300 '150.
Therefore, we need to use the pixel size adaptive window of the canvas canvas.
4. Establish a method to update the canvas pixel size synchronously with the css size.
ResizeRendererToDisplaySize (renderer); / / sets the render size to its display size, and returns whether the canvas pixel size is equal to the Boolean value of its display (css) size function resizeRendererToDisplaySize (renderer) {const {width, height, clientWidth, clientHeight} = renderer.domElement; const needResize = width! = = clientWidth | | height! = clientHeight; if (needResize) {renderer.setSize (clientWidth, clientHeight, false);} return needResize;}
Renderer.setSize is the way to reset the render size, in which the canvas canvas is resized according to the wdirection h parameter.
This.setSize = function (width, height, updateStyle) {if (xr.isPresenting) {console.warn ('THREE.WebGLRenderer: Can't change size while VR device is presenting.'); return;} _ width = width; _ height = height; _ canvas.width = Math.floor (width * _ pixelRatio); _ canvas.height = Math.floor (height * _ pixelRatio) If (updateStyle! = false) {_ canvas.style.width = width + 'px'; _ canvas.style.height = height +' px';} this.setViewport (0,0, width, height);}
The bool parameter in the setSize () method is important and is used to determine whether to set the css size of the canvas canvas.
5. When the size of the canvas canvas changes, the aspect ratio of the camera viewport also needs to be adjusted synchronously. In this way, when we drag and drop the boundaries of the browser and zoom the browser, we can see the size of the canvas canvas adaptive browser.
Function animate () {requestAnimationFrame (animate); if (resizeRendererToDisplaySize (renderer)) {const {clientWidth, clientHeight} = renderer.domElement; camera.aspect = clientWidth / clientHeight; camera.updateProjectionMatrix ();} cubes.forEach ((cube) = > {cube.rotation.x + = 0.01; cube.rotation.y + = 0.01;}); renderer.render (scene, camera);}
The camera.aspect property is the aspect ratio of the camera viewport
When we talked about the perspective projection matrix in WebGL, we said that when the aspect ratio of the camera viewport changes, the camera's perspective projection matrix will change accordingly, so we need to use the camera.updateProjectionMatrix () method to update the perspective projection matrix.
As for why we don't put the method of updating the aspect ratio of the camera viewport into resizeRendererToDisplaySize (), this is to reduce the coupling between the resizeRendererToDisplaySize () method and the camera. Whether you want to do this or not depends on the needs of the project.
Next we can give an example of the application of canvas canvas responsive layout.
Example: 3D illustration
In the following example, we will give a zoom function to the 3D illustration to better observe the details.
1. Create a new Illustration page.
Src/view/Illustration.tsx
Import React, {useRef, useEffect, useState} from "react"; import {BoxGeometry, DirectionalLight, Mesh, MeshPhongMaterial, PerspectiveCamera, Scene, WebGLRenderer} from "three"; import ". / Illustration.css"; const {innerWidth, innerHeight} = window;const scene = new Scene (); const camera = new PerspectiveCamera (75, innerWidth / innerHeight, 0.1,1000); const renderer = new WebGLRenderer (); / / renderer.setSize (innerWidth, innerHeight, false); / Light const color = 0xffffffences Const intensity = 1X Const light = light (new DirectionalLight, new DirectionalLight) Light.position.set (- 1,2,4); scene.add (light); const geometry = new BoxGeometry (); const material = new MeshPhongMaterial ({color: 0x44aa88}); camera.position.z = 5 camera.position.z Const cubes = [- 2,0,2] .map ((num) = > makeInstance (num)); scene.add (. Cubes) / / set the rendering size to its display size, and return whether the canvas pixel size is equal to the Boolean value function resizeRendererToDisplaySize (renderer: WebGLRenderer) of its display (css) size. {const {width, height, clientWidth, clientHeight} = renderer.domElement; const needResize = width! = = clientWidth | | height! = clientHeight; if (needResize) {renderer.setSize (clientWidth, clientHeight, false);} return needResize;} function makeInstance (x: number) {const cube = new Mesh (geometry, material) Cube.position.x = x; return cube;} function animate () {requestAnimationFrame (animate); if (resizeRendererToDisplaySize (renderer)) {const {clientWidth, clientHeight} = renderer.domElement; camera.aspect = clientWidth / clientHeight; camera.updateProjectionMatrix ();} cubes.forEach ((cube) = > {cube.rotation.x + = 0.01; cube.rotation.y + = 0.01;}); renderer.render (scene, camera) } const Illustration: React.FC = (): JSX.Element = > {const divRef = useRef (null); let [btnState, setBtnState] = useState (["small", "zoom in"]); const toggle = () = > {if (btnState [0] = "small") {setBtnState (["big", "zoom out"]);} else {setBtnState (["small", "zoom in"]);}} UseEffect (() = > {const {current} = divRef; if (current) {current [XSS _ clean] = ""; current.append (renderer.domElement);} animate ();}, []); return (
A cube, also known as a cube, is a regular polyhedron composed of six square faces, so it is also called a regular hexahedron. It has 12 sides and 8 vertices. The cube is a special cuboid. A cube is a special regular quadrilateral, cuboid, triangular polyhedron, rhombus polyhedron and parallel hexahedron, just as a square is a special rectangle, rhombus, parallelogram. The cube has regular octahedral symmetry, that is, Cox BC3 symmetry, Shrevey symbol, Cox-Deacon symbol, and the dual of regular octahedron.
{btnState [1]}
The cube has 11 different unfold diagrams, that is, there are 11 different ways to cut the 7 edges of the hollow cube and flatten it into a flat figure, as shown in figure 1. [2] 11 different unfold diagrams of the cube. If we want to color the cube so that the adjacent faces do not have the same color, we need at least three colors (similar to the four-color problem). Cube is the only Plato regular polyhedron that can independently lay three-dimensional Euclidean space, so cube stacking is also the only positive stacking in four dimensions (the stacking topology in three-dimensional space is equivalent to four-dimensional polycelles). It is also the only one of Plato's solids that has even sides-square faces. therefore, it is a unique banding polyhedron in Plato's solids (all its relative faces are symmetrical about the center of the cube). If you cut the cube along the diagonal, you can get six congruent regular 4 prisms (but it is not semi-positive, and the ratio of the length of the bottom edge to the length of the side edge is 2: √ 3). By affixing its square face to the original cube, you can get a rhombic dodecahedron (Rhombic Dodecahedron) (pairwise coplanar triangles form a diamond).
The dual polyhedron of a cube is a regular octahedron. When the regular octahedron is inside the cube: the volume of the regular octahedron: the volume of the cube = [(1 + 3) × high × bottom area] × 2: edge = (1 + 3) (n + 2) [(n) / 2] 2: 1: 6 the diagonal of the star octahedron can form a cube. Truncated cube: cutting off the midpoint of another edge to get a truncated cube hypercube: a generalization of cubes in higher dimensions. More generally, cubes are three-dimensional members of a large family, that is, cubes (also known as supersquares and orthometries). They all have similar properties (such as dihedral angles of 90 °, similar hypervolume formulas, Vn-cube=a, etc.). Special cases of cuboids and tetrahedrons.
Cube is the only Plato regular polyhedron that can independently lay three-dimensional Euclidean space, so cube stacking is also the only positive stacking in four dimensions (the stacking topology in three-dimensional space is equivalent to four-dimensional polycelles). It is also the only one of Plato's solids that has even sides-square faces. therefore, it is a unique banding polyhedron in Plato's solids (all its relative faces are symmetrical about the center of the cube). If you cut the cube along the diagonal, you can get six congruent regular 4 prisms (but it is not semi-positive, and the ratio of the length of the bottom edge to the length of the side edge is 2: √ 3). By affixing its square face to the original cube, you can get a rhombic dodecahedron (Rhombic Dodecahedron) (pairwise coplanar triangles form a diamond).
);}; export default Illustration
two。 Set css styl
Src/view/Illustration.css
P {text-indent: 2em; line-height: 24px; font-size: 14px;} .cont {width: 80%; max-width: 900px; margin: auto;} .inllustration {position: relative; float: left;}. CanvasWrapper {margin-right: 15px; transition-property: width, height; transition-duration: 1s, 1s;}. Small {width: 150px; height: 150px;}. Big {width: 100%; height: 100%;}. CanvasWrapper canvas {width: 100%. Height: 100%;} .btn {position: absolute; top: 0; left: 0; cursor: pointer;}
3. In App.tsx, create a new route based on the Illustration page
Src/App.tsx
Import React from "react"; import {useRoutes} from "react-router-dom"; import Basics from ". / view/Basics"; import RenderStructure from ". / view/RenderStructure"; import ResponsiveDesign from ". / view/ResponsiveDesign"; import Illustration from ". / view/Illustration"; const App: React.FC = (): JSX.Element = > {const routing = useRoutes ([. {path: "Illustration", element:,},]); return {routing};}; export default App
4. Open another link in the home page Basics.tsx
Import React from "react"; import {Link} from "react-router-dom"; const Basics: React.FC = (): JSX.Element = > {return (basic three.js example) Illustration 3D illustration);}; export default Basics
Next, click the Illustration link on the home page to see the effect.
2-Adaptive device resolution
Most of today's PC and mobile displays are HD-DPI displays.
HD-DPI is the abbreviation of High Definition-Dots Per Inch, which means high resolution display.
The resolution of the monitor of different devices is different.
Those who have tested will know that we need to test the project with different devices, such as the models provided in WeChat Mini Programs's developer tools below.
The iPhone6/7/8 in the above figure is an example:
375667 represents the physical size of the phone's screen, and if we build a 100% full screen in it, the size is 375667.
Dpr stands for pixel density, and 2 means that the phone screen has 3752 pixels in width and 6672 pixels in height, so the pixel size of the iPhone6/7/8 screen is 750mm 1334.
When we draw in this kind of high-resolution display whose pixel size is larger than the physical size, we need to consider a problem.
If we build a screen-filled canvas directly in iPhone6/7/8, the pixel size is 375 to 667.
This size does not take advantage of the high-resolution display, we need to set its pixel size to 7501334, and then set its css size to 375667.
In this way, the canvas canvas can be displayed on the monitor in high resolution.
Code example:
Function resizeRendererToDisplaySize (renderer: WebGLRenderer) {const {width, height, clientWidth, clientHeight} = renderer.domElement; const [w, h] = [clientWidth * devicePixelRatio, clientHeight * devicePixelRatio]; const needResize = width! = = w | height! = = h; if (needResize) {renderer.setSize (w, h, false);} return needResize;}
The above devicePixelRatio is the device pixel density, which is the attribute under window, namely window.devicePixelRatio.
In fact, sometimes without careful observation, it is difficult to see whether the canvas has an adaptive device resolution.
Therefore, if the rendering quality of the picture is not high, we can do nothing, which can also avoid the problem of reducing the rendering efficiency when the pixel size of the canvas canvas becomes larger.
So much for responsive design, and then let's talk about the built-in geometry in three.js.
The above is the content of this article on "the method of three.js responsive design". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.