Making a <canvas> Element Bigger

I've encountered an issue with resizing my canvas using the width and height attributes. Despite adjusting these values in my code, the canvas remains the same size. Here's the snippet of the code:

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
  <canvas id="canvas" width="200" height="50"></canvas>

    <script>

//set the variables
var a = document.getElementById('canvas'),
    c = a.getContext('2d'),
    w = a.width = window.innerWidth,
    h = a.height = window.innerHeight,
    area = w * h,
    particleNum = 300,
    ANIMATION;

var particles = [];


//create the particles
function Particle(i) {
  this.id = i;
  this.hue =  rand(50, 0, 1);
  this.active = false;
}

Particle.prototype.build = function() {
  this.x = w / 2;
  this.y = h / 2;
  this.r = rand(7, 2, 1);
  this.vx = Math.random() * 10 - 5;
  this.vy = Math.random() * 10 - 5;
  this.gravity = .01;
  this.opacity = Math.random() + .5;
  this.active = true;

  c.beginPath();
      c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
  c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
  c.fill();
};

Particle.prototype.draw = function() {
  this.active = true;
  this.x += this.vx;
  this.y += this.vy;
  this.vy += this.gravity;
  this.hue -= 0.5;
  this.r = Math.abs(this.r - .05);

  c.beginPath();
      c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
  c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
  c.fill();

  // reset particle
  if(this.r <= .05) {
    this.active = false;
  }
};


//functionality
function drawScene() {
  c.fillStyle = "black";
  c.fillRect(0,0,w,h);

  for(var i = 0; i < particles.length; i++) {
    if(particles[i].active === true) {
      particles[i].draw();
    } else {
      particles[i].build();
    }
  }

      ANIMATION = requestAnimationFrame(drawScene);
}

function initCanvas() {
  var s = getComputedStyle(a);

  if(particles.length) {
    particles = [];
    cancelAnimationFrame(ANIMATION);
    ANIMATION;
    console.log(ANIMATION);
  }

  w = a.width = window.innerWidth;
    h = a.height = window.innerHeight;

  for(var i = 0; i < particleNum; i++) {
    particles.push(new Particle(i));
  }

  drawScene();
  console.log(ANIMATION);
}


//init
(function() {
  initCanvas();
  addEventListener('resize', initCanvas, false);
})();


//helper functions
function rand(max, min, _int) {
  var max = (max === 0 || max)?max:1, 
      min = min || 0, 
      gen = min + (max - min) * Math.random();

  return (_int) ? Math.round(gen) : gen;
};

    </script>
  </body>
</html>      

      

Answer №1

Take a closer look at this section:

var x = document.getElementById('canvas'),
    y = x.getContext('2d'),
    width = x.width = window.innerWidth,
    height = x.height = window.innerHeight,
    space = width * height,

Notice that width represents the window's width and height represents the window's height. Feel free to modify the values of width and height with your own custom values and let me know if it works ;)

UPDATE:

To change the dimensions of the canvas, simply replace height and width like this within your script tag:

x.style.width = '500px'; //choose any value you want
x.style.height = '500px';

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

Tips for adjusting the layout of a section class using Tailwind CSS according to screen size?

I'm really struggling with implementing my latest idea and could really use some help: I've designed this article preview section that looks amazing on small screens like mobile devices: https://i.sstatic.net/nWENQ.png <section class="w ...

The C# MVC Controller is having difficulty retrieving decimal or double values from an Ajax POST request

Having trouble sending decimal or double values via ajax to my C# MVC Controller. The values always come through as null, even though they work fine when sent as strings or integers. Why is this happening? When checking the client's request, the corre ...

Issue with function not getting triggered upon ng-click event binding

Having trouble getting a button to call the getFilteredRows() function in my MVC app's view and controller. I've tried various combinations, but the button just won't trigger the function. Can anyone help me figure out why? @using ProjectEx ...

Tips for testing $scope.$on within an AngularJS 1.5+ Component with Jasmine

Currently, I am in the process of testing the execution of some code using $scope.$on within an AngularJS 1.5+ component. However, I am facing difficulties in setting up the $rootScope accurately in Jasmine to execute the broadcast. To guide me through thi ...

What prevents Popper from functioning on its own when I incorporate bootstrap.bundle.js?

Upon my understanding, Bootstrap 4 relies on Popper for its functionalities. When utilizing bootstrap.bundle.js, Bootstrap can smoothly access Popper for various operations. Nevertheless, when attempting to use Popper independently, an error message is enc ...

Is it possible to invoke a C# method within a string concatenation method when using HTML tags?

I have a method called RenderAppraisalImage() that uses a foreach loop to iterate through my images and create HTML tags for them using html.Append. I have also created a delete method and need to add a button tag to the html.append function so that when a ...

chooses to activate prefers-color-scheme regardless of whether dark mode is also activated

Currently, I have implemented the following CSS to invert an image when in dark mode on my website: @media (prefers-color-scheme: dark) { #main-logo img {filter: invert(1);} } While this does successfully invert the image in dark mode, it also trigg ...

What is the best way to place division elements next to each other?

Is there a way to align the text "burger king" to the right of the logo on my webpage? I attempted using the bootstrap class pull-left, but it didn't produce any changes. This is how my page appears: body { font-size: 16px; background-color: # ...

The hyperlink does not function properly when included within an <input type=button> element

I have encountered an issue with the code below. In my project, I have a search bar along with some buttons. Currently, only the hyperlink of the search button is functioning correctly. The other buttons seem to redirect to the same link as the search bu ...

Encountering an error while trying to execute `$(document).ready(function() {}

Recently, I delved into the world of JavaScript, particularly Jquery. As I encountered the $(document).ready(function() {}); statement and added it to my code, I faced an issue when placing it within the header tag of my HTML. The script tag would display ...

What could be causing the custom Angular filter to not return the expected results?

I have been working on a custom filter called "occursToday" for an array of "event" objects. This filter is supposed to return events that have a startDate matching the current date. However, when I test the filter, no events are displayed despite expectin ...

Error in NodeJS session: the variable "request" is not defined

Recently, I have started working with NodeJS and I am currently facing an issue while trying to implement sessions in my project. Any assistance or guidance on this matter would be greatly appreciated. Below is the code snippet where the error occurs: va ...

Trigger JavaScript function once all Ajax requests have completed

Seeking assistance with troubleshooting JavaScript code that is not functioning as expected. The Application sends file names to the server via Ajax calls for processing, but I need to update the database once all imports are complete. The problem arises ...

Is the Kendo cascade-from trigger happening before it should?

Utilizing Kendo with angular.js, I am experiencing an issue where the model does not update when the event fires after making a selection in the first dropdown list... <input kendo-drop-down-list id="ddServiceLocations" k-options="ddServi ...

Code that achieves the same functionality but does not rely on the

I utilized a tutorial to obtain the ajax code below. The tutorial referenced the library jquery.form.js. Here is the code snippet provided: function onsuccess(response,status){ $("#onsuccessmsg").html(response); alert(response); } $("# ...

Execute a JavaScript function upon page refresh without displaying the onbeforeunload event popup

I need to disconnect the user when the page reloads without displaying a popup. view image description here Below is the code snippet: useEffect(()=> { const disconnect = (event) => { event?.preventDefault(); socketRef.current.disconnect(); r ...

Verify the correctness of two password fields using jQuery

I need help finding a script that can actively check if the passwords entered in two password fields match while typing. The script should indicate if the passwords do not match without needing to click the Submit button. Below are the two password fields ...

Trouble with updating mongoDB records within a forEach loop

I currently have a Node backend server that is linked to a MongoDB database. Within this database, there is a collection called patients containing patient objects. My goal is to update the position attribute for each object. To begin, I am retrieving the ...

Using AJAX to post button values

I have encountered an issue while attempting to post a value to a PHP script using the POST method in AJAX. The error message is as follows: Notice: Undefined index: gamekey Here is the JavaScript code I am working with: function adminchat(row) { ...

Changes are being made to how Date objects stored in Firestore behave, which could potentially cause disruptions in your app

Currently encountering an issue while working on VueJs where I am struggling to log data from Firebase. Despite making code adjustments based on the console's recommendations, nothing seems to be working as expected. My setup involves using Vue Cli 3 ...