演示HTML5 Canvas Fill 与Stroke文字效果,基于Canvas如何实现纹理填充与描边。
一:颜色填充与描边
颜色填充可以通过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);
纹理图片:
三:运行效果 代码:
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.height = canvas.parentNode.clientHeight; <br />if (!canvas.getContext) { <br />console.log("Canvas not supported. Please install a HTML5 compatible browser."); <br />return; <br />} <br />// 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.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 />function loaded() { <br />// delay to image loaded <br />setTimeout(textureFill, 1000/30); <br />} <br />function textureFill() { <br />// var woodfill = ctx.createPattern(imageTexture, "repeat-x"); <br />// var woodfill = ctx.createPattern(imageTexture, "repeat-y"); <br />// var woodfill = ctx.createPattern(imageTexture, "no-repeat"); <br />var woodfill = ctx.createPattern(imageTexture, "repeat"); <br />ctx.strokeStyle = woodfill; <br />ctx.strokeText('Hello World!', 20, 200); <br />// fill rectangle <br />ctx.fillStyle = woodfill; <br />ctx.fillRect(60, 240, 260, 440); <br />} <br /></script>
HTML5 Canvas Text Demo - By Gloomy Fish