Wednesday 29 August 2012

Resize html5 canvas width/height element to its content

I   needed method to resize the width of my html5 canvas so that it was the total width of its content.

Im looking for a similar method to the one below. Unfortunately you can't change the width of a canvas element half way through your code with out redrawing it.... pants.

I think theirs away to save the content of the canvas to an image before you re-size the width.
After which you simply redraw the content after re-size.
...I couldnt get it to work so my codes a little bit more drawn out.




var canvas;
var context;
var width;
var height;

function domLoaded(e){
canvas = document.getElementById("scroller");
context = canvas.getContext("2d");
width = canvas.getAttribute('width');
height = canvas.getAttribute('height');
var imageObj = new Image();
canvas.style.backgroundColor="red";

imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
var txt = "Doesnt matter how much text you put here the canvas will resize.";
context.font = "15pt Calibri";
context.fillText(txt,imageObj.width, 15);
var totalWidth = context.measureText(txt).width+imageObj.width;
canvas.width = totalWidth;

width = canvas.getAttribute('width');
context.drawImage(imageObj, 0, 0);
context.font = "15pt Calibri";
context.fillText(txt,imageObj.width, 15);
};
imageObj.src = "http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg";



}
document.addEventListener("DOMContentLoaded", domLoaded);

No comments: