Canvas Width and Height in Html5

Canvas width and height in HTML5

The canvas DOM element has .height and .width properties that correspond to the height="…" and width="…" attributes. Set them to numeric values in JavaScript code to resize your canvas. For example:

var canvas = document.getElementsByTagName('canvas')[0];
canvas.width = 800;
canvas.height = 600;

Note that this clears the canvas, though you should follow with ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height); to handle those browsers that don't fully clear the canvas. You'll need to redraw of any content you wanted displayed after the size change.

Note further that the height and width are the logical canvas dimensions used for drawing and are different from the style.height and style.width CSS attributes. If you don't set the CSS attributes, the intrinsic size of the canvas will be used as its display size; if you do set the CSS attributes, and they differ from the canvas dimensions, your content will be scaled in the browser. For example:

// Make a canvas that has a blurry pixelated zoom-in
// with each canvas pixel drawn showing as roughly 2x2 on screen
canvas.width = 400;
canvas.height = 300;
canvas.style.width = '800px';
canvas.style.height = '600px';

See this live example of a canvas that is zoomed in by 4x.

var c = document.getElementsByTagName('canvas')[0];var ctx = c.getContext('2d');ctx.lineWidth   = 1;ctx.strokeStyle = '#f00';ctx.fillStyle   = '#eff';
ctx.fillRect( 10.5, 10.5, 20, 20 );ctx.strokeRect( 10.5, 10.5, 20, 20 );ctx.fillRect( 40, 10.5, 20, 20 );ctx.strokeRect( 40, 10.5, 20, 20 );ctx.fillRect( 70, 10, 20, 20 );ctx.strokeRect( 70, 10, 20, 20 );
ctx.strokeStyle = '#fff';ctx.strokeRect( 10.5, 10.5, 20, 20 );ctx.strokeRect( 40, 10.5, 20, 20 );ctx.strokeRect( 70, 10, 20, 20 );
body { background:#eee; margin:1em; text-align:center }canvas { background:#fff; border:1px solid #ccc; width:400px; height:160px }
<canvas width="100" height="40"></canvas><p>Showing that re-drawing the same antialiased lines does not obliterate old antialiased lines.</p>

HTML5: Canvas width and height

Yes, those units are always in pixels and applies to the bitmap the canvas element uses. However, if there is no size defined on the element using CSS (ie. style attribute or using a style sheet) the element will automatically adopt to the size of its bitmap.

There is no other way of setting the size of the bitmap than by number of pixels. Using CSS will only change the size of the element itself, not the bitmap, stretching whatever is drawn to the bitmap to fit the element.

To use other units you will have to manually calculate these using JavaScript, for example:

// using % of viewport for canvas bitmap (pixel ratio not considered)
var canvas = document.getElementById("myCanvas"),
vwWidth = window.innerWidth,
vwHeight = window.innerHeight,
percent = 60;

canvas.width = Math.round(vwWidth * percent / 100); // integer pixels
canvas.height = Math.round(vwHeight * percent / 100);

// not to be confused with the style property which affects CSS, ie:
// canvas.style.width = "60%"; // CSS only, does not affect bitmap

If you want to support retina then you need to use the window.devicePixelRatio and multiply it with the sizes. In this case CSS would be necessary as well (combine with code above):

var pxRatio = window.devicePixelRatio || 1,
width = Math.round(vwWidth * percent / 100),
height = Math.round(vwHeight * percent / 100);

canvas.width = width * pxRatio;
canvas.height = height * pxRatio;

canvas.style.width = width + "px";
canvas.style.height = height + "px";

Scale HTML5 Canvas to div width and height

As you're using bootstrap, you can do it with jquery:

var $canvas = $("#canvas");
var $parent = $canvas.parent();
$canvas.width($parent.width());
$canvas.height($parent.height());

HTML5 Canvas 100% height and width

body, #canvasRain {width:100%; height:100%; margin:0px;} will set your size properly but your problem is that your canvas height/width you're using to do your drawing doesn't pick up the proper px values when setting them with %'s. And that's where the scaling comes in with the fuzzy flakes. It takes some default canvas size and stretches to 100% of the view. Adding something like

bufferCanvas.width = canvas.width = window.innerWidth;
bufferCanvas.height = canvas.height = window.innerHeight;

seems to do the trick. And you might want/need to handle resize events to recalculate it. Here is a sample. I couldn't get jsFiddle to work for me, so it's just the whole thing.

How do I get the width and height of a HTML5 canvas?

It might be worth looking at a tutorial: MDN Canvas Tutorial

You can get the width and height of a canvas element simply by accessing those properties of the element. For example:

var canvas = document.getElementById('mycanvas');
var width = canvas.width;
var height = canvas.height;

If the width and height attributes are not present in the canvas element, the default 300x150 size will be returned. To dynamically get the correct width and height use the following code:

const canvasW = canvas.getBoundingClientRect().width;
const canvasH = canvas.getBoundingClientRect().height;

Or using the shorter object destructuring syntax:

const { width, height } = canvas.getBoundingClientRect();

The context is an object you get from the canvas to allow you to draw into it. You can think of the context as the API to the canvas, that provides you with the commands that enable you to draw on the canvas element.

HTML5 Canvas 100% Width Height of Viewport?

In order to make the canvas full-screen width and height always, meaning even when the browser is resized, you need to run your draw loop within a function that resizes the canvas to the window.innerHeight and window.innerWidth.

Example: http://jsfiddle.net/jaredwilli/qFuDr/

HTML

<canvas id="canvas"></canvas>

JavaScript

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

// resize the canvas to fill browser window dynamically
window.addEventListener('resize', resizeCanvas, false);

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

/**
* Your drawings need to be inside this function otherwise they will be reset when
* you resize the browser window and the canvas goes will be cleared.
*/
drawStuff();
}

resizeCanvas();

function drawStuff() {
// do your drawing stuff here
}
})();

CSS

* { 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 { display:block; } /* To remove the scrollbars */

That is how you properly make the canvas full width and height of the browser. You just have to put all the code for drawing to the canvas in the drawStuff() function.

Get canvas width and height using javascript

The canvas is a special case when it comes to the width and height.

The canvas.style.width and canvas.style.height define the width and height of the canvas as displayed on the page.

The canvas.width and canvas.height properties define the size of the canvas in pixels or the resolution of the canvas. The canvas resolution does not always match the canvas display size.

You can get the canvas resolution by just getting the width and height properties.

var width = canvas.width;
var height = canvas.height;

The canvas resolution will not have any units at the end so can be directly converted to a Number. The canvas.width and canvas.height properties are always in pixels.

If you do not set the canvas.width and canvas.height properties the canvas resolution will default to 300 by 150.

You can access the 2D context canvas via the context.canvas property. The context does not have a width and height property.

 // get resolution
var width = ctx.canvas.width;
var height = ctx.canvas.height;

// get display size. Note values will have units eg px,em,%
var displayWidth = ctx.canvas.style.width;
var displayHeight = ctx.canvas.style.height;

Oh and as pointed out in the comments. Style attributes will only be available if set.

Update HTML canvas width and height attributes automatically

Update 2

If I understand the question correct: the canvas has a flex CSS set (not shown in the question right now). It defines the canvas to be 2x the size of the other two elements, but since the canvas is resized and not its bitmap, the drawings are stretches as well and you want the bitmap to adopt dynamically.

If so, do this change to the code -

This update will leave the CSS rules of the canvas element alone and let flexbox handle it. It will read the actual pixel size of the element and then apply it to the bitmap so that data isn't stretched:

$(window).on("resize", function() {
var cnvs = $(".cnvs")[0]; // cache canvas element
var rect = cnvs.getBoundingClientRect(); // actual size of canvas el. itself

cnvs.width = rect.width;
cnvs.height = rect.height;
// ... redraw content here ...
}

Additionally, since resizing the window can produce a lot of events, you may want to consider "debouncing" so that you only deal with the more recent resize:

var timerID;
$(window).on("resize", function() {
clearTimeout(timerID);
timerID = setTimeout(function() {
var cnvs = $(".cnvs")[0]; // cache canvas element
var rect = cnvs.getBoundingClientRect(); // actual size of canvas el. itself

cnvs.width = rect.width;
cnvs.height = rect.height;
// ... redraw content here ...
}, 180); // adjust at will
}

This will delay the resizing/redrawing until 180ms has passed.

Size of HTML5 Canvas via CSS versus element attributes

The explanation is here: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#attr-canvas-width as seen in another post, thanks!

The intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.



Related Topics



Leave a reply



Submit