0

I have a canvas tag without width and height attributes. The canvas has inline width and height. Now when I apply linearGradient over it, it doesn't cover whole canvas. Demo:

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");



var gradient1 = ctx.createLinearGradient(0, 0, 150, 0);

gradient1.addColorStop(0, "#123456");
gradient1.addColorStop(1, "#654321");
ctx.fillStyle = gradient1;

ctx.fillRect(0, 0, 150, 100);
canvas {
  border: 1px dotted red;
}
<canvas id="canvas" style="width: 150px; height: 100px;"></canvas>

Question1: Why doesn't whole 150px of canvas get covered? And if I add width="150" and height="100" attributes on canvas tag, why does it then fill whole canvas?

Question 2: In below script c.width returns 300px not 150px, why?

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");


console.log(c.width);
console.log(c.height);
canvas {
  border: 1px dotted red;
}
<canvas id="canvas" style="width: 150px; height: 100px;"></canvas>

Question3: Is this behavior due to something similar to svg viewBox?

user31782
  • 7,087
  • 14
  • 68
  • 143

1 Answers1

0

I'm not sure why the inline styling isn't working, but if you change your canvas element to this:

<canvas id="canvas" width="150px" height= "100px;"></canvas>

Then the console logs the correct value and the gradient fills the canvas. :) I don't know why you can't use the other method, but I do know that everywhere I've seen I think everyone who uses the html canvas specifies the width and height in this way. (unless they specify it in the javascript)

Here's a pen of your working code: https://codepen.io/Awesomennjawarrior/pen/zwmmPY

Caleb Bertrand
  • 410
  • 5
  • 15