When programming in HTML canvas, the js dimensions of the canvas don't always match the css dimensions. Why is this happening and how can I fix this?
Asked
Active
Viewed 77 times
-1
-
1Can you please share some code you tried? – raju Jul 09 '17 at 15:11
-
1Possible duplicate of [Resize HTML5 canvas to fit window](https://stackoverflow.com/questions/1664785/resize-html5-canvas-to-fit-window) – Kukic Vladimir Jul 09 '17 at 15:15
-
Canvas should not be sized with CSS. It should be sized with HTML attributes of JS dynamically setting of those attributes. – Scott Marcus Jul 09 '17 at 15:23
3 Answers
2
I've found the problem. I was setting the dimensions of the using CSS, when you actually have to set the width and height attributes. This was causing it to be stretched/skewed.
var canvas = $('<canvas/>').attr({width: cw, height: ch}).appendTo('body');
1
You can try to set the width and height of the canvas to be equal to the dimensions of the window object:
function createCanvas() {
var ctx = //the canvas context;
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
//your code
}
In addition, it is a good idea to set the body and html tags to the full width of the window:
body, html{
height: 100%;
width: 100%;
}

Kaloyan
- 106
- 1
- 3
- 8
1
You can also do this by using pure javascript and set the dimensions of the canvas in javascript depending on your CSS values:
//Get Canvas
var canvas = document.getElementById("canv");
// Get computed style of the canvas element.
var cstyle = window.getComputedStyle(canvas);
// Returns the width as str in px: e.g. 600px.
// Parse resolves that issue.
canv.width = parseInt(cstyle.width);
canv.height = parseInt(cstyle.height);

Sever van Snugg
- 571
- 4
- 12