canvas(三)图形样式

着色区域

  • 描边区域: 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);
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值