三:运行效果

首頁 >web前端 >H5教程 >HTML5 Canvas如何實作紋理填滿與描邊(Fill And Stroke)_html5教學技巧

HTML5 Canvas如何實作紋理填滿與描邊(Fill And Stroke)_html5教學技巧

WBOY
WBOY原創
2016-05-16 15:49:152031瀏覽

示範HTML5 Canvas Fill 與Stroke文字效果,基於Canvas如何實作紋理填滿與描邊。

一:顏色填充與描邊
顏色填充可以透過fillStyle來實現,描邊顏色可以透過strokeStyle來實現。簡單範例
如下:

複製程式碼
程式碼如下:


程式碼如下:


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);
紋理圖片:
 效果


 
代碼:
複製程式碼


複製程式碼



複製程式碼



複製程式碼



複製程式碼



複製程式碼



複製碼






Canvas Fill And Stroke Text Demo

<script> <br />var ctx = null; // global variable 2d context <br />var imageTexture = null; <br />window.onload = function() { <br />var canvas = document.getElementById("text_canvas"); <br />console.log(canvas.parentNode.clientWidth); <br />canvas.width = canvas.parentNode.clientWidth; <br />canvas.width = canvas.parentNode.clientWidth; <br />canvas. parentNode.clientHeight; <br />if (!canvas.getContext) { <br />console.log("Canvas not supported. Please install a HTML5 compatible browser."); <br />return; <br />} <br />} <br />return; / get 2D context of canvas and draw rectangel <br />ctx = canvas.getContext("2d"); <br />ctx.fillStyle="black"; <br />ctx.fillRect(0, 0, canvas.width, canvas.width, canvas. .height); <br />// fill and stroke text <br />ctx.font = '60pt Calibri'; <br />ctx.lineWidth = 3; <br />ctx.strokeStyle = 'green'; <br />ctx. strokeText('Hello World!', 20, 100); <br />ctx.fillStyle = 'red'; <br />ctx.fillText('Hello World!', 20, 100); <br />// fill and stroke by pattern <br />imageTexture = document.createElement('img'); <br />imageTexture.src = "../pattern.png"; <br />imageTexture.onload = loaded(); <br />} <br />imageTexture.onload = loaded(); </script>
} function loaded() { // delay to image loaded setTimeout(textureFill, 1000/30); } function textureFill() { // ctvar woodfate = ctvarx. 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); }

HTML5 Canvas Text Demo - By Gloomy Fish

Fill And Stroke
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn