简体   繁体   中英

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:
AA
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!?

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);

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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM