Tips for positioning a canvas and a div element next to each other on a webpage

I have a canvas and a div element that I need to split in a 60% to 40% ratio. However, no matter what changes I make to the display settings, the div is always displayed before the canvas.

The Div element contains buttons with color-changing properties for the canvas element.

<div id = "ModelArea1">
    <div id = "Model1">
  <canvas id ="scene1" style="width: 100%; height:100%;">
    </canvas>
    </div>
    <div id ="SelectionArea1">
        <button type ="button" class ="ButtonFormat" onclick =displayVariations()>Fabric Textures</button>
        <div class = "FabricTectureOptions" style="display:none;">  
            <div class ="Fabric1">      
            </div>
            <div class ="Fabric2">      
            </div>
        </div>
        <button type ="button" class ="ButtonFormat" onclick =displayVariations()>Leather Textures</button>
    </div>
</div>
.Fabric1{
  background-image: url("https://i.ibb.co/B2kPznR/Fabric-Upholstery-Moss-Plain-Weave001-AO-1-K.jpg");
   height: 50px;
   width: 50px;
   border-radius: 10px;
   display: inline-block;
}
.Fabric2{
  background-image: url("https://i.ibb.co/kKZRpdm/Fabric-Upholstery-Moss-Plain-Weave001-COL-VAR3-1-K.jpg");
   height: 50px;
   width: 50px;
   border-radius: 10px;
   display: inline-block;
}
.ButtonFormat{
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 5px;
  border-style: none outset outset none;
  outline: none;
  font-size: 12px;
}
.FabricTectureOptions{
  padding: 0 18px;
  overflow: hidden;
  background-color: #f1f1f1;
  border-radius: 10px;
}
#ModelArea1{
  width:100%;
  display:inline-flex;
}
#Model1{
  width: 60%;
}
#SelectionArea1{
  width: 40%;
}

I want both the canvas and div elements to have the same height and width and be positioned side by side like this:

| Canvas        |     Div  |
|               |          |
|               |          |

Question 1: How can I achieve this alignment correctly?

Question 2: Is it necessary to wrap the canvas in a div to achieve this layout, or is there an alternative method?

Here is the codepen link for reference: https://codepen.io/FarhaNaseem/pen/eYgKJZW

Answer №1

If you follow these steps, your canvas will function to a certain extent:

renderer.setSize(window.innerWidth * 0.6, window.innerHeight); // Set the canvas width to 60% initially;

However, you'll need to adjust the canvasWidth whenever the window is resized. I also utilize JavaScript to create new container elements and add child elements to it.

// Resize canvas dynamically
window.addEventListener("resize", () => {
   let ratio = 0.6
   let canvasWidth = window.innerWidth * ratio
   renderer.setSize(canvasWidth, window.innerHeight) // Adjust height by multiplying with the ratio
   camera.aspect = canvasWidth / window.innerHeight
   camera.updateProjectionMatrix() // Call this after changing parameters.
});

// Add elements to wrapper container in DOM
let ModelArea1 = document.querySelector("#ModelArea1")
let container = document.createElement("div")
container.classList.add("container")
document.body.append(container)
container.appendChild(renderer.domElement) // Attach canvas to container
container.appendChild(ModelArea1) // Include 40% area after canvas

This method results in a more organized generated DOM:

<div class="container">
  
  <canvas id="scene1" width="726" height="541">
    </canvas>

  <div id="ModelArea1">
    
    <div id="Model1">
    </div>
    
    <div id="SelectionArea1">
      <button type="button" class="ButtonFormat" onclick="displayVariations()">Fabric Textures</button>
      <div class="FabricTectureOptions" style="display:none;">
        <div class="Fabric1">
        </div>
        <div class="Fabric2">
        </div>
      </div>
      <button type="button" class="ButtonFormat" onclick="displayVariations()">Leather Textures</button>
    </div>
    
  </div>
</div>

You can also convert the container into a flexbox element using display: flex

Preview:

Check out the Codepen Demo here: https://codepen.io/m4n0/pen/zYNeGVz

https://i.sstatic.net/JsV1J.png

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

Is there a way to implement request-specific global variables for individual websocket connections in a Node.js application, similar to using res.locals for

Currently, I'm working on creating global variables within the io.use method of the socket.io server-side library. The goal is to have variables that are accessible throughout the entire request lifecycle for websockets. My setup involves using the ex ...

Alter the URL and CSS upon clicking an element

Currently, I am faced with a challenge on my website where I have multiple pages that utilize PHP to include content and jQuery to toggle the display of said content by adjusting CSS properties. However, I am encountering difficulty in implementing this ...

Using the timer function to extract data within a specific time frame - a step-by-step guide

Is there anything else I need to consider when the temperature increases by 1 degree? My plan is to extract data from my machine for the last 30 seconds and then send it to my database. set interval(function x(){ If(current_temp != prev_temp){ if((c ...

Troubleshooting problem with scrollbar in HTML table within a div element

I'm utilizing Bootstrap for the majority of my CSS. I've split a section into two columns, with the left column displaying a table with data and the right side featuring a Google map. The issue arises when the table row grows, as it doesn't ...

JQuery script fails to load in the head section while dynamically generating an HTML page with JavaScript

Using JavaScript, I have created a new window dynamically and added some HTML code to it. However, when I try to insert a script link into the HTML head, it fails to load when the window is open. <script type="text/javascript"> function newWindo ...

.Internet Explorer text update problem

Encountering a problem specifically in IE (like always). I've managed to narrow down the issue I'm facing to a recursive script responsible for updating a tweet's timestamp. The script functions correctly, identifying all the date/time sta ...

JavaScript Datepicker Formatting

I need to modify the date format of a datepicker. Currently, it displays dates in MM/DD/YYYY format but I want them to be in DD-MM-YYYY format. <input id="single-date-picker" type="text" class="form-control"> Here's the JavaScript code: $("# ...

angularJS controller does not seem to be functioning properly due to a certain

var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; //January is 0! var yyyy = today.getFullYear(); var currentdate = yyyy + ',' + mm + ',' + dd; var appointmentDate = moment($scope.AppointmentsList[i].J).f ...

Styling Navigation in Internet Explorer 7 and 8

I'm encountering issues with a drop-down menu system specifically in IE7 and 8. The functionality is smooth in Chrome and FF, but for some reason, it fails to apply certain styles and ends up misaligned in the IE7 and 8 browsers. You can check it ou ...

CSS technique for adjustable column width in HTML tables

Important Note: The HTML to PDF rendering engine I am using disables JavaScript by default, so I am seeking solutions that utilize CSS only. Within my report, there is a table utilized for accounting purposes featuring 11 columns: The first column serve ...

Using jQuery to append text after multiple element values

I currently have price span tags displayed on my website: <div> <span class="priceTitle">10.00</span> </div> <div> <span class="priceTitle">15.00</span> </div> <div> <span class="priceTitle">20.0 ...

Using React's useEffect to implement a mousedown event listener

I created a modal that automatically closes when the user clicks outside of it. method one - involves passing isModalOpened to update the state only if the modal is currently open. const [isModalOpened, toggleModal] = useState(false); const ref = useRef(n ...

What is the best way to change the font size in HTML?

https://i.sstatic.net/IjLvn.png After carefully analyzing the image provided, I encountered an issue while attempting to incorporate the code display:block. However, no changes were reflected. Can you identify what may be causing this discrepancy in my te ...

Refresh directive for concealing elements post authentication

Hey everyone, I'm facing a situation where I need to display certain UI elements based on whether a session is active or not. I initially tried using a directive for this purpose, and while it worked well, I encountered an issue where the directives ...

Creating an object and setting its prototype afterwards

While exploring examples and questions online about prototypal inheritance, I noticed that most of them involve assigning prototypes to constructor functions. One common pattern is shown in the code snippet below: Object.beget = function (o) { var F = ...

Making use of JavaScript's XMLHttpRequest() function allows for seamless

My issue revolves around my use of multiple XMLHttpRequest() requests in order to retrieve the value (miniTable) returned by the TableRow() function. Strangely, while I get the desired value when using alert() at the end of the TableRow() function, the T ...

Personalized payment fields: Revealing/concealing data using a selector

Following this successful solution: // Incorporating an external jQuery/JS file function cfields_scripts() { // IMPORTANT NOTE: // When using a child theme, replace get_template_directory_uri() with get_stylesheet_directory_uri() // Place th ...

Difficulty encountered when trying to use Bootstrap tooltip with Bootstrap icon

Attempting to implement bootstrap tooltips on bootstrap icons with the following code: <body> <script> const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]') ...

The value of this.$refs.<refField> in Vue.js with TypeScript is not defined

During the process of converting my VueJs project to TypeScript, I encountered an error related to TypeScript. This issue arises from a component with a custom v-model implementation. In the HTML, there is an input field with a 'plate' ref that ...

php After the ajax request, the array_push function is failing to add values to the

I am having trouble with my ajax and php implementation. I want to append an array every time an ajax call is made, but it doesn't seem to be working. Here are the codes I am using: $('#multiple_upload_form' +count).ajaxForm({ ...