-1

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?

Shay Lempert
  • 311
  • 2
  • 9

3 Answers3

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');

http://jsfiddle.net/h2yJn/66/

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

Demo: https://jsfiddle.net/ofaghxfq/2/

Sever van Snugg
  • 571
  • 4
  • 12