搜尋
首頁web前端H5教程Html5 Canvas中支援對text文字進行渲染的範例程式碼(圖)

html5 canvas中支援對text文字進行渲染;
直接的理解就是把text繪製在畫布上,並且像圖形一樣處理它(可以加shadow、gradient、pattern、color fill等等);
#既然它的本質是文字,就會具有文字所特有的一些屬性 ;本篇的重點也在於此;
不過,在最後會增加一些圖形填充效果在text上應用的實例;

context.font:

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

字體屬性的設定與css中的類似;
範例:

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

context.measureText(message):
當我們提供一個文字message,呼叫此方法,
它會依據目前context設定的字型、大小等,傳回一個文字的度量資訊物件TextMetrics;
#當前html5 canvas中TextMetrics對象,只包含一個屬性,就是width;
可以用來確定目前給定字串文本的在目前環境下的寬度;
例如:

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



<!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>

## fillText([text],[x],[y],[maxWidth]):

#參數的意義:

text:要在canvas上要渲染的文字內容;x,y:代表開始渲染的點的位置座標;

##maxWidth:代表最大寬度;


與之搭配的設定文字的顏色屬性:fillStyle

#strokeText([text ],[x],[y],[maxWidth]):

參數的意義與fillText相同;與fillText相比,它指渲染文字的輪廓;
與之搭配的設定文字的色彩屬性:
strokeStyle#Canvas中有對文字對齊方式的支援,包括兩個選項:水平Horizo​​ntal alignment與垂直Vertical alignment;
#context.textAlign:文字水平對齊方式。可取屬性值: start, end, left,right, center。預設值:start.

######context.textBaseline######:文字垂直對齊方式。可取屬性值:top, hanging, middle,alphabetic, ideographic, ###bottom###。預設值: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);
}

以上是Html5 Canvas中支援對text文字進行渲染的範例程式碼(圖)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
掌握microdata:HTML5的分步指南掌握microdata:HTML5的分步指南May 14, 2025 am 12:07 AM

Microdatainhtml5enhancesseoanduserexperienceByByBybyBystructuredDatatoSearchEngines.1)useIteMscope,itemType,anditempropattributestomarkupcontentlikeSoreRoductSssSssSoRorevents.2)

HTML5表格中有什麼新功能?探索新輸入類型HTML5表格中有什麼新功能?探索新輸入類型May 13, 2025 pm 03:45 PM

html5introducesnewinputtypesthatenhanceSerexperience,簡化開發和iMproveAccessibility.1)自動validatesemailformat.2)優化優化,優化OmportizeSmizesemizesemizesemizesemizesemizeSmobobileWithAnumericKeyPad.3)和Simimplifydateandtimeputientupits,並重新替代了Forcustemolcustemolcustene。

理解H5:含義和意義理解H5:含義和意義May 11, 2025 am 12:19 AM

H5是HTML5,是HTML的第五個版本。 HTML5提升了網頁的表現力和交互性,引入了語義化標籤、多媒體支持、離線存儲和Canvas繪圖等新特性,推動了Web技術的發展。

H5:可訪問性和網絡標準合規性H5:可訪問性和網絡標準合規性May 10, 2025 am 12:21 AM

無障礙訪問和網絡標準遵循對網站至關重要。 1)無障礙訪問確保所有用戶都能平等訪問網站,2)網絡標準遵循提高網站的可訪問性和一致性,3)實現無障礙訪問需使用語義化HTML、鍵盤導航、顏色對比度和替代文本,4)遵循這些原則不僅是道德和法律要求,還能擴大用戶群體。

HTML中的H5標籤是什麼?HTML中的H5標籤是什麼?May 09, 2025 am 12:11 AM

HTML中的H5標籤是第五級標題,用於標記較小的標題或子標題。 1)H5標籤幫助細化內容層次,提升可讀性和SEO。 2)結合CSS可定製樣式,增強視覺效果。 3)合理使用H5標籤,避免濫用,確保內容結構邏輯性。

H5代碼:Web結構的初學者指南H5代碼:Web結構的初學者指南May 08, 2025 am 12:15 AM

HTML5構建網站的方法包括:1.使用語義化標籤定義網頁結構,如、、等;2.嵌入多媒體內容,使用和標籤;3.應用表單驗證和本地存儲等高級功能。通過這些步驟,你可以創建一個結構清晰、功能豐富的現代網頁。

H5代碼結構:組織內容以實現可讀性H5代碼結構:組織內容以實現可讀性May 07, 2025 am 12:06 AM

通過合理的H5代碼結構可以讓頁面在眾多內容中脫穎而出。 1)使用語義化標籤如、、等組織內容,使結構清晰。 2)通過CSS佈局如Flexbox或Grid控制頁面在不同設備上的呈現效果。 3)實現響應式設計,確保頁面在不同屏幕尺寸上自適應。

H5與較舊的HTML版本:比較H5與較舊的HTML版本:比較May 06, 2025 am 12:09 AM

HTML5(H5)與舊版本HTML的主要區別包括:1)H5引入了語義化標籤,2)支持多媒體內容,3)提供離線存儲功能。 H5通過新標籤和API增強了網頁的功能和表現力,如和標籤,提高了用戶體驗和SEO效果,但需注意兼容性問題。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。