示範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); 二:紋理填充與描邊複製代碼
代碼如下:
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