HTML5 Canvas中 fillText() 和 strokeText() 的区别
Canvas现在越来越多地被运用到我们的项目中了,所以对Canvas的研究也得跟上呀,不然就被时代抛弃了。这次要给大家分享的是 HTML5 Canvas 中的 fillText 和 strokeText 的区别,代码及效果图片演示。
HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas</title>
<style>
canvas{border: 1px solid #ccc}
</style>
</head>
<body>
<canvas id="mycanvas" width='580' height='350' >浏览器不支持Canvas,请升级或改用其它浏览器!</canvas>
<script src="./js/canvas.js"></script>
</body>
</html>
JavaScript代码
window.onload = function(){
var mycanvas = document.getElementById('mycanvas');
var ctx = mycanvas.getContext('2d');
ctx.font ='68px Arial';
ctx.fillStyle = '#0099CC';
ctx.fillText('云库网 - 前端开发',25,130);
ctx.strokeStyle = '#000';
ctx.strokeText('云库网 - 前端开发',25,260);
}
最终效果展示
fillText()
HTML5 canvas fillText() 方法
定义及用法:fillText() 方法在画布上绘制填色的文本。文本的默认颜色是黑色。
浏览器支持:Internet Explorer 9、Firefox、Opera、Chrome 以及 Safari 支持 fillText() 方法。
语法:context.fillText(text,x,y,maxWidth);
text | 规定在画布上输出的文本。 |
x | 开始绘制文本的 x 坐标位置(相对于画布)。 |
y | 开始绘制文本的 y 坐标位置(相对于画布)。 |
maxWidth | 可选,允许的最大文本宽度,以像素计。 |
strokeText()
HTML5 canvas strokeText() 方法
定义及用法:strokeText() 方法是用来在画布上绘制文本(没有填色)。文本的默认颜色是黑色。
浏览器支持:Internet Explorer 9、Firefox、Opera、Chrome 以及 Safari 支持 strokeText() 方法。
语法:context.strokeText(text,x,y,maxWidth);
text | 规定在画布上输出的文本。 |
x | 开始绘制文本的 x 坐标位置(相对于画布)。 |
y | 开始绘制文本的 y 坐标位置(相对于画布)。 |
maxWidth | 可选,允许的最大文本宽度,以像素计。 |
注意:Internet Explorer 8 或更早的浏览器不支持 <canvas> 元素。所在放弃IE吧!
如果想给字体更换颜色,可以用例子中的 ctx.fillStyle = ‘#0099CC’;ctx.strokeStyle = ‘#000’;这两行代码分别是给fillText()方法和strokeText()方法所绘出的字更换颜色的。注意:fillText()方法对应的是 ctx.fillStyle = ‘#0099CC’;;strokeText() 方法对应的是 ctx.strokeStyle = ‘#000′;代码中的 ctx.font =’68px Arial’; 是定义字体及字体大小。
火狐MDN(fillText()):https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillText
火狐MDN(strokeText()):https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/strokeText
首发于:云库前端( http://yunkus.com )有什么问题可以在这里或者到我的博客留言!