当前位置: 移动技术网 > IT编程>网页制作>Html5 > HTML5 Canvas如何实现纹理填充与描边(Fill And Stroke)

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

2019年07月25日  | 移动技术网IT编程  | 我要评论
演示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);

纹理图片:
 
三:运行效果
 
代码:

复制代码
代码如下:

<!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>

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网