HTML5 Canvas Border

Hey Everyone, I've been working on an HTML5 canvas project where I set the canvas width to $(window).width(). Everything was going smoothly until I added a border, which caused a horizontal scroll to appear.

Important: I attempted to use the innerWidth() function, but so far I haven't been able to solve the issue. My determination drives me to figure out why this problem is happening.

$(document).ready(function () {
    $('canvas').width($(window).width());
    $('canvas').height($(window).height());
    console.log($(window).width())
})
* {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}
.home{
    width:100%;
    height:auto;
}
canvas{
    display:block;
    border:2px solid #0094ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="home">
    <canvas id="myCanvas"></canvas>
</div>

Answer №1

Get rid of these lines:

$('canvas').width($(window).width());
$('canvas').height($(window).height());
console.log($(window).width())

Instead, use CSS to set the width and height:

canvas{
    display:block;
    border:2px solid #0094ff;
    width:100%;
    height:100%;
}

Answer №2

Implemented the following CSS and script:

CSS


{
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}
body {
    margin: 0px;
    padding: 0px;
}
.home {
    width: 100%;
    height: auto;
}
canvas {
    display: block;
    border: 2px solid #0094ff;
}

Script


$('canvas').width($(window).width() - 4);
$('canvas').height($(window).height() - 4);
console.log($(window).width());

Answer №3

When utilizing .width and .height, you are defining the sizes of content regardless of box-sizing. Replace them with .css({width, height}). Also, remove the margin from the body and set the canvas's display to block in order to prevent vertical scrolling.

It's worth mentioning that it is not necessary to set sizes through the script, but potentially you do need to establish dimensions.

$(function () { // Solely for determining drawing scale on canvas, has no impact on appearance
  var $window = $(window);
  var $canvas = $("canvas");
  var border = $canvas.css("border-width");
  
  $('canvas')
    .prop('width', $window.width() - 2 * border);
    .prop('height', $window.height() - 2 * border);
});
* {
  box-sizing: border-box;
}

html, body, canvas {
  display: block;
  margin: 0;
  height: 100%;
  width: 100%;
}

canvas{
  border: 2px solid #0094ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<canvas id="myCanvas"></canvas>

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

Exploring cross-browser compatibility with the use of CSS3 and JavaScript

Starting a new project to create a fresh website. It seems like many people are leaning towards CSS3 and AJAX, neglecting browsers without JavaScript support. They resort to workarounds like enabling CSS3 through JavaScript in older browsers. Is this the ...

Having trouble loading a React component

I've been working on breaking down modules from a monolithic React project to store them separately in my npm registry. However, I'm encountering issues with exporting and importing them correctly. Previously, I was using the following code: con ...

Changing the Values of Variables in an npm Package within SvelteKit

I have been working on a SvelteKit component library where I define variables for components like background-color and font-family in a CSS file. Inside the ./dist/index.js file of my library, I export the CSS using `import './main.css'`. When in ...

Upgrading Angular from version 8 to 9: Dealing with Compilation Errors in Ivy Templates

After successfully upgrading my Angular application from version 8 to version 9 following the Angular Update Guide, I encountered some issues in the ts files and managed to resolve them all. In version 8, I was using the View Engine instead of Ivy, which ...

Code for object creation, inheritance, and initialization

In the code snippet below, a class is defined for managing input events such as mouse, touch, and pointer: // base.js export default () => { return { el: undefined, event: undefined, handler(ev) { console.log('default handler&a ...

transferring data from a web page to a php script seamlessly without navigating away

I've already spent a significant amount of time searching on Stack Overflow and Google, but I haven't found a solution that works for me. My issue is that I have an HTML form and I need to send the data to PHP without redirecting or leaving the ...

Dynamic Menu Navigation (No Bootstrap Required)

My Navbar is working perfectly in the original mode but when the screen width is less than 950px, it displays the buttons stacked vertically. However, the dropdown button opens the dropdown content on the wrong side. I want the dropdown content to appear u ...

A centered Bootstrap navigation bar on a WordPress site

My Bootstrap navbar is floating in the center on WordPress and I'm not sure why. Can anyone help me with this issue? Could it be related to WordPress or my stylesheet problems? (Will update my code here if you need) STYLES.CSS .navbar-default { ...

What could be the reason why certain animations fail to run on specific icons when hovering over the parent element?

I recently launched my website which features a series of tabs with unique icons. Some of the icons, labeled as soap-icon, have animated effects while others, categorized under icomoon-icon, do not. Upon checking the console, I discovered that the animati ...

Link up each query with every php echo

Suppose I have the following PHP code: $logger = $_SESSION['logger']; $postquery = $con->query("SELECT * FROM posts ORDER BY id DESC LIMIT 5"); while($row = $postquery->fetch_object()){ $posts[] = $row; } And then, this section of ...

"Encountering a failure with PHP PDO prepared delete statement in MySQL while executing an Ajax

I am troubleshooting a PDO Prepared DELETE statement issue within a PHP file that is called using AJAX. Below is the AJAX call: var data = {action: "deleteTask", value: "1"}; $.ajax({ type: "POST", dataType: "json", url: "aja ...

``There seems to be an issue with the functionality of Angular's $routeProvider

I'm currently facing an issue with my setup. I have a local angular front-end running on localhost using an Apache Server on Linux. When I try to access localhost, everything works fine and I can see my index.html. However, I have a link in the index. ...

Tips for adjusting your Navbar from transparent to solid based on screen size changes instead of scrolling

I am seeking assistance in creating a responsive Navbar that transitions from transparent to solid when the screen size changes, such as on a smartphone. I want the Navbar to remain fixed at the top of the page and not move down as I scroll. I tried adding ...

Slide your finger upwards to shut down the mobile navbar in bootstrap

Hey there, I'm currently developing a website using Bootstrap framework v3.3.4. I have a mobile navbar that opens when I click a toggle button, but I would like it to slide up to close the navigation instead. Here is an image showing the issue Do y ...

Using React Higher Order Components to transmit data attributes to the initial child/element within the encapsulated component

Presently, I have a custom higher-order component structured in the following manner: export const withAttrs = (WrappedComponent) => { const ModifiedComponent = (props) => ( <WrappedComponent {...props} data-test-id="this-is-a-element&q ...

Utilizing VueJS to effectively integrate the Google Places API with multiple references

I am currently integrating the Google Places API into my project and have encountered an interesting challenge. I need to implement multiple delivery addresses, requiring me to modify how the Google Places API functions. Below is my existing code snippet: ...

Experiencing a problem with a loop structure in my code

I've been trying to create a loop that will increase the temperature by 10 degrees every 2 minutes. However, I'm struggling to figure out how to stop the temperature at 120 degrees after 16 minutes. Any suggestions on how to solve this issue? va ...

Paper.js: Is there a way to prevent canvas height and width from changing when the window is resized?

My canvas with paperjs is set up to resize dynamically when the window is resized. I appreciate any help in advance. HTML <canvas id="myCanvas" height="800" width="1000"></canvas> JS var Initialize = function () { var canvas = document ...

Autofill drop-down menu upon initial selection in Rails3 with jQuery Autocomplete

I am currently working on enhancing the functionality of an autocomplete drop-down list to automatically display all items from a specific table when there is no input in the text field. While everything is functioning smoothly, I am facing a challenge wit ...

Utilize NgRepeat to access an unidentified array in AngularJS

In a complex multi-level array, there are objects nested at the deepest level. [ [ [ "FUND", { "totassets":10.9, "totdate":"2015-03-23", "expratiogross":1.35, "exprationet" ...