search
HomeWeb Front-endH5 TutorialSample code that supports rendering text in Html5 Canvas (picture)

html5 canvas supports rendering text;
The direct understanding is to draw the text on the canvas, and like Treat it the same as graphics (you can add shadow, gradient, pattern, color fill, etc.);
Since its essence is text, it will have some attributes unique to text ;The focus of this article is also here;
However, at the end, some examples of applying graphic fill effects to text will be added;

context.font:

[font style] [font weight] [font size] [font face]

The setting of font attributes is similar to that in css;
Example:

context.font = "italic bold 24px serif"; context.font = "normal lighter 50px cursive";

context.measureText(message):
When we Provide a text message and call this method.
It will return the metric information of a text based on the font, size, etc. set by the current contextObjectTextMetrics;
The TextMetrics object in the current html5 canvas only contains one attribute, which is width;
can be used to determine the current given string text The width in the current environment;
For example:

var metrics = context.measureText(message);
var textWidth = metrics.width;


fillText([text],[x],[y],[maxWidth]):
##Parameter meaning:
text: required The text content to be rendered on the canvas;
x,y: represents the position coordinates of the point where rendering starts;
maxWidth: represents the maximum width;

Set the color attribute of the text with it: fillStyle


strokeText([text ],[x],[y],[maxWidth]):
The meaning of the parameter is the same as fillText; compared with fillText, it refers to the outline of the rendered text;
The matching color attribute of the text is set: strokeStyle

##Canvas has support for text alignment. Includes two options: horizontal Horizontal alignment and vertical Vertical alignment;

context.textAlign: text horizontal alignment. Possible attribute values: start, end, left, right, center. Default value: start.
context.textBaseline: Text vertical alignment. Possible attribute values: top, hanging, middle, alphabetic, ideographic, bottom. Default value: alphabetic.

Horizontal alignment选项:center|start|end|left|right
例:context.textAlign = "center";

Vertical alignment选项:top|hanging|middle|alphabetic|ideographic|bottom
例:context.textBaseline = "top";

当我们把一段文本渲染在canvas上时,文本本身显示在画布上,会占据一个矩形块(看不见的矩形,我们暂且称其为IBox(invisible bounding box));

这里提到的对齐方式,都是针些这个文本所占据的这个IBox来操作的(IBox有,上,下,左,右四条边线);

把字符串“HA”在画布的中心点位置(两条黑色直线相交点为中心);textAlign为默认值,应用不同的textBaseline所产生的效果如下图:

把字符串“HA”在画布的中心点位置(两条黑色直线相交点为中心);textBaseline为默认值,应用不同的textAlign所产生的效果如下图:

大家可以细细品味一下,它们的区别……

实例:

基本属性展示:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>test</title>
<script type="text/javascript" src="modernizr-latest.js"></script>
<script type="text/javascript">
window.addEventListener("load", eventWindowLoaded, false);

function eventWindowLoaded() {
canvasApp();
}

function canvasSupport() {
return Modernizr.canvas;
}

function eventWindowLoaded() {
canvasApp();
}

function canvasApp() {
var message = "your text";
var fillOrStroke = "fill";
var fontSize = "50";
var fontFace = "serif";
var textFillColor = "#ff0000";
var textBaseline = "middle";
var textAlign = "center";
var fontWeight = "normal";
var fontStyle = "normal";

if(!canvasSupport()) {
return;
}

var theCanvas = document.getElementById("canvasOne");
var context = theCanvas.getContext("2d");
var formElement = document.getElementById("textBox");
formElement.addEventListener(&#39;keyup&#39;, textBoxChanged, false);
formElement = document.getElementById("fillOrStroke");
formElement.addEventListener(&#39;change&#39;, fillOrStrokeChanged, false);
formElement = document.getElementById("textSize");
formElement.addEventListener(&#39;change&#39;, textSizeChanged, false);
formElement = document.getElementById("textFillColor");
formElement.addEventListener(&#39;change&#39;, textFillColorChanged, false);
formElement = document.getElementById("textFont");
formElement.addEventListener(&#39;change&#39;, textFontChanged, false);
formElement = document.getElementById("textBaseline");
formElement.addEventListener(&#39;change&#39;, textBaselineChanged, false);
formElement = document.getElementById("textAlign");
formElement.addEventListener(&#39;change&#39;, textAlignChanged, false);
formElement = document.getElementById("fontWeight");
formElement.addEventListener(&#39;change&#39;, fontWeightChanged, false);
formElement = document.getElementById("fontStyle");
formElement.addEventListener(&#39;change&#39;, fontStyleChanged, false);

drawScreen();

function drawScreen() {
context.fillStyle = "yellow";
context.fillRect(0, 0, theCanvas.width, theCanvas.height);

context.lineWidth = 1;
context.beginPath();
context.moveTo(theCanvas.width / 2, 0);
context.lineTo(theCanvas.width / 2, theCanvas.height);
context.stroke();
context.closePath();

context.beginPath();
context.moveTo(0, theCanvas.height/2);
context.lineTo(theCanvas.width, theCanvas.height/2);
context.stroke();
context.closePath();

//Text
context.textBaseline = textBaseline;
context.textAlign = textAlign;
context.font = fontWeight + " " + fontStyle + " " + fontSize + "px " + fontFace;
var xPosition = (theCanvas.width / 2);
var yPosition = (theCanvas.height / 2);
switch(fillOrStroke) {
case "fill":
context.fillStyle = textFillColor;
context.fillText(message, xPosition, yPosition);
break;
case "stroke":
context.strokeStyle = textFillColor;
context.strokeText(message, xPosition, yPosition);
break;
case "both":
context.fillStyle = textFillColor;
context.fillText(message, xPosition, yPosition);
context.strokeStyle = "#000000";
context.strokeText(message, xPosition, yPosition);
break;
}
}

function textBoxChanged(e) {
var target = e.target;
message = target.value;
drawScreen();
}

function fillOrStrokeChanged(e) {
var target = e.target;
fillOrStroke = target.value;
drawScreen();
}

function textSizeChanged(e) {
var target = e.target;
fontSize = target.value;
drawScreen();
}

function textFillColorChanged(e) {
var target = e.target;
textFillColor = "#" + target.value;
drawScreen();
}

function textFontChanged(e) {
var target = e.target;
fontFace = target.value;
drawScreen();
}

function textBaselineChanged(e) {
var target = e.target;
textBaseline = target.value;
drawScreen();
}

function textAlignChanged(e) {
var target = e.target;
textAlign = target.value;
drawScreen();
}

function fontWeightChanged(e) {
var target = e.target;
fontWeight = target.value;
drawScreen();
}

function fontStyleChanged(e) {
var target = e.target;
fontStyle = target.value;
drawScreen();
}

}
</script>
</head>
<body>
<div style="position: absolute; top: 50px; left: 50px;">
<canvas id="canvasOne" width="400" height="150">
Your browser does not support HTML5 Canvas.
</canvas>
<form>
<span>Text</span>
<input id="textBox"/>
<br/>
<span>Fill or Stroke</span>
<select id="fillOrStroke">
<option value="fill">fill</option>
<option value="stroke">stroke</option>
<option value="both">both</option>
</select>
<br/>
<span>Font</span>
<select id="textFont">
<option value="serif">serif</option>
<option value="sans-serif">sans-serif</option>
<option value="cursive">cursive</option>
<option value="fantasy">fantasy</option>
<option value="monospace">monospace</option>
</select>
<br/>
<span>font size</span>
<input type="range" id="textSize" min="0" max="200"    value="30"/>
<br/>
<span>font color</span>
<input id="textFillColor" value="FF0000"/>
<br/>
<span>font weight</span>
<select id="fontWeight">
<option value="normal">normal</option>
<option value="bold">bold</option>
<option value="bolder">bolder</option>
<option value="lighter">lighter</option>
</select>
<br/>
<span>font style</span>
<select id="fontStyle">
<option value="normal">normal</option>
<option value="italic">italic</option>
<option value="oblique">oblique</option>
</select>
<br/>
<span>textBaseLine</span>
<select id="textBaseline">
<option value="middle">middle</option>
<option value="top">top</option>
<option value="hanging">hanging</option>
<option value="alphabetic">alphabetic</option>
<option value="ideographic">ideographic</option>
<option value="bottom">bottom</option>
</select>
<br/>
<span>TextAlign</span>
<select id="textAlign">
<option value="center">center</option>
<option value="start">start</option>
<option value="end">end</option>
<option value="left">left</option>
<option value="right">right</option>
</select>
</form>
</div>
</body>
</html>

阴影效果: 

代换上面代码的drawScreen方法体

function drawScreen() {
context.fillStyle = "yellow";
context.fillRect(0, 0, theCanvas.width, theCanvas.height);
//Text
context.textBaseline = textBaseline;
context.textAlign = textAlign;
context.shadowColor = "#707070";
context.shadowOffsetX = 5;
context.shadowOffsetY = 5;
context.shadowBlur = 5;
context.font = fontWeight + " " + fontStyle + " " + fontSize + "px " + fontFace;
var xPosition = (theCanvas.width / 2);
var yPosition = (theCanvas.height / 2);
context.fillStyle = textFillColor;
context.fillText(message, xPosition, yPosition);
}

渐变效果:

代换View Code 代码段中的drawScreen方法

function drawScreen() {
context.fillStyle = "yellow";
context.fillRect(0, 0, theCanvas.width, theCanvas.height);
var gradient = context.createLinearGradient(0, 0, theCanvas.width, 0);
context.font = "italic bold 40px serif";
gradient.addColorStop(0, "#000000");
gradient.addColorStop(.5, "#FF0000");
gradient.addColorStop(1, "#00ff00");
var xPosition = (theCanvas.width / 2);
var yPosition = (theCanvas.height / 2);
context.fillStyle = gradient;
context.fillText("message", xPosition, yPosition);
}

The above is the detailed content of Sample code that supports rendering text in Html5 Canvas (picture). 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
H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

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.

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.