Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize the canvas using JavaScript?

How would one make the JavaScript canvas (or whatever the 400px by 400px drawing area is called) larger than 400x400?

I have a 1440p screen and when I run my JS files through an HTML file, the canvas is not surprisingly a small 400px by 400px box in the top left.

Is there anything I can do to expand the canvas to a specified height and width?

like image 348
B. Freeman Avatar asked Sep 18 '16 21:09

B. Freeman


People also ask

How do you resize a canvas?

With the Select and Move Tool, click the canvas size label or border to select the canvas. Click the canvas border handles to resize the canvas dynamically. When you drag the border handles without using any keyboard modifiers, the canvas resizes non-uniformly. Hold Shift to constrain the resize proportions.

How do you dynamically resize canvas?

Resizing the canvas on the fly is quite easy. To do it, simply set the width and height properties of the Canvas object, and then redraw the canvas contents: Canvas . width = 600 ; Canvas .

How do you change the canvas size in HTML?

The default size for both element and drawing surface is 300 x 150 screen pixels. To set the height and width canvas HTML5 has two attributes: Height: With the help of Height attribute we can set the height. Width: With the help of Width attribute we can set the width.

Does JavaScript work in canvas?

<canvas> is an HTML element which can be used to draw graphics via scripting (usually JavaScript). This can, for instance, be used to draw graphs, combine photos, or create simple animations.


1 Answers

The following jsfiddle demonstrates how to resize the canvas. https://jsfiddle.net/intrinsica/msj0cwx3/

(function() {
  var canvas = document.getElementById('canvas'),
      context = canvas.getContext('2d');

  // Event handler to resize the canvas when the document view is changed
  window.addEventListener('resize', resizeCanvas, false);

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

    // Redraw everything after resizing the window
    drawStuff(); 
  }
  resizeCanvas();

  function drawStuff() {
    // Do drawing here
    context.strokeRect(10,10, 230,100);
    context.font = '16px serif';
    context.fillText('The canvas is the blue', 30, 30);
    context.fillText('background color seen here.', 30, 50);
    context.fillText('It will resize if the window', 30, 70);
    context.fillText('size is adjusted.', 30, 90);
  }
})();
* { margin:0; padding:0; } /* to remove the top and left whitespace */

html, body { width:100%; height:100%; } /* just to be sure these are full screen*/

canvas {
    background: #77f;  /* to show the canvas bounds */
    display:block;     /* to remove the scrollbars */
}
<canvas id="canvas"></canvas>
like image 181
James Dunn Avatar answered Sep 23 '22 01:09

James Dunn