Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

How to set canvas height and width dynamically

var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');

function drawTextAndResize(text, fontSize, font){
  text = text || "hello world";
  fontSize =  fontSize || 48;
  font = font || "serif";
  // First we set the font to the context
  ctx.font = fontSize + 'px '+ font;
  // We set the size of our canvas accordingly to the width of our text
  canvas.width = ctx.measureText(text).width;
  // 1.3*fontSize is an approximation of the line height, for a complete way to get the height, refer to this answer : http://stackoverflow.com/a/17631567/3702797
  canvas.height = fontSize*1.3;
  // Since our context has been reset, we have to reset its font as well
  ctx.font = fontSize + 'px '+ font;
  // Finally we draw the text, approximately vertically centered
  ctx.fillText(text, 0,canvas.height/1.3);
  }

drawTextAndResize("This is some text", 32, "arial");
setTimeout(drawTextAndResize, 4000);
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #How #set #canvas #height #width #dynamically
ADD COMMENT
Topic
Name
9+4 =