大网数据广告活动
Web 标准与前端开发

CanvasRenderingContext2D: lang property

· 52CE 我爱测

The **`CanvasRenderingContext2D.lang`** property of the Canvas 2D API gets or sets the language of the canvas drawing context.

Canvas API

The CanvasRenderingContext2D.lang property of the Canvas 2D API gets or sets the language of the canvas drawing context.

Value

The lang property can take one of the following string values:

  • A BCP 47 language tag representing the language of the canvas context.
  • The string inherit, in which case the language is inherited from the lang attribute of the originating canvas element or the nearest available ancestor with an explicit lang set.
  • An empty string (""), which can be set to specify that the canvas context has no language.

The default value is inherit.

Description

Sometimes, you need to set a language for a canvas rendering context so that it knows how to render language-dependent features: for example, some fonts have certain characters rendered differently in different languages. An on-screen canvas context (CanvasRenderingContext2D) is always associated with a particular <canvas> element, so whenever you render content using it, it can derive the language from the value of the <canvas> element's lang attribute.

However, an off-screen canvas context (OffscreenCanvasRenderingContext2D) renders its content before it is associated with a <canvas> element, so it can't derive a rendering language from the lang attribute of the <canvas> element. The lang property addresses this issue, allowing you to set a language directly on a canvas rendering context, whether you are using an on-screen or off-screen canvas.

The inherit value

When the inherit value is used, the language of the canvas context is inherited from the lang attribute of the nearest-available HTML source:

  • In the case of an on-screen context, or an off-screen context that was transferred from an on-screen context, this will be the originating canvas element, provided it has a valid lang attribute set.
  • If a lang attribute is not available on an associated <canvas> element, which could be the case for an on- or off-screen context, this will be the nearest available ancestor with an explicit lang set, which is commonly the document root.

Due to technical limitations, the inherit value behaves differently for on-screen and off-screen canvases:

  • For on-screen canvases, the lang value of the context is inherited when the associated CanvasRenderingContext2D object is first created, and is updated dynamically if the lang attribute of the associated canvas is updated (either directly or by inheritance).
  • For off-screen canvases, the lang value is inherited when the associated OffscreenCanvasRenderingContext2D object is first created "as a snapshot"; subsequent updates to the lang attribute from which the offscreen context inherited its value do not change its lang attribute. For this reason, the language of an off-screen canvas can only be changed by setting its lang value explicitly.

Examples

Basic usage

const canvasElem = document.querySelector("canvas");
const ctx = canvasElem.getContext("2d");

// Get context language; returns "inherit" by default
console.log(ctx.lang);

// Set context language
ctx.lang = "en";
// Logs "en"
console.log(ctx.lang);

Demonstrating canvas context localization support

In this example, we render a text string to a 2D canvas context in a particular font that has language-dependent ligatures. We allow the canvas context's language to be adjusted so you can see the difference in rendering.

HTML

The HTML features a select element that allows you to choose a language — en (English) or tr (Turkish) — and a canvas element to render to.

<p>
  <label for="lang">Choose language:</label>
  <select id="lang" name="lang">
    <option>en</option>
    <option>tr</option>
  </select>
</p>
<canvas></canvas>

JavaScript

In the JavaScript, we first grab references to the <canvas> element, its CanvasRenderingContext2D, and the <select> element, then load the language-dependent font using the CSS Font Loading API. Once the font is loaded, we run an init() function. This function defines another function — drawText(), which draws some text to the canvas context that uses the loaded font, adds a change event listener to the <select> element, then calls drawText() so that the text is immediately drawn to the canvas when the page first loads.

const canvasElem = document.querySelector("canvas");
const ctx = canvasElem.getContext("2d");

const selectElem = document.querySelector("select");

const latoMediumFontFace = new FontFace(
  // Lato-Medium is a font with language specific ligatures
  "Lato-Medium",
  'url("https://mdn.github.io/shared-assets/fonts/Lato-Medium.ttf")',
);

latoMediumFontFace.load().then((font) => {
  document.fonts.add(font);
  init();
});

function init() {
  function drawText() {
    ctx.clearRect(0, 0, canvasElem.width, canvasElem.height);
    ctx.font = "30px Lato-Medium";
    ctx.color = "black";
    ctx.fillText("finish crafting", 50, 100);
  }

  selectElem.addEventListener("change", () => {
    document.documentElement.lang = selectElem.value;
    drawText();
  });

  drawText();
}

When the <select> value is changed, the change event handler function fires, which:

  • Sets the value of the <html> element's lang attribute to the <select> element value, effectively changing the language of the document.
  • Runs the drawText() function. The CanvasRenderingContext2D.lang property is set to inherit by default, therefore the canvas context inherits the language of the document.

Result

The example is rendered as follows:

demonstrating_canvas_context_localization_support

Try changing the document language using the <select> element. When the language is set to English, the font will be rendered with the "fi" ligature. However, when it is set to Turkish, the font will be rendered without the "fi" ligature, because that locale doesn't include it.

Language support for offscreen canvases

This example is the similar to the previous example, except that the font is rendered to an OffscreenCanvasRenderingContext2D then the resulting bitmap is transferred to the on-screen <canvas> to display.

In addition, because an inherited off-screen canvas language is only set once, and not dynamically updated if the inherited lang attribute value is changed, we explicitly set the lang property on the OffscreenCanvasRenderingContext2D instead.

HTML

<p>
  <label for="lang">Choose language:</label>
  <select id="lang" name="lang">
    <option>en</option>
    <option>tr</option>
  </select>
</p>
<canvas></canvas>

JavaScript

The JavaScript works in the same way as the previous example, except that:

  • The on-screen canvas context is defined as an ImageBitmapRenderingContext.
  • We define a new OffscreenCanvasRenderingContext2D to draw the text onto, transfer the result to a bitmap using OffscreenCanvas.transferToImageBitmap, then render it on the <canvas> using ImageBitmapRenderingContext.transferFromImageBitmap.
  • When the <select> value is changed, we update the lang property directly on the OffscreenCanvasRenderingContext2D instead of changing the <html> lang attribute value.
const canvasElem = document.querySelector("canvas");
const ctx = canvasElem.getContext("bitmaprenderer");

const offscreen = new OffscreenCanvas(canvasElem.width, canvasElem.height);
const offscreenCtx = offscreen.getContext("2d");

const selectElem = document.querySelector("select");

const latoMediumFontFace = new FontFace(
  // Lato-Medium is a font with language specific ligatures.
  "Lato-Medium",
  'url("https://mdn.github.io/shared-assets/fonts/Lato-Medium.ttf")',
);

latoMediumFontFace.load().then((font) => {
  document.fonts.add(font);
  init();
});

function init() {
  function drawText() {
    offscreenCtx.clearRect(0, 0, canvasElem.width, canvasElem.height);
    offscreenCtx.lang = selectElem.value;
    offscreenCtx.font = "30px Lato-Medium";
    offscreenCtx.color = "black";
    offscreenCtx.fillText("finish crafting", 50, 100);

    const bitmap = offscreen.transferToImageBitmap();
    ctx.transferFromImageBitmap(bitmap);
  }

  selectElem.addEventListener("change", () => {
    drawText();
  });

  drawText();
}

Result

The example is rendered as follows:

language_support_for_offscreen_canvases

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。