Robert Parham Robert Parham - 2 months ago 14
CSS Question

Can't make a square canvas inside a jQuery UI dialog

All I want is to make the canvas inside in the dialog a perfect square. For some reason it keeps rendering taller than wide.

Following is a minimal version of my code that duplicates the problem. At least in Firefox and Chrome.

$(function() {
var docwidth = $(document).outerWidth();
var modalwidth = (docwidth > 767) ? 750 : 450;

// #pscanvas is the div that wraps the canvas
$("#pscanvas").width(modalwidth / 10 * 9).height(modalwidth / 10 * 9);

// #psc is the canvas itself
$("#psc").width(modalwidth / 10 * 9).height(modalwidth / 10 * 9);

// #psc-dialog is the dialog div
$("#psc-dialog").dialog({
autoOpen: false,
width: modalwidth
});
$("#psc-dialog").dialog("open");
});


Here is a ---> jsFiddle

How can I can make the canvas (with the black border) a square?

Answer

Instead of using jQuery.width() and jQuery.height() methods, use width and height properties of HTMLElement as Canvas elements does not consider CSS properties.

$(function() {
  var docwidth = $(document).outerWidth();
  var modalwidth = (docwidth > 767) ? 750 : 450;
  $("#psc-dialog").width(modalwidth).height(modalwidth + 25);
  $("#pscanvas").width(modalwidth / 10 * 9).height(modalwidth / 10 * 9);
  $("#psc").get(0).width = (modalwidth / 10 * 9);
  $("#psc").get(0).height = (modalwidth / 10 * 9);
  $("#psc-dialog").dialog({
    autoOpen: false
  });
  $("#psc-dialog").dialog("open");
});

Fiddle Demo

Comments