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 BBut 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 cal开发者_开发技巧l. 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';
精彩评论