Drawing rotated text on a HTML5 canvas

后端 未结 5 1510
不知归路
不知归路 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:32

    While this is sort of a follow up to the previous answer, it adds a little (hopefully).

    Mainly what I want to clarify is that usually we think of drawing things like draw a rectangle at 10, 3.

    So if we think about that like this: move origin to 10, 3, then draw rectangle at 0, 0. Then all we have to do is add a rotate in between.

    Another big point is the alignment of the text. It's easiest to draw the text at 0, 0, so using the correct alignment can allow us to do that without measuring the text width.

    We should still move the text by an amount to get it centered vertically, and unfortunately canvas does not have great line height support, so that's a guess and check thing ( correct me if there is something better ).

    I've created 3 examples that provide a point and a text with 3 alignments, to show what the actual point on the screen is where the font will go.

    enter image description here

    var font, lineHeight, x, y;
    
    x = 100;
    y = 100;
    font = 20;
    lineHeight = 15; // this is guess and check as far as I know
    this.context.font = font + 'px Arial';
    
    
    // Right Aligned
    this.context.save();
    this.context.translate(x, y);
    this.context.rotate(-Math.PI / 4);
    
    this.context.textAlign = 'right';
    this.context.fillText('right', 0, lineHeight / 2);
    
    this.context.restore();
    
    this.context.fillStyle = 'red';
    this.context.fillRect(x, y, 2, 2);
    
    
    // Center
    this.context.fillStyle = 'black';
    x = 150;
    y = 100;
    
    this.context.save();
    this.context.translate(x, y);
    this.context.rotate(-Math.PI / 4);
    
    this.context.textAlign = 'center';
    this.context.fillText('center', 0, lineHeight / 2);
    
    this.context.restore();
    
    this.context.fillStyle = 'red';
    this.context.fillRect(x, y, 2, 2);
    
    
    // Left
    this.context.fillStyle = 'black';
    x = 200;
    y = 100;
    
    this.context.save();
    this.context.translate(x, y);
    this.context.rotate(-Math.PI / 4);
    
    this.context.textAlign = 'left';
    this.context.fillText('left', 0, lineHeight / 2);
    
    this.context.restore();
    
    this.context.fillStyle = 'red';
    this.context.fillRect(x, y, 2, 2);
    

    The line this.context.fillText('right', 0, lineHeight / 2); is basically 0, 0, except we move slightly for the text to be centered near the point

提交回复
热议问题