search
HomeWeb Front-endH5 TutorialHow to wrap canvas text? Introduction to the method of wrapping text in canvas

html5中的canvas是用于绘制图形的,可以通过 JavaScript 来控制它绘制各种文本和图像,但是在使用 canvas 绘制文字的时候,我们可能想要让这些文字在某处按要求换行,这该如何实现呢?本篇文章将来给大家介绍关于canvas文字换行的方法,话不多说,下面我们来一起看看具体的内容。

在canvas中提供了将文本作为图片输出到画布上的功能,通常用到的函数主要有canvas.drawText 和canvas.fillText两个。

以canvas.fillText()函数为例,在canvas.fillText("information" , width , height , maxwidth )中包含四个参数,"information"表示文本输出的内容,width和height分别表示你想要输出的文本起始字符左上角的位置,而maxwidth则表示了该字符串的最大宽度,例如将maxwidth设为100,则无论字符串有多长,都将限制在100像素宽度内。

接下来我们来看一看将canvas文字换行的代码:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>canvas自动换行</title>
  <style type="text/css">
    * {
      margin: 0
    }
    #main {
      width: 400px;
      margin: 20px auto 0;
    }
    #canvas, #editableWarp, #editable, #hideText {
      width: 400px;
      height: 125px;
      padding: 0;
      border: 0;
      background: pink;
      color: blue;
      font-size: 14px;
      font-family: &#39;sans-serif&#39;;
      position: relative;
      z-index: 1
    }
    #hideText {
      z-index: 0;
      position: absolute;
       word-break: break-word;
      word-wrap: break-word;
    }
    p {
      line-height: 32px;
    }
  </style>
</head>
<body>
  <div id="main">
    <p>
      输入:
    </p>
    <div id="editableWarp">
      <div id="hideText"></div>
      <textarea id="editable" placeholder="请输入文字..."></textarea>
    </div>
    <p>
      canvas输出:
    </p>
    <canvas id="canvas" width="400" height="125">您的浏览器不支持canvas</canvas>
  </div>
  <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
  <script type="text/javascript">
    var $canvas = $(&#39;#canvas&#39;),
        $editable = $(&#39;#editable&#39;),
        $hideText = $(&#39;#hideText&#39;),
        ctx = $(canvas)[0].getContext("2d");
    $editable.keyup(function handleEdittable () {
      var txt = $editable.val(),
          html = convertText(txt);
      $hideText.html(html);
      drawText();
    });
    function convertText(txt) {
      var html = txt.replace(/(\S)/ig, &#39;<span>$1</span>&#39;);
      html = html.replace(/\n|\r/ig, &#39;<br>&#39;);
      html = html.replace(/\s/ig, &#39; &#39;);
      return html;
    }
    function drawText () {
      ctx.clearRect(0, 0, $(canvas).width(), $(canvas).height());
      var fontSize = $hideText.css(&#39;fontSize&#39;);
      ctx.font = fontSize + &#39; sans-serif&#39;;
      ctx.textAlign = &#39;conter&#39;;
      ctx.textBaseline = "top";
      ctx.fillStyle = &#39;red&#39;;
      $.each($("#hideText span"), function (i, item) {
        var pos = $(item).position();
        var txt = $(item).text();
        ctx.fillText(txt, pos.left, pos.top);
      });
    }
  </script>
</body>
</html>

canvas换行效果如下:

How to wrap canvas text? Introduction to the method of wrapping text in canvas

本篇文章到这里就结束了,关于canvas元素更多的知识可以参考HTML5开发手册学习具体内容。

The above is the detailed content of How to wrap canvas text? Introduction to the method of wrapping text in canvas. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5: How It Enhances User Experience on the WebH5: How It Enhances User Experience on the WebApr 19, 2025 am 12:08 AM

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

Deconstructing H5 Code: Tags, Elements, and AttributesDeconstructing H5 Code: Tags, Elements, and AttributesApr 18, 2025 am 12:06 AM

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment