html5 之 canvas 相关知识(二)API-fillStyle

王朝学院·作者佚名  2016-05-23
窄屏简体版  字體: 小  |  中  |  大  |  超大  

html5 之 canvas 相关知识(二)API-fillStyle颜色、样式和阴影fillStyle 设置或返回用于填充绘画的颜色、渐变或模式

定义和用法context.fillStyle=color|gradient|pattern;//指示绘图填充色的CSS颜色值|用于填充绘图的渐变对象线性或放射性|用于填充绘图的 pattern 对象

实例一:矩形绘制,也是最简单的使用方法。

context.fillStyle=color

<canvas id="canvas" width=300 height=150></canvas><script> var myCanvas = document.getElementById("canvas"); var cc = myCanvas.getContext("2d"); cc.fillStyle = "#ff0000"; cc.fillRect(100,25,100,100);//四个参数分别对应:x,y,w,h</script>

效果图

实例二:从上到下的渐变,矩形填充。

context.fillStyle=gradient

<canvas id="canvas" width=300 height=150></canvas><script> var myCanvas = document.getElementById("canvas"); var cc = myCanvas.getContext("2d"); var myGradient=cc.createLinearGradient(0,0,0,170); myGradient.addColorStop(0,"#ff0000"); myGradient.addColorStop(1,"#ffcc00"); cc.fillStyle=myGradient; cc.fillRect(100,25,100,100);</script>

效果图

createLinearGradient() 方法创建线性的渐变对象。

渐变可用于填充矩形、圆形、线条、文本等等。

提示:请使用该对象作为strokeStyle或fillStyle属性的值。

提示:请使用addColorStop方法规定不同的颜色,以及在 gradient 对象中的何处定位颜色。

context.createLinearGradient(x0,y0,x1,y1);//渐变开始点的 x 坐标,渐变开始点的 y 坐标,渐变结束点的 x 坐标,渐变结束点的 y 坐标

实例三:定义一个从左到右,由黑到红再到白的渐变,作为矩形的填充样式:

<canvas id="canvas" width=300 height=150></canvas><script> var myCanvas = document.getElementById("canvas"); var cc = myCanvas.getContext("2d"); var myGradient=cc.createLinearGradient(100,0,200,0); myGradient.addColorStop(0,"black"); myGradient.addColorStop(0.5,"red"); myGradient.addColorStop(1,"white"); cc.fillStyle=myGradient; cc.fillRect(100,25,100,100);</script>

实例四:绘图填充

context.fillStyle=pattern

<p align="center"><img src="img/lamp.gif" id="lamp" alt=""></p><canvas id="canvas2" width=300 height=150></canvas><script> var img=document.getElementById("lamp"); function drawImgRepat(){ var c=document.getElementById("canvas2"); var ctx=c.getContext("2d"); var pat=ctx.createPattern(img,"repeat");//repeat|repeat-x|repeat-y|no-repeat ctx.rect(0,0,128,96); ctx.fillStyle=pat; ctx.fill(); } img.onload = drawImgRepat;</script>

这里发现 一点小问题:1、图片需要在页面中;2、rect(0,0,128,96),如果改变开始x.y坐标,发现图片显示不完整,也就是说图片开始位置永远是0,0

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航