Reputation: 425
I am attempting to render some text to a seperate canvas like so:
var tmpCanvas = document.createElement("canvas");
var tmpContext = tmpCanvas.getContext('2d');
tmpContext.textAlign = 'center';
tmpContext.font = size + 'px';
tmpCanvas.width = tmpContext.measureText(txt).width;
tmpCanvas.height = size;
tmpContext.fillStyle = "#000";
tmpContext.fillRect(0, 0, tmpCanvas.width, tmpCanvas.height);
tmpContext.fillStyle = color;
tmpContext.fillText(txt, tmpCanvas.width / 2, tmpCanvas.height / 2);
This canvas is then rendered to the main canvas' centre:
context.drawImage(cachedText, (d_canvas.width / 2) - (cachedText.width / 2), (d_canvas.height / 2) - (cachedText.width / 2), cachedText.width, cachedText.height);
I am doing this, because the text that is drawn is quite complex so I do not want to repeat the drawing operation several times. However, the issue is that despite the fact that I have set the canvas size to be equal to the text size, the text is smaller than the canvas, and it is off center. How can I create a canvas/image object with a pre rendered text on it as I have attempted above.
Here is a fiddle to illustrate the problem: http://jsfiddle.net/x4t1vjam/
Upvotes: 1
Views: 1039
Reputation: 3578
So, as it turns out, there was a few problems with your code. First and foremost, when you set a font size on a canvas, you must also set a font type - in my example, it is set as a generic 'serif' font.
Secondly, your drawing code is in a weird order, so after the font size was being used to set the width of the canvas, it was being overridden before it could be used to draw the font.
Lastly, the positioning logic is wrong. I've tried the best I can quickly to fix it, but it'll need some tweaking. You can see it mostly working here;
http://jsfiddle.net/x4t1vjam/5/
The code will need cleaned up, possibly storing some of the values in variables earlier in the code to avoid declaring them twice. And because I can't post an answer without a code sample, here's where I've made my changes.
tmpContext.textAlign = 'center';
tmpContext.font = size + "px serif";
tmpCanvas.width = tmpContext.measureText(txt).width;
tmpCanvas.height = size;
tmpContext.fillStyle = "#000";
tmpContext.fillRect(0, 0, tmpCanvas.width, tmpCanvas.height);
tmpContext.fillStyle = color;
tmpContext.font = "100px serif";
tmpContext.fillText(txt, (tmpCanvas.width / 2) - tmpContext.measureText(txt).width / 2,
size);
Upvotes: 1