Canvas学习笔记(二)

274 阅读2分钟

这是有系统性学习canvas笔记的第二篇。本文将继续介绍CanvasRenderingContext2D的方法。

这是我参与8月更文挑战的第13天,活动详情查看:8月更文挑战

线

  • 设置线的宽度:ctx.lineWidth = value;

  • 设置线末端的样式:ctx.lineCap = style(butt|round|square)

其中,butt表示以方形结束,起点和末端分别在线段两端的中点。 round和square则会在两端分别增加一个矩形区域,一个为圆形,另一个为方形。

  • 设置线连接的样式:ctx.lineJoin = "round|bavel|miter"
  • 设置线和间隙的交替长度:ctx.setLineDash(Array<number>)

image.png

  • 设置虚线偏移量:ctx.lineDashOffset = value,负值为顺时针,正值为逆时针。

我们来设置一个蚂蚁线效果:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

let offset = 0;

function draw(){
    offset += 2;
    ctx.clearRect(0,0, canvas.width, canvas.height);
    ctx.setLineDash([4, 2]);
    ctx.lineDashOffset = offset;
    ctx.strokeRect(10,10, 100, 100);
    setTimeout(()=>{
        draw()
    },20)
}
draw()

填充和画笔样式

填充:fillStyle=color|gradient

画笔:strokeStyle=color|gradient

渐变和图案

canvas可以绘制渐变,太强大了。canvas里支持两种渐变:径向渐变和线性渐变,我们介绍一下线性渐变。

线性渐变

语法:ctx.createLinearGradient

//x0,y0 x1,y1分别表示渐变的起点和终点
ctx.createLinearGradient(x0, y0, x1, y1);


//设置一个三色的渐变
const gradient = ctx.createLinearGradient(0,0,100,100)
//0% 处设置为红色
gradient.addColorStop(0, 'red');
//50% 处设置为黄色
gradient.addColorStop(.5, 'yellow');
//100% 处设置为绿色
gradient.addColorStop(1, 'green');

//将渐变设置为填充色
ctx.fillStyle = gradient;
//绘制矩形
ctx.fillRect(20, 20, 200, 100);

接下来,我们介绍一下如何设置canvas图案。

图案

所谓的canvas图案,就是以一个位图为基准,将图案重复性地绘制到canvas上,语法为: ctx.createPattern(image, repetition)。效果类似于css里的background:url() repeat

ctx.createPattern(image, repetition);
//image:<img>,<video>,<canvas>,ImageData,Blob
//repetition:'repeat','repeat-x','repeat-y','no-repeat'

image.png

未完待续

感谢阅读