nvcnvn
nvcnvn

Reputation: 5175

HTML5 canvas issue?

Here is my JS code:

function Show(output, startX, startY){
    var c = document.getElementById("myCanvas");
    var context = c.getContext("2d");

    context.fillText  ("A" , startX, startY);

    context.font         = 'bold 20px sans-serif';
    context.fillText  ("B" , startX, startY + 50);
}
Show(outputcpu, 50, 50);
Show(outputio, 150, 50);

what I expect is some thing like:
A A
B B

But I'm not sure why what i get is:
A A
B B
I think the issue due to context.font last until the next function call. But I don't know how to stop it! Any idea!?

Upvotes: 0

Views: 252

Answers (2)

Declan Cook
Declan Cook

Reputation: 6126

You'll need to reset the font before you draw - try:

function Show(output, startX, startY){
    var c = document.getElementById("myCanvas");
    var context = c.getContext("2d");
    context.font = ' 20px sans-serif';
    context.fillText  ("A" , startX, startY);

    context.font = 'bold 20px sans-serif';
    context.fillText  ("B" , startX, startY + 50);
}
Show(outputcpu, 50, 50);
Show(outputio, 150, 50);

Here is a fiddle - http://jsfiddle.net/8Tuzp/

EDIT:

If you really don't like changing the font twice (I see no problem with doing so), you can save the canvas state and restore it once you have draw the bold text. Restoring the canvas context back to before you changed the font.

    function Show(output, startX, startY){
    var c = document.getElementById("myCanvas");
    var context = c.getContext("2d");
    context.save();
    context.fillText  ("A" , startX, startY);
    context.font = 'bold 20px sans-serif';
    context.fillText  ("B" , startX, startY + 50);
    context.restore();
}
Show(null, 50, 50);
Show(null, 150, 50);

Upvotes: 3

Jakub Wieczorek
Jakub Wieczorek

Reputation: 1919

You need to set the font weight back to normal as context properties are persistent across getContext() calls:

context.fillText  ("A" , startX, startY);
context.font         = 'bold 20px sans-serif';
context.fillText  ("B" , startX, startY + 50);
context.font         = '20px sans-serif';

Upvotes: 2

Related Questions