着色区域
- 描边区域:
strokeStyle
代表了描边样式,描边区域的绘制方法是 stroke()、strokeRect()
或者strokeText()
。 - 填充区域:
fillStyle
代表了填充样式,填充区域的绘制方法是fill()
、fillRect()
或者fillText()
。
着色方式
- 纯色
- 渐变
- 纹理
纯色
-
书写方式(与css 一致):
- red
- #000000
- rgb(r,g,b)
- rgba(r,g,b,a)
-
赋值方式
ctx.fillStyle= ‘red’
ctx.strokeStyle= ‘ rgb(r,g,b) ‘
渐变
-
建立渐变对象的方式:
- 线性渐变
gradient=createLinearGradient(x1, y1, x2, y2)
- 径向渐变
gradient=createRadialGradient(x1, y1, r1, x2, y2, r2)
- 线性渐变
-
定义渐变的颜色节点
gradient.addColorStop(position, color)
-
赋值方式
ctx.fillStyle= gradient
ctx.strokeStyle= gradient
线性渐变
const linerGradient=ctx.createLinearGradient(x1,y1,x2,y2);
linerGradient.addColorStop(0,'red');
linerGradient.addColorStop(.5,'yellow');
linerGradient.addColorStop(1,'green');
ctx.fillStyle=linerGradient;
径向渐变
const radGradient=ctx.createRadialGradient(x1, y1, r1, x2, y2, r2);
radGradient.addColorStop(0,'red');
radGradient.addColorStop(.5,'yellow');
radGradient.addColorStop(1,'green');
ctx.fillStyle=radGradient;
纹理
-
建立纹理对象:
pattern=context.createPattern(image,"repeat|repeat-x|repeat-y|no-repeat");
-
为着色样式赋值
ctx.fillStyle= pattern
ctx.strokeStyle= pattern
const img=new Image();
img.src='./images/floor.jpg';
img.onload=function(){
const pt=ctx.createPattern(img,'repeat');
ctx.fillStyle=pt;
ctx.fillRect(
0,0,
canvas.width,canvas.height
);
}
const rec=document.getElementById('rec');
const canvas=document.getElementById('canvas');
const {clientWidth,clientHeight}=rec;
canvas.width=clientWidth;
canvas.height=clientHeight;
const ctx=canvas.getContext('2d');
//地板和瓷砖
const floor=new Image();
floor.src='./images/floor.jpg';
const tile=new Image();
tile.src='./images/tile.jpg';
//当所有图片都加载成功后再绘图
Promise.all([imgPro(floor),imgPro(tile)]).then(()=>{
//绘图方法
draw();
});
//建立Promise 对象,指定img 加载成功后,执行resolve
function imgPro(img){
return new Promise((resolve)=>{
img.onload=function(){
resolve(img);
}
});
}
//绘图
function draw(){
//纹理对象
const ptf=ctx.createPattern(floor,'repeat');
const ptt=ctx.createPattern(tile,'repeat');
//赋值
ctx.fillStyle=ptf;
ctx.strokeStyle=ptt;
//描边宽度
ctx.lineWidth=60;
//绘图
ctx.fillRect(0,0,clientWidth,clientHeight);
ctx.strokeRect(0,0,clientWidth,clientHeight);
}