(《HTML5 Canvas核心技术 图形/动画与游戏开发》学习[2])
fillStyle: 设置填充图形的颜色,渐变和模式。
strokeStyle: 设置用于笔触(描边)的颜色,渐变和模式。
用法一:设置颜色。属性值可以是任意有效的css颜色字串(RGB, RGBA, HSLA, 指定颜色名称)。
示例:#ffffff, rgba(100,100,100,0.8), rgb(255,255,0), hsla(40,82%,33%,0.6), burlywood, cadetblue等。。。。
用法二:设置渐变色和图案。
线性渐变示例:
var gradient=context.createLinearGradient(0,0,canvas.width,0);
gradient.addColorStop(0, 'blue');
gradient.addColorStop(0.25, 'white');
gradient.addColorStop(0.5, 'purple');
gradient.addColorStop(0.75, 'red');
gradient.addColorStop(1, 'yellow');
context.fillStyle=gradient;
context.rect(0,0,canvas.width,canvas.height);
context.fill();
其中,createLinearGradient()的四个参数按顺序为:渐变开始点的x坐标,渐变开始点的y坐标,渐变结束点的x坐标,渐变结束点的y坐标。
放射渐变示例:
var gradient=context.createRadialGradient(canvas.width/2,canvas.height,10,canvas.width/2,0,100);
和线性渐变只有gradient变量不同,createRadialGradient()参数为:渐变的开始圆的x坐标,渐变的开始圆的y坐标,开始圆的半径,渐变的结束圆的x坐标,渐变的结束圆的y坐标,结束圆的半径。
图案示例:
// JavaScript Document
var canvas=document.getElementById('canvas'),
context=canvas.getContext('2d'),
repeatRadio=document.getElementById('repeatRadio'),
repeatXRadio=document.getElementById('repeatXRadio'),
repeatYRadio=document.getElementById('repeatYRadio'),
noRepeatRadio=document.getElementById('noRepeatRadio'),
image=new Image();
function fillCanvasWithPattern(repeatString){
var pattern=context.createPattern(image,repeatString);
context.clearRect(0,0,canvas.width,canvas.height);
context.fillStyle=pattern;
context.fillRect(0,0,canvas.width,canvas.height);
context.fill();
}
repeatRadio.οnclick=function(e){
fillCanvasWithPattern('repeat');
};
repeatXRadio.οnclick=function(e){
fillCanvasWithPattern('repeat-x');
};
repeatYRadio.οnclick=function(e){
fillCanvasWithPattern('repeat-y');
};
noRepeatRadio.οnclick=function(e){
fillCanvasWithPattern('no-repeat');
};
image.src='babe.png';
image.οnlοad=function(e){
fillCanvasWithPattern('repeat');
};
.createPattern()语法:context.createPattern(要使用的图片,画布或者视频等元素,“重复方式”)