Reputation: 346
I am using canvas to draw text, and on some mobile devices it intermittently gets stretched vertically, so the bottom of the text is where it is supposed to be, but the top of the text stretches to the top of the display. I am unable to replicate it myself on an iPhone 6+, but it has been reported to happen on an iPhone 6+, as well as other iPhones and Androids.
This is the code I use, pretty standard looking:
ctx.globalalpha = 1.0;
ctx.fillStyle = "white";
ctx.font = "40.0rem CenturyGothic";
ctx.textAlign = "center";
ctx.fillText("TOUCH TO START", width / 2, (height / 2) + 8, width);
The image that I draw behind the text is not stretched, so it's not the entire canvas that gets stretched, only the text that draws on the canvas.
I set the canvas width and height with this code in javascript:
canvas.width = window.innerWidth;
canvas.height = (1600 / 1000) * canvas.width;
And I set the width and height in css here:
#canvas {
width: 100%;
height: auto;
}
Has anyone else experienced this? Any ideas on how to address it?
Upvotes: 1
Views: 1727
Reputation: 1
The problem might have something to do with how the fillText
function handles the maxWidth
argument.
I had a similar problem. My text would look vertically stretched. Turned out it was horizontally squashed.
In my case, I expected the text to overflow to the next line, but all it does is shrink along the x-axis when it gets wider than maxWidth
(which could be why it doesn't always happen).
This alone wouldn't explain why your text stretched to the top of the screen, but along with other code I can imagine how it might happen.
Upvotes: 0
Reputation: 32207
I don't particularly like this way because it stretched pixels, but it will work for some basic things.
I'm writing the text to an off screen canvas, then drawing that image back onto the original canvas. When it's drawn back I'm stretching the image. Now that the stretch is ADDED to the original width and height. I did this because then width and height stay relative eg. your word may be a difference size every time.
https://jsfiddle.net/0xbtm4o1/
CanvasRenderingContext2D.prototype.stretchText = function(text, x, y, xw, xh) {
var c = document.createElement("canvas").getContext("2d");
c.font = this.font;
c.fillColor = this.fontColor;
var w = c.measureText(text).width;
var h = parseInt(this.font);
c.fillText(text, 0, h);
this.drawImage(c.canvas, 0, 0, w, h, x, y, w+xw, h+xh);
}
var ctx = document.getElementById("c").getContext("2d");
ctx.font = "20px Arial";
ctx.fillColor = "black";
ctx.stretchText("Hello World!", 10, 20, 0, 40);
Upvotes: 1