Search code examples
javascriptangulartypescriptcanvashtml5-canvas

Rotate Text orientation on Canvas


I have a canvas in my Angular application where user can play around with the coordinates of some fixed shapes(8 texts and 1 rectangle). I want to be able to be able to allow user to also select the orientation of the text i.e. show horizontal or vertical. How can I achieve this behaviour. Appreciate any help.

redrawLabel(result: ISerialLabelDesign) {
    console.log('inside redrawLabel');
    this.clearDrawing();
    this.shapesToDrawArray.length = 0;
    console.log(result); // giving the entire form.value object
    this.defaultLabelWidth = 300//result.labelWidth * 3.7795;  // convert from mm to pixel
    this.defaultLabelHeight = 300//result.labelHeight * 3.7795;
    this.renderDrawing(result);
    this.startDrawing(this.shapesToDrawArray);
}

startDrawing(shapesToDraw: Shape[]) {
    console.log('inside startDrawing::');
    for (var i = 0; i < shapesToDraw.length; i++) {
        if (shapesToDraw[i].type === 'barcode') {
            this.drawRectangle(this.context, shapesToDraw[i].x, shapesToDraw[i].y, shapesToDraw[i].w, shapesToDraw[i].h);
        } else if (shapesToDraw[i].type === 'text') {
            this.drawText(this.context, shapesToDraw[i].text, shapesToDraw[i].x, shapesToDraw[i].y, shapesToDraw[i].w, shapesToDraw[i].h);
        }
    }
}

private drawRectangle(context: CanvasRenderingContext2D, x: number, y: number, w: number, h: number) {
    console.log('inside drawRectangle');
    context.strokeRect(x, y, w, h);
}

private drawText(context: CanvasRenderingContext2D, text: string, x: number, y: number, w: number, h: number) {
    context.fillStyle = 'black';
    context.font = '8px Arial';
    context.fillText(text, x, y);
}

enter image description here


Solution

  • You can rotate your text with rotate() as followed:

    private drawText(context: CanvasRenderingContext2D, text: string, x: number, y: number, w: number, h: number) {
        context.fillStyle = 'black';
        context.font = '8px Arial';
        context.rotate(Math.PI / 2); // Rotation of the text
        context.textBaseline = 'middle';
        context.textAlign = 'center';
        context.fillText(text, x, y);
    }