1

I'm trying to manipulate a canvas using jquery, but no matter how I set the size something comes out different than when manipulating the html directly.

var size = 100;
var halfSize = size / 2;
drawCircle1();
drawCircle2();
drawCircle3();

// behaves as expected
function drawCircle1() {
  var canvas = document.getElementById('c1');
  var ctx = canvas.getContext("2d");
  ctx.translate(halfSize, halfSize);
  ctx.arc(0, 0, halfSize, 0, 2 * Math.PI);
  ctx.fill();
}

// draws a round circle, but the canvas size is not right
function drawCircle2() {
  var canvas = $('#c2')
  var ctx = canvas.get(0).getContext("2d");
  ctx.translate(halfSize, halfSize);
  ctx.arc(0, 0, halfSize, 0, 2 * Math.PI);
  ctx.fill();
}

// canvas sized correctly but circle stretched
function drawCircle3() {
  var canvas = $('#c3')
  canvas.height(size);
  canvas.width(size);
  var ctx = canvas.get(0).getContext("2d");
  ctx.translate(halfSize, halfSize);
  ctx.arc(0, 0, halfSize, 0, 2 * Math.PI);
  ctx.fill();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id='c1' width=100 height=100 style="border:solid 1px red"></canvas>
<canvas id='c2' width=100 height=100 style="border:solid 1px green"></canvas>
<canvas id='c3' style="border:solid 1px blue"></canvas>

1 Answers1

0

In the second example, I think height is just misspelled.

In the third example, jQuery is setting the CSS height and width. Doing so doesn't change the actual size of the canvas, so the canvas is distorted. Instead, set the width and height attributes, as shown below.

Also see Canvas width and height in HTML5.

var size = 100;
var halfSize = size / 2;
drawCircle1();
drawCircle2();
drawCircle3();

// behaves as expected
function drawCircle1() {
  var canvas = document.getElementById('c1');
  var ctx = canvas.getContext("2d");
  ctx.translate(halfSize, halfSize);
  ctx.arc(0, 0, halfSize, 0, 2 * Math.PI);
  ctx.fill();
}

// draws a round circle, but the canvas size is not right
function drawCircle2() {
  var canvas = $('#c2')
  var ctx = canvas.get(0).getContext("2d");
  ctx.translate(halfSize, halfSize);
  ctx.arc(0, 0, halfSize, 0, 2 * Math.PI);
  ctx.fill();
}

// canvas sized correctly but circle stretched
function drawCircle3() {
  var canvas = $('#c3')
  canvas.attr('width', size);
  canvas.attr('height', size);
  var ctx = canvas.get(0).getContext("2d");
  ctx.translate(halfSize, halfSize);
  ctx.arc(0, 0, halfSize, 0, 2 * Math.PI);
  ctx.fill();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id='c1' width=100 height=100 style="border:solid 1px red"></canvas>
<canvas id='c2' width=100 height=100 style="border:solid 1px green"></canvas>
<canvas id='c3' style="border:solid 1px blue"></canvas>
showdev
  • 28,454
  • 37
  • 55
  • 73