您好,登錄后才能下訂單哦!
這篇文章主要介紹h5 Canvas中Fill 與Stroke文字效果如何實現,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
一:顏色填充與描邊
顏色填充可以通過fillStyle來實現,描邊顏色可以通過strokeStyle來實現。簡單示例
如下:
// fill and stroke text ctx.font = '60pt Calibri'; ctx.lineWidth = 3; ctx.strokeStyle = 'green'; ctx.strokeText('Hello World!', 20, 100); ctx.fillStyle = 'red'; ctx.fillText('Hello World!', 20, 100);
二:紋理填充與描邊
HTML5 Canvas還支持紋理填充,通過加載一張紋理圖像,然后創建畫筆模式,創建紋理模式的API為ctx.createPattern(imageTexture,"repeat");第二參數支持四個值,分別為”repeat-x”, ”repeat-y”, ”repeat”,”no-repeat”意思是紋理分別沿著X軸,Y軸,XY方向沿重復或者不重復。紋理描邊與填充的代碼如下:
var woodfill = ctx.createPattern(imageTexture,"repeat"); ctx.strokeStyle = woodfill; ctx.strokeText('Hello World!', 20, 200); // fill rectangle ctx.fillStyle = woodfill; ctx.fillRect(60, 240, 260, 440);
紋理圖片:
三:運行效果
代碼如下:
<!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content=" chr ome=IE8"> <meta http-equiv="Content-type" content="text/html;char set =UTF-8"> <title>Canvas Fill And Stroke Text Demo</title> <link href="default.css" rel="stylesheet" /> <script> var ctx = null ; // global variable 2d context var imageTexture = null; window. onload = function() { var canvas = document .getElementById("text_canvas"); console.log(canvas.parentNode.clientWidth); canvas.width = canvas.parentNode.clientWidth; canvas. height = canvas.parentNode.clientHeight; if (!canvas.getContext) { console.log("Canvas not supported. Please inst all a HTML5 compatible browser."); return ; } // get 2D context of canvas and draw rectangel ctx = canvas.getContext("2d"); ctx.fillStyle="black"; ctx.fillRect(0, 0, canvas.width, canvas.height); // fill and stroke text ctx.font = '60pt Calibri'; ctx.li neW idth = 3; ctx.strokeStyle = 'green'; ctx.strokeText('Hello World!', 20, 100); ctx.fillStyle = 'red'; ctx.fillText('Hello World!', 20, 100); // fill and stroke by pattern imageTexture = document.createElement('img'); imageTexture.src = "../pattern.png"; imageTexture.onload = loaded(); } function loaded() { // delay to image loaded set Time out(textureFill, 1000/30); } function textureFill() { // var woodfill = ctx.createPattern(imageTexture, "repeat-x"); // var woodfill = ctx.createPattern(imageTexture, "repeat-y"); // var woodfill = ctx.createPattern(imageTexture, "no-repeat"); var woodfill = ctx.createPattern(imageTexture, "repeat"); ctx.strokeStyle = woodfill; ctx.strokeText('Hello World!', 20, 200); // fill rectangle ctx.fillStyle = woodfill; ctx.fillRect(60, 240, 260, 440); } </script> </head> <body> <h2>HTML5 Canvas Text Demo - By Gloomy Fish</h2> <pre>Fill And Stroke</pre> <p id="my_painter"> <canvas id="text_canvas"></canvas> </p> </body> </html>
以上是h5 Canvas中Fill 與Stroke文字效果如何實現的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。