user1534664
user1534664

Reputation: 3418

HTML5 canvas text resizes

This must be obvious to most of you, so sorry for asking, but how come when I change the width of my canvas my text resizes as well? And how can I prevent this from happening?

code used:

canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
context.fillText("text",10,10);

btw: before I get voted down / bashed at, I tried searching about this for like twenty minutes.. no results.

Upvotes: 4

Views: 2379

Answers (2)

Mohit Srivastava
Mohit Srivastava

Reputation: 1919

This problem might occur due to changing the attributes by using CSS. It seems that canvas gets re-scaled when you access its properties through css. I think your problem might be solved if you use this in your javascript code instead of changing it through css :

document.getElementById("yourCanvasId").height = 150; // height you want to change to
document.getElementById("yourCanvasId").width = 150; // width you want to change to

Same problem occurred with me. I did this and the problem was solved. Hope it helps !

Upvotes: 1

Loktar
Loktar

Reputation: 35309

If you aren't re-sizing it using CSS You need to set the context font like so.

Live Demo

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

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

function drawText() {
    ctx.font = 'italic 20px Calibri';
    ctx.fillText("HELLO!", 100, 100);
}

window.addEventListener("resize", function() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    drawText()
});
drawText()​

If you are resizing the canvas element using css like the following example

canvas{
    width:200px;
}

Then theres not much you can do to fix it. When you resize the canvas using CSS you just stretch it, but the pixel density stays the same. You should never use css to resize the canvas element, rather you should be using the width and height properties via JS like I do in my example above.

Upvotes: 2

Related Questions