The background size does not adjust to the size of the viewport

I am encountering an issue with the background size on my webpage. When changing the viewport size on this page , the background does not adjust to the new viewport dimensions immediately. It seems to retain the previous dimension and only updates to the correct size when the page is refreshed. Can anyone assist me in ensuring that my background scales appropriately with the viewport size?

<!doctype html>
<html>

<head>
<style>

@font-face{
    font-family: Roslindale; 
    src: url("pvcweb-banner-TRIAL.woff") format('woff');
    font-weight: bold;
}

.workspace {
  height: 100vh;
  width: 100vw;
  top: 0;
  left: 0;
  display: grid;
  place-items: center;
  font: 700 12px system-ui;
}

body, html {
    height: 100vh;
    width: 100vw;
    background-size: cover;
}



body{
  overflow: hidden;
  cursor: url(images/cursor.png),auto;
}
canvas {
  width:100%; height:100%; 
  background-size: cover;
}
.header-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgb(0, 0, 0);
  opacity: 0.1;
}
</style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r122/three.min.js"></script>     
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/16327/gsap-latest-beta.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

</head>

<body>
<div class='header-overla' style="position: fixed; height: 100vh;">

<script>
var mousePos = {x:.5,y:.5, z:.5};
document.addEventListener('mousemove', function (event) {  mousePos = {x:event.clientX/window.innerWidth, y:event.clientY/window.innerHeight, z:event.clientZ/window.innerWidth};});
var phase = 0;

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(95, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 30;

var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var boxSize = 0.2;
var geometry = new THREE.BoxGeometry(boxSize, boxSize, boxSize);
var materialGreen = new THREE.MeshBasicMaterial({transparent: true,  color: 0xffffff,  opacity: 0.4,  side: THREE.DoubleSide});

var pitchSegments = 60;
var elevationSegments = pitchSegments/2;
var particles = pitchSegments*elevationSegments
var side = Math.pow(particles, 1/3);

var radius = 30;

var parentContainer = new THREE.Object3D();
scene.add(parentContainer);

function posInBox(place) {
  return ((place/side) - 0.5) * radius * 1.2;  
}

//Plant the seeds, grow some trees in a grid!
for (var p = 0; p < pitchSegments; p++) {
  var pitch = Math.PI * 2 * p / pitchSegments ;
  for (var e = 0; e < elevationSegments; e++) {
    var elevation = Math.PI  * ((e / elevationSegments)-0.5)
    var particle = new THREE.Mesh(geometry, materialGreen);
    
    
    parentContainer.add(particle);

    var dest = new THREE.Vector3();
    dest.z = (Math.sin(pitch) * Math.cos(elevation)) * radius; //z pos in sphere
    dest.x = (Math.cos(pitch) * Math.cos(elevation)) * radius; //x pos in sphere
    dest.y = Math.sin(elevation) * radius; //y pos in sphere

    particle.position.x = posInBox(parentContainer.children.length % side);
    particle.position.y = posInBox(Math.floor(parentContainer.children.length/side) % side);
    particle.position.z = posInBox(Math.floor(parentContainer.children.length/Math.pow(side,2)) % side);
    console.log(side, parentContainer.children.length, particle.position.x, particle.position.y, particle.position.z)
    particle.userData = {dests: [dest,particle.position.clone()], speed: new THREE.Vector3() };
  }
}

function render() {
  phase += 0.002;
  for (var i = 0, l = parentContainer.children.length; i < l; i++) {
    var particle = parentContainer.children[i];
    var dest = particle.userData.dests[Math.floor(phase)%particle.userData.dests.length].clone();
    var diff = dest.sub(particle.position);
    particle.userData.speed.divideScalar(1.02); // Some drag on the speed
    particle.userData.speed.add(diff.divideScalar(8000));// Modify speed by a fraction of the distance to the dest    
    particle.position.add(particle.userData.speed);
    particle.lookAt(dest);
  }
  
  parentContainer.rotation.y = phase*3;
  parentContainer.rotation.x = (mousePos.y-0.5) * Math.PI;
  parentContainer.rotation.z = (mousePos.x-0.5) * Math.PI;

  renderer.render(scene, camera);
  requestAnimationFrame(render);
}
render();
    
</script>
  
    
   

</body>


</html> 

Thank you for your assistance.

Answer №1

  1. When using the <canva> element, make sure to apply custom CSS using the !important keyword with size values instead of inline CSS for width and height.

  2. Instead of using background-size, consider using object-fit for the <canva> element.

Here's an example:

canvas {
    width: 100% !important;
    height: 100% !important;
    object-fit: cover;
}

Apologies for any mistakes in my English writing.

Answer №2

Are you referring to the background in the three.js scene?

If that's the case, you should include a resize event listener to adjust the canvas/scene and update the camera accordingly.

 window.addEventListener('resize', onWindowResize, false);
 
 function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
}

You may also want to eliminate the default body padding by using margin: '0px'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An HTML webpage that automatically refreshes but does't display the iframe content when the underlying HTML page is being updated

I have a script that updates a text file with completed tasks, creating log files in the process. I then use another script to format these logs with HTML code for tables, headings, banners, etc., saving the formatted version as Queue.html. To display this ...

Challenges with JavaScript and JQuery - Extracting and Displaying YouTube Information on Website

While I have some experience with Javascript and JQuery, my latest project on FirstPersonTheater.net is not going as planned. I am using PHP to generate a video ID in javascript code to retrieve information about YouTube videos such as title, uploader, vie ...

Monitoring a folder using webpack

Currently, I have webpack set up in my development environment to bundle all of my dependencies. To help concatenate various js files and include them in a script tag within the markup, I am utilizing the webpack-merge-and-include-globally plugin. Althoug ...

Can you provide a step-by-step guide on creating a JSONP Ajax request using only vanilla

// Performing an ajax request in jQuery $.ajax( { url : '', data: {}, dataType:'jsonp', jsonpCallback: 'callbackName', type: 'post' ,success:function (data) { console.log('ok'); }, ...

Creating a popup trigger in ReactJS to activate when the browser tab is closed

I am currently working on an enrollment form that requires customer information. If a user fills out half of the form and then attempts to close the tab, I want to trigger a popup giving them the option to save and exit or simply exit. While I have a jQue ...

Bootstrap navbar partially collapsed with inner items concealed not at the edges

Many discussions have come up regarding partially collapsing Bootstrap navbars, such as: Item1 Item2 Item3 Item4 Item5 Is it possible to achieve the following collapsed format: Item1 Item2 Item3 =menu= Or: =menu= Item3 Item4 Item5 This method ...

The Laravel return view function seems to be malfunctioning as it is displaying an error page instead

I am facing an issue where I am trying to display an existing view but instead of the show page, I keep getting a "404 not found" error. As a beginner in Laravel, I am still trying to grasp its concepts. Any insights into why I am encountering the error 40 ...

Using the npm package in JavaScript results in a return value of 1

Recently, I have been working on turning this into an npm package: Test.tsx: import React from "react"; export default class Test extends React.Component { public render() { return ( <h1> Hallo & ...

Avoid page refreshing when retrieving data using PHP and AJAX

In my current program, I am able to add data and insert it into the database. However, I am looking for a way to automatically send this data to another page or browser without refreshing. I have two browsers open, so how can I submit the data to the other ...

Could the absence of an external style sheet for CSS be hindering the execution of my code?

A generous Stack Overflow user provided me with the code you see here and their JSFiddle can be accessed at http://jsfiddle.net/f18513hw/. The code functions properly in JSFiddle. I copied and pasted the code into my Textpad, saved it in my htdocs folder o ...

Encountering a 404 error when attempting to access static files within a directory using Express Js

Organizing my static files has been a breeze with multiple directories. I have some static files in the client directory, while dashboard-related files are nested within the src directory. Here is how my directory structure looks: / | client //housing sta ...

What is the best way to send an object from the front end to the backend using res.send?

In my current project, I am establishing communication between the frontend and backend. The process involves the backend sending an expression to the frontend for computation, after which the computed answer needs to be sent back to the backend. For exam ...

Transferring sizable JavaScript array to the Web API

I've been grappling with this problem for two days... In my JavaScript code, I have a large array comprising 20,000 rows and 41 columns. This data was initially fetched in JavaScript via an ajax call, as shown below: var dataArray = []; var dataRequ ...

Woocommerce Dual Column Payment Portal

I prefer a two-column layout for the checkout process on www.narwal.shop/checkout Here is the code I added: /* Large devices (large desktops, 1200px and up) */ @media (min-width: 993px) { /* --------------------- WOOCOMMERCE -------- ...

Can I link the accordion title to a different webpage?

Is it possible to turn the title of an accordion into a button without it looking like a button? Here is an image of the accordion title and some accompanying data. I want to be able to click on the text in the title to navigate to another page. I am worki ...

Input values in Angular are not being updated according to the corresponding model values

My Angular application features two routes that share the same controller and partials. Despite the shared code, the controller and partials behave slightly differently depending on the route being used. Here are the routes: $routeProvider.when('/joi ...

What is the reason that when we assign `'initial'` as the value for `display` property, it does not function as intended for list elements?

To toggle the visibility of elements, I have created a unique function that accepts an object and a boolean. Depending on the boolean value, either 'none' or 'initial' is assigned to the 'display' property of the specified obj ...

Obtain User Input from a TextArea Element on an HTML Page using ASP.net

In my asp.net 4.0 project, I am using jTemplates to create a HTML-Page that includes a text area and a submit button. I am looking for a way to retrieve the value entered in the text area when the user clicks on the submit button. Can anyone provide guid ...

What is the best way to retrieve the object of the selected option from a single select input in Angular

I'm currently working with an array of objects that looks like this: let myArray = [{'id':1,'Name':"ABC"},{'id':2,'Name':"XYZ"}] I'm trying to retrieve object values based on a dropdown selection, but so ...

What specific files from the Kendo core are required for utilizing Mobile and Angular functionalities?

After browsing through similar questions, I couldn't find a solution. Currently, I am experimenting with Kendo (open source core for now) in a Visual Studio Cordova project. Initially, disregarding Cordova, I am focusing on setting up a basic view wit ...