AlonAlon
AlonAlon

Reputation: 215

HTML5: Canvas width and height

Consider:

<canvas id="myCanvas" width="200" height="300" />

Are those units in pixels? If not, is there a workaround to change it?

Upvotes: 2

Views: 1556

Answers (3)

user1693593
user1693593

Reputation:

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";

Upvotes: 3

Smile0ff
Smile0ff

Reputation: 798

use css to setup your canvas styles

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

 <style>

    #el{
         display: block;
         width:100%;
         height: 100%;
     }     

 </style>

Upvotes: 0

kslice917
kslice917

Reputation: 1

Almost all size parameters in HTML5 are going to be in pixels. If you're experiencing issues drawing the canvas with your current code, try taking out the self-closing block at the end:

 <canvas id="myCanvas" width="200" height="300"></canvas>

You may also consider viewing the properties of the canvas element as defined by W3 Schools: http://www.w3schools.com/html/html5_canvas.asp

Upvotes: 0

Related Questions