1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【HTML】FirefoxのCanvasでも縦書きしたい!

Posted at

すべての始まり

そんなまさかね…と思い検証してみたところ…

image.png

ソース
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>縦書き</title>
  <style>
    canvas {
      border: 1px solid black;
    }
    .vertical {
      writing-mode: vertical-rl;
    }
  </style>
</head>
<body>
  <canvas id="canvas" class="vertical" width="500" height="500"></canvas>
  <script>
    const canvas = document.querySelector("#canvas");
    const context = canvas.getContext("2d");
    context.textBaseline = 'top';
    context.font = "24px serif";
    // x座標を24pxずらしているのは、こうしないとFirefoxでCanvas外に文字が描画されて見えないから
    context.fillText("私は「Foo!やったー!」と思った。", 24, 0);
  </script>
</body>
</html>

はぁ~(クソデカため息)

という訳でFirefoxをChrome化させる

drawChromeStyleVerticalText(
    document.querySelector("#canvas"),
    "私は「Foo!やったー!」と思った。",
    "24px serif", 100, 100
);

function drawChromeStyleVerticalText(canvas, text, font, x, y) {
    const context = canvas.getContext("2d");
    context.textBaseline = 'top';
    context.font = font;

    if (/^.*Firefox.*$/.test(window.navigator.userAgent)) {
        context.save();
        context.translate(0, 0);
        context.rotate(-Math.PI / 2);
        context.fillText(text, -x, y);
        context.restore();
    }
    else {
        context.fillText(text, x, y);
    }
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>縦書き</title>
  <style>
    canvas {
      border: 1px solid black;
    }
    .vertical {
      writing-mode: vertical-rl;
    }
  </style>
</head>
<body>
  <canvas id="canvas" class="vertical" width="500" height="500"></canvas>
  <script src="main.js"></script>
</body>
</html>

結果

image.png

OK!

おまけ

テキストが縦書きされたキャンバスを生成するライブラリ

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?