Guidelines for adjusting canvas dimensions based on parent div attributes

Trying to insert a p5.js canvas into a div using the divs width to control the canvas width, within a jekyll post. The markdown file includes a div positioned at the top of the post.

<div id="myCanvas"</div>
<script src="/js/p5Sketches/firstP5Sketch.js" type="text/javascript"></script>

Java script has the p5.js canvas assigned to the div. Attempting to retrieve the parent div's clientWidth is yielding unusual results.

var canvasDiv = document.getElementById('myCanvas');
var width = canvasDiv.clientWidth;

function setup() {
  var sketchCanvas = createCanvas(width,450);
  sketchCanvas.parent("myCanvas");
}

function draw() {
  if (mouseIsPressed){
    fill(0);
  } else {
    fill(255);
  }
  ellipse(mouseX, mouseY, 40, 40);

  if (keyIsPressed == true){
    clear();
  }
}

function windowResized() {
  resizeCanvas(width,450);
}

In the canvasDiv attributes, the correct clientWidth value is obtained (844px). However, the width variable prints as 1244px. In the Chrome inspector, the p5 canvas width is set to 100px.

<canvas id="" width="200" height="900" style="width: 100px !important; height: 450px !important;" class=""></canvas>

The value is not transferred to the p5 canvas and the reason remains unclear. No CSS is applied to style the myCanvas or canvas elements.

Thank you for your assistance.

Answer №1

To properly capture the parent elements information, it is important to include it within the setup() function.

By default, the width and height of the canvas set by setup() is 100x100. If the width is not specified within the setup function, it will automatically default to this value. Referencing the documentation:

The system parameters width and height are determined by the arguments passed to this function. In the absence of createCanvas(), the window will be given a standard size of 100x100 pixels.

For more information, visit:

This proof is demonstrated in the following image: https://i.sstatic.net/XIvor.png

Here is the corrected code that should replace your setup() function:

function setup() {
    var canvasDiv = document.getElementById('myCanvas');
    var width = canvasDiv.offsetWidth;
    var sketchCanvas = createCanvas(width, 450);
    console.log(sketchCanvas);
    sketchCanvas.parent("myCanvas");
}

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

Building a stylish table using Material UI in ReactJS

I've been working on creating a dashboard using the Material UI minimized table. You can check out the documentation here: Material UI Tables However, I've encountered an issue that has me stuck for the past 5 hours. While I was able to successf ...

Initiate an Elementor popup upon form submission (After submit event) using Contact Form 7 in WordPress

I have incorporated Elementor popups and contact form 7 into my WordPress website. Currently, my goal is to activate the Elementor popup after the contact form 7 form has been submitted. Below is what I have tried so far, and there have been no console er ...

Guide to submitting a form with an image upon pressing a button

I am working with the following HTML structure: <form id="form" enctype="multipart/form-data"> <div class="row"> <div class="col"> <div class="mb-3"> ...

Could someone please assist me in figuring out the issue with my current three.js code that is preventing it from

Recently, I decided to delve into learning three.js and followed the getting started code on the official documentation. However, I encountered a frustrating issue where the scene refused to render, leaving me completely perplexed. Here is my index.html: ...

The form's validation fails to recognize dynamically added input after the initial validation

I am currently working on a form that dynamically adds inputs. Whenever the user selects a different "supplier" from the addMaterialSupplier dropdown, a new input for the price is automatically added. The issue I'm facing is that when I click the bu ...

Change the value of input on onClick event in React

Although this may seem simple, it is a little confusing to me. I'm having trouble understanding why the input value in the following case is not being reset. handleReset() { this.setState({ data: "" }); } <button onClick={this.handleReset}>R ...

Angular state correctly maps to the controller but is not reflected in the HTML

I'm currently in the process of setting up a basic Angular application, something I've done many times before. I have defined a home state and another state for a note-taking app, but I am facing an issue where neither state is displaying or inje ...

Tips for attaching inline styles to the body element with a vuejs component

I am new to vue.js and have been learning for a couple of days now. There are still some concepts that I am struggling to understand. I am currently working on creating a dropdown menu that appears when the user clicks on three dots. However, I am facing a ...

How can I implement the dynamic loading of components using the Vue 3 composition API?

My goal is to dynamically load a component with the name retrieved from the database, however, I keep encountering the error [Vue warn]: Component is missing template or render function. import SimpleQuestions from '@/components/SimpleQuestions.vue&ap ...

Tips for comparing two arrays in node.js

I am faced with the task of comparing two arrays. let runArray = ['Welcome', 'Hello'] let data = [{ Node:'Good', Session:'2', Run:'Welcome', Run_Group:'Display', Elapsed_Ms: '1000& ...

The script I added is malfunctioning when I utilize laravel/ui

Recently, I started using a template from node js during a course. While reading various posts, I learned that bootstrap utilizes jquery. It dawned on me that the script placed in the head section was causing issues when inserting scripts in other views. ...

Error: Trying to use Router without providing a middleware function. Please make sure to pass a valid middleware function while using Router

While working on my express application with MongoJS, I encountered an issue where despite returning a function, it was showing that an object has been returned instead. To address this, I made sure to include module.exports=router in my JavaScript file. H ...

Performing a bulk update using the array provided as the base for the update statement

In my database, there is a table called sched that I frequently need to update. To facilitate this process, I have created an HTML interface that displays the current values of the sched table for users to edit. Upon making changes, scripts are triggered ...

PhantomJS is failing to provide any output

Currently, I am utilizing PhantomJS for web scraping purposes. However, I have encountered an issue where the evaluate method is not returning any data. The script seems to run for a few seconds and then unexpectedly exits. I have confirmed that PhantomJS ...

Updates to object properties are not appearing in Vue component

I am facing an issue with a Vue component that has a single prop, which is an object. Despite changing a property in this object, it does not reflect the update in the Vue template. Below is a simplified version of the component: <template> <p ...

Unable to Update the Status Code

When it comes to setting the status code to 9999, I am utilizing the basic Response.StatusCode. In this case, the page is accessed via an AJAX call and the status code is checked at readyState = 4. On detecting 9999 as the status code, an alert pops up wit ...

How can VueX be leveraged to add an item to an array and also delete an item from the same array?

https://stackblitz.com/edit/vue-script-setup-with-vuex-gfjaff?file=src/components/UserProfile.vue I'm currently working on a feature where I can input a name into a dispatch function and have it added to an array. Eventually, I plan to include a text ...

What is the method to effectively conduct a testing procedure for JavaScript files that have been exported using

I have a JavaScript file called "sum.js" which contains a simple function: // sum.js function sum(a, b) { return a + b; } export default { sum }; Now I want to write a test for this file using Jest. Here is my "sum.test.js" file in the same folder: // ...

Bringing Typescript functions into the current module's scope

Is it possible to import and reference a module (a collection of functions) in typescript without the need for the Module. prefix? For instance: import * as Operations from './Operations'; Can I access Operations.example() simply as example()? ...

Tips for sending form data from ReactJS to controller in ASP.NET MVC:

Seeking help with React and ASP.NET integration. I am attempting to create a form in ASP.NET using React, but encountering issues when trying to pass form data from ReactJS to an MVC ASP.NET controller. Below is the code that I have been working on. Any su ...