Drawing rotated text on a HTML5 canvas

后端 未结 5 1509
不知归路
不知归路 2020-11-28 04:06

Part of a web application I\'m developing requires me to create bar graphs to display various information. I figured, if the user\'s browser is capable, I would draw them us

5条回答
  •  我在风中等你
    2020-11-28 04:28

    Funkodebat posted a great solution which I have referenced many times. Still, I find myself writing my own working model each time I need this. So, here is my working model... with some added clarity.

    First of all, the height of the text is equal to the pixel font size. Now, this was something I read a while ago, and it has worked out in my calculations. I'm not sure if this works with all fonts, but it seems to work with Arial, sans-serif.

    Also, to make sure that you fit all of the text in your canvas (and don't trim the tails off of your "p"'s) you need to set context.textBaseline*.

    You will see in the code that we are rotating the text about its center. To do this, we need to set context.textAlign = "center" and the context.textBaseline to bottom, otherwise, we trim off parts of our text.

    Why resize the canvas? I usually have a canvas that isn't appended to the page. I use it to draw all of my rotated text, then I draw it onto another canvas which I display. For example, you can use this canvas to draw all of the labels for a chart (one by one) and draw the hidden canvas onto the chart canvas where you need the label (context.drawImage(hiddenCanvas, 0, 0);).

    IMPORTANT NOTE: Set your font before measuring your text, and re-apply all of your styling to the context after resizing your canvas. A canvas's context is completely reset when the canvas is resized.

    Hope this helps!

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var font, text, x, y;
    
    text = "Mississippi";
    
    //Set font size before measuring
    font = 20;
    ctx.font = font + 'px Arial, sans-serif';
    //Get width of text
    var metrics = ctx.measureText(text);
    //Set canvas dimensions
    c.width = font;//The height of the text. The text will be sideways.
    c.height = metrics.width;//The measured width of the text
    //After a canvas resize, the context is reset. Set the font size again
    ctx.font = font + 'px Arial';
    //Set the drawing coordinates
    x = font/2;
    y = metrics.width/2;
    //Style
    ctx.fillStyle = 'black';
    ctx.textAlign = 'center';
    ctx.textBaseline = "bottom";
    //Rotate the context and draw the text
    ctx.save();
    ctx.translate(x, y);
    ctx.rotate(-Math.PI / 2);
    ctx.fillText(text, 0, font / 2);
    ctx.restore();

提交回复
热议问题