Having issues with the right margin in HTML5 canvas and struggling to remove the scroll bar

I am struggling with adjusting the margins of my canvas to ensure equal spacing on both sides without any horizontal scroll bars.

Desired Outcome: Equal margin on both sides of canvas without any horizontal scroll bars.

Issue: The margin-right property is not working as expected. While some solutions suggest specifying a fixed width, that is not suitable for my needs. I require the canvas to dynamically adjust its dimensions based on the window size.

To address this, I am using the following Javascript function:

window.addEventListener('resize' , resizeCanvas , false);

function resizeCanvas(){
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight/1.2;
}

Do you have any alternative solutions to this problem?

Regarding the overflow issue, adding overflow-x: hidden to the body only hides the scrollbar but does not fix the problem. The canvas still extends beyond the screen, making the right border invisible. View here

Below is the code I am working with:

HTML

<body onload="start()">
    <canvas id="myCanvas"></canvas>
</body>

CSS

body{

}

canvas{

    border: 1px solid black;
    border-radius: 5px;
    background-color: #fff;

    margin: auto 50px auto 50px; /* left margin works, but right does not */

}

Thank you!

Additional Note:

I have refrained from setting width: 100% for the canvas to prevent distortion of the content inside it.

Answer №1

According to Chris, it is important to adjust the width of the canvas to be less than the full width of the page:

canvas.width = window.innerWidth - 100;

Keep in mind that you should also consider the border-width of the canvas and the 8px margin of the body in your codepen when making this adjustment:

canvas.width = window.innerWidth - 118;

Answer №2

CSS calc() function can be used to achieve the desired result by subtracting the margins from 100%. Check out the demo below. CSS calc() reference

function start() {

  var canvas = document.getElementById('myCanvas');
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight / 1.2;
  var ctx = canvas.getContext('2d');

  function rand(min, max) {
    return parseInt(Math.random() * (max - min + 1), 10) + min;
  }

  function get_random_color() {
    var h = rand(1, 360);
    var s = rand(30, 100);
    var l = rand(30, 70);
    return 'hsl(' + h + ',' + s + '%,' + l + '%)';
  }

  function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  var balls = [];
  var ballCount = getRandomInt(2, 10);
  var startpointX = 100;
  var startpointY = 50;

  for (var i = 0; i < ballCount; i++) {

    var randValue = getRandomInt(20, 30);
    balls.push({
      x: startpointX,
      y: startpointY,
      vx: getRandomInt(3, 3) * direction(),
      vy: getRandomInt(1, 1) * direction(),
      radius: randValue,
      mass: randValue,
      color: get_random_color(),

      draw: function() {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
        ctx.closePath();
        ctx.fillStyle = this.color;
        ctx.fill();
      }
    });

    startpointX = startpointX + 50;
    startpointY = startpointY + 40;
  }


  function direction() {
    var chosenValue = Math.random() < 0.5 ? 1 : -1;
    return chosenValue;
  }

  function draw() {

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    for (var i = 0; i < ballCount; i++) {

      balls[i].draw();
      balls[i].x += balls[i].vx;
      balls[i].y += balls[i].vy;

      if ((balls[i].y + balls[i].vy + balls[i].radius) > canvas.height || (balls[i].y + balls[i].vy - balls[i].radius) < 0) {
        balls[i].vy = -balls[i].vy;
      }
      if ((balls[i].x + balls[i].vx + balls[i].radius) > canvas.width || (balls[i].x + balls[i].vx - balls[i].radius) < 0) {
        balls[i].vx = -balls[i].vx;
      }
    }

    //collision check
    for (var i = 0; i < ballCount; i++) {
      for (var j = i + 1; j < ballCount; j++) {

        var distance = Math.sqrt(
          (balls[i].x - balls[j].x) * (balls[i].x - balls[j].x) +
          (balls[i].y - balls[j].y) * (balls[i].y - balls[j].y)
        );

        if (distance < (balls[i].radius + balls[j].radius)) {

          var ax = (balls[i].vx * (balls[i].mass - balls[j].mass) + (2 * balls[j].mass * balls[j].vx)) / (balls[i].mass + balls[j].mass);
          var ay = (balls[i].vy * (balls[i].mass - balls[j].mass) + (2 * balls[j].mass * balls[j].vy)) / (balls[i].mass + balls[j].mass);
          balls[j].vx = (balls[j].vx * (balls[j].mass - balls[i].mass) + (2 * balls[i].mass * balls[i].vx)) / (balls[i].mass + balls[j].mass);
          balls[j].vy = (balls[j].vy * (balls[j].mass - balls[i].mass) + (2 * balls[i].mass * balls[i].vy)) / (balls[i].mass + balls[j].mass);
          balls[i].vx = ax;
          balls[i].vy = ay;
        }
      }
    }

    raf = window.requestAnimationFrame(draw);
  }


  function onBoxTouched() {

    for (var i = 0; i < ballCount; i++) {

      if (balls[i].x + balls[i].radius > 600 && balls[i].x + balls[i].radius < 750 &&
        balls[i].y + balls[i].radius > 200 && balls[i].y + balls[i].radius < 350) {

        ele.style.backgroundColor = balls[i].color;

        balls.splice(i, 1);
        ballCount = ballCount - 1;

        if (ballCount == 0) {
          ele.style.fontSize = "x-large";
          ele.innerHTML = "Over";
        } else {
          ele.innerHTML = ballCount;
        }
      }
    }
  }

  window.requestAnimationFrame(draw);

  window.addEventListener('resize', resizeCanvas, false);

  function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight / 1.2;
  }

}
* {}

html,
body {}

canvas {
  border: 1px solid black;
  border-radius: 5px;
  background-color: #fff;
  width: calc(100% - 40px);
  margin: auto 20px auto 20px;
}

#box {
  width: 150px;
  height: 150px;
  background-color: plum;
  border-radius: 5px;
  position: absolute;
  top: 200px;
  left: 600px;
  font-size: 72px;
  font-weight: bold;
  color: white;
  line-height: 150px;
  text-align: center;
}

#info {
  float: left;
  font-size: 24px;
  color: #6D8390;
  margin-top: 20px;
}
<body onload="start()">
  <canvas id="myCanvas"></canvas>
</body>

Hope this solution works for you :)

Answer №3

Instead of playing with margins, consider adjusting the width of your canvas and centering it for a cleaner look.

CSS

canvas {
  border: 1px solid black;
  border-radius: 5px;
  background-color: #fff;
  width: 90%!important;
}

HTML

<body onload="start()">
  <center>
    <canvas id="myCanvas"></canvas>
  </center>
</body>

https://codepen.io/anon/pen/GEmLPL

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

Should I reload the entire table or insert a row manually?

This unique ajax question arises: within a table lies the users' information, displayed based on individual settings and timing. Sometimes, users instantly see the data, other times they must wait for it - their choice determines when it appears. Wha ...

What is the process for configuring environmental variables within my client-side code?

Is there a reliable method to set a different key based on whether we are in development or production environments when working with client-side programs that lack an inherent runtime environment? Appreciate any suggestions! ...

Real-time filtering in personalized dropdown menu with search input

I have been attempting to create a custom list filter for input using a computed property. In one file, I am developing a widget, while in another file, I am implementing it. Below is the code snippet from the widget creation file: <template> ...

A step-by-step guide on developing template tags in the express framework inspired by Django

Can template tags similar to Django's be created in Node.js using the Express framework? Thank you, ...

Can sweetalert2 be used as a tooltip?

I have a query, is it feasible to include a tooltip in the alert message? Alternatively, could there be another tooltip option available? Swal.fire({ title: '<strong>An example with HTML tags</strong>', icon: 'info', ...

Deactivate dropdown menu selection depending on choice made in another list

I am currently working with the following code: $('select').on('change', function(){ $('select option').prop("disabled", false); $("select").not(this).find("option[value="+ $(this).val() + "]").prop('disabled ...

Enhance your Magento store with a personalized layout update

Is there a way to call a stylesheet from my skin folder instead of pointing to my base path? Right now I have <reference name="head"> <action method="addCss"> <stylesheet>yourtheme/css/red.css</stylesheet> < ...

Issue encountered while trying to implement a recursive function for mapping through nested elements was not producing the

I am currently working on recursively mapping through an array of nested objects, where each object can potentially contain the same type of objects nested within them. For example: type TOption = { id: string; name: string; options?: TOption; } con ...

The zip() operator in RxJS is not functioning as intended. It consistently finishes execution without emitting any values

Suppose you have an observable containing a large number of elements, say 450 or more. You want to transfer these elements to a different observable in batches of 100 elements each. You can check out a functional example provided by @martin at this link: ...

Enhance your dynamic php page with the use of a light box feature

Hey, I have created a PHP page that dynamically reads images from a folder and displays them on a gallery page. However, I am facing some issues - I am unable to link an external CSS file and I have to include all the CSS within the HTML. Additionally, I c ...

Having trouble with the scrolling feature on a read-only text area within a form

My form allows users to input their data, but once submitted, the form becomes read-only. However, I'm facing an issue where the data in the text area is not scrollable even though it should be. I need assistance in figuring out why the content in th ...

Guide to Indicating an Icon in Front of an HTML Link and Emphasizing Both with Tap

When using an iOS UIWebview, I am facing the issue of needing to add an icon before standalone links that are within a locally loaded HTML file. In addition to adding the icon, I also need both the icon and link to be highlighted when tapped. The desired ...

Optimizing HTML/CSS performance: Comparing flexbox and tables for handling extensive datasets

Creating a React table component with hundreds of lines and variable cell widths can be complex. Would it be better to implement this using flexbox or a traditional table structure in HTML/CSS? ...

Is there a way to adjust the orientation of a <video> element without affecting the orientation of the video controls?

<video controls> </video> video { transform: scaleX(-1) } This CSS code flips the video horizontally, but it also flips the control buttons along with it. I attempted to flip the wrapper element containing the video using .wrapper {transfor ...

Uncovering data treasures on the web with BeautifulSoup: Extracting JSON files from DIV elements made simple

As I attempted to extract data from a website using standard class names for the required elements, I came across an interesting discovery. Near the top of the HTML code, there was what appeared to be a JSON file containing all the necessary information. ...

Can we add to the input field that is currently in focus?

Recently, I've been working on a bookmarklet project. My goal is to append an element to the currently focused input field. For instance, if a user clicks on a textarea and then activates my bookmarklet, I want to insert the text "Hello" into that sp ...

Executing npm scripts in Node.js

Trying to move away from using the likes of Grunt or Gulp in my projects, I've been exploring npm-scripts as a potential replacement. While npm-scripts makes use of `package.json`, I've found that more advanced build processes require command lin ...

A guide to programmatically downloading a file with JavaScript on Internet Explorer

I'm currently facing a challenge with my web page. There is a button that, when clicked, should generate a CSV file (by converting from JSON) for the user to download. I've implemented the logic based on this jsfiddle, and it works perfectly in C ...

Root location for offline and pre-production in the Backbone boilerplate router

I am currently utilizing the backbone boilerplate found at https://github.com/tbranyen/backbone-boilerplate My development process involves working on static HTML/JS files offline and conducting tests offline before deploying them to another site for pre- ...

Ways to specifically load a script for Firefox browsers

How can I load a script file specifically for FireFox? For example: <script src="js/script.js"></script> <script src="js/scriptFF.js"></script> - is this only for Firefox?? UPDATE This is how I did it: <script> if($. ...