欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-10 14:08:16
本文为大家详细介绍下HTML5 Canvas Fill 与Stroke文字效果,基于Canvas如何实现纹理填充与描边、颜色填充与描边,具体代码如下,感兴趣的朋友可以参考下哈,希望对大家有所帮助... 13-07-15...
演示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);

纹理图片:
HTML5 Canvas如何实现纹理填充与描边(Fill And Stroke) 
三:运行效果
HTML5 Canvas如何实现纹理填充与描边(Fill And Stroke) 
代码:

复制代码
代码如下:

<!doctype html>
<html>
<head>
<meta http-equiv="x-ua-compatible" content="chrome=ie8">
<meta http-equiv="content-type" content="text/html;charset=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 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>
<pre>fill and stroke</pre>
<div id="my_painter">
<canvas id="text_canvas"></canvas>
</div>
</body>
</html>