好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

HTML5 Canvas如何实现纹理填充与描边(Fill And Stroke)

演示 HTML5 canvas Fill 与 stroke 文字效果,基于Canvas如何实现纹理填充与描边。

一:颜色填充与描边
颜色填充可以通过fillStyle来实现,描边颜色可以通过strokeStyle来实现。 简单 示例
如下:

复制代码

代码如下:


// fill and stroke text
ctx.font = '60pt Cali br i';
ctx.lineWidth = 3;
ctx.strokeStyle = 'green';
ctx.strokeText('Hello World!', 20, 100);
ctx.fillStyle = ' red ';
ctx.fillText('Hello World!', 20, 100);


二:纹理填充与描边
HT ML 5 Canvas还支持纹理填充,通过加载一张纹理图像,然后创建 画笔 模式,创建纹理模式的API为ctx.createPattern(imageTexture,"re PE at");第二参数支持四个值,分别为]repeat-x], ]repeat-y], ]repeat],]no-repeat] 意思 是纹理分别沿着X轴,Y轴,XY 方向 沿重复 或者 不重复。纹理描边与填充的代码如下:

复制代码

代码如下:


VAR woo DF ill = ctx.createPattern(imageTexture,"repeat");
ctx.strokeStyle = woodfill;
ctx.strokeText('Hello World!', 20, 200);
// fill rectangle
ctx.fillStyle = woodfill;
ctx.fillRect(60, 240, 260, 440);


纹理图片:
&nbs p;
三:运行效果
 
代码:

复制代码

代码如下:


<!DOCTYPE html>
<html>
<head>
< ;m eta http-equiv="X-UA-Compatible" content="ch rom e=IE8">
<meta http-equiv="Content -t ype" content="text/html;charset=UTF-8">
<t IT le>Canvas Fill And Stroke Text Demo</title>
<link hr ef="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.h ei ght = canvas.parentNode.clientHeight;
if (!canvas.getContext) {
console.log("Canvas not supported. Please install 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.lineWidth = 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
setTimeout(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>
< h1 >HTML5 Canvas Text Demo - By Gloomy Fish </h1>
< PR e>Fill And Stroke</pre>
<div id="my_p ai nter">
<canvas id="text_canvas"></canvas>
</div>
</body>
</html>

总结

以上是 为你收集整理的 HTML5 Canvas如何实现纹理填充与描边(Fill And Stroke) 全部内容,希望文章能够帮你解决 HTML5 Canvas如何实现纹理填充与描边(Fill And Stroke) 所遇到的问题。

如果觉得 网站内容还不错, 推荐好友。

查看更多关于HTML5 Canvas如何实现纹理填充与描边(Fill And Stroke)的详细内容...

  阅读:18次