什么是canvas
canvas是H5里面的一个标签,canvas 标签只是图形容器,必须使用脚本(JavaScript )来绘制图形。
canvas能做什么
1.基础图形的绘制
2.文字的绘制
3.图片和视频的处理
4.动画的实现
5.小游戏的制作
canvas使用
<canvas>
<span>当前浏览器不支持 canvas</span>
</canvas>
准备工作(canvas有默认的尺寸 300x150)
// 选择canvas标签
const canvasElement= document.getElementById('canvasContainer')
// 选择画布的绘制的类型
const ctx = canvasElement.getContext('2d')
// 画布的尺寸
canvasElement.width = 600
canvasElement.height = 600
介绍一些简单用法
1.画直线
ctx.moveTo(100,100);
// 选择从起始位置开始,画到 200 200 的位置
ctx.lineTo(200,200);
// 第二条线
ctx.lineTo(0, 200);
// 闭合图形,有两条线以上的,能自动帮你连接到 起始点
ctx.stroke();
// ctx.lineTo(100,100);
ctx.closePath();
ctx.stroke()
2.画曲线
ctx.moveTo(0, 80)
// 二次贝塞尔曲线 贝塞尔控制点坐标 结束点坐标
ctx.quadraticCurveTo(60, 0, 120, 80)
ctx.stroke()
ctx.moveTo(0, 80)
// 三次贝塞尔曲线 第一个贝塞尔控制点坐标 第二个贝塞尔控制点坐标 结束点坐标
ctx.bezierCurveTo(100, 0, 200, 200, 300, 80)
ctx.stroke()
3.画矩形
// 第一二个参数是 起始点的X,Y,第三四个参数是 矩形的宽高
ctx.rect(50, 50, 200, 100);
ctx.stroke()
// 第一二个参数是 起始点的X,Y,第三四个参数是 矩形的宽高
ctx.strokeRect(50, 50, 200, 100);
// 第一二个参数是 起始点的X,Y,第三四个参数是 矩形的宽高 填充颜色
ctx.fillRect(50, 50, 200, 100);
4.画圆(顺时针的90度和逆时针的90度,是不一样的)
/*
* arc参数
* 圆的中心的 x 坐标
* 圆的中心的 y 坐标
* 圆的半径
* 起始角,以弧度计(弧的圆形的三点钟位置是 0 度)
* 结束角,以弧度计
* 可选。规定应该逆时针还是顺时针绘图。False = 顺时针,true = 逆时针
*/
ctx.arc(100, 100, 50, 0, Math.PI *2, 0);
ctx.stroke();
5.画圆角矩形
ctx.beginPath();
ctx.moveTo(70, 60);
// 弧的起点的 x 坐标 弧的起点的 y 坐标 弧的终点的 x 坐标 弧的终点的 y 坐标 弧的半径
ctx.arcTo(200, 60, 200, 70, 20);
ctx.arcTo(200, 180, 190, 180, 20);
ctx.arcTo(50, 180, 50, 170, 20);
ctx.arcTo(50, 60, 60, 60, 20);
ctx.stroke();
6.填充颜色
// 某一个固定的色值
ctx.fillStyle = '#0ff'
// 渐变色值
const bg = ctx.createLinearGradient(0, 0, 200, 50)
// 渐变的开始圆的坐标 开始圆的半径 渐变的结束圆坐标 结束圆的半径
// const bg = ctx.createRadialGradient(x0,y0,r0,x1,y1,r1)
bg.addColorStop(0, '#0ff')
bg.addColorStop(0.5, '#f0f')
bg.addColorStop(1, '#ff0')
ctx.fillStyle = bg
ctx.fillRect(0, 0, 200, 100);
7.画图片
const img = new Image();
img.src = 'https://dss3.baidu.com/-rVXeDTa2gU2pMbgoY3K/it/u=1987807581,1673564996&fm=202&mola=new&crop=v1';
img.onload = function () {
// createPattern() 方法在指定的方向内重复指定的元素
const bg = ctx.createPattern(img, 'no-repeat');
ctx.fillStyle = bg;
ctx.fillRect(0, 0, 300, 200);
// drawImage(img,sx,sy,swidth,sheight,x,y,width,height)
// ctx.drawImage(img, 0, 0)
}
8.画文字
ctx.font = '60px Arial'
// 空心文字
ctx.strokeText('文字', 100, 100)
// 填充颜色文字
ctx.fillText('文字', 200, 200)
9.画阴影
// 阴影颜色
ctx.shadowColor = '#0ff';
// 阴影大小
ctx.shadowBlur = 12;
// X轴偏移
ctx.shadowOffsetX = 10;
ctx.fillRect(50, 50, 300, 200);
10.画动画
/**
* 定义圆
*/
const circle = {
x: 30, // 水平方向的坐标
y: 300, // 垂直方向的坐标
size: 30, // 圆的半径
dx: 5, // 水平坐标的变化值
dy: 4 // 垂直坐标的变化值
}
/**
* 绘制圆
*/
function drawCirle() {
ctx.beginPath();
ctx.arc(circle.x, circle.y, 30, 0, Math.PI * 2);
ctx.fillStyle = 'purple';
ctx.fill();
}
/**
* 更新canvas实现动画效果
*/
function update() {
ctx.clearRect(0, 0, canvasElement.width, canvasElement.height);
drawCirle();
circle.x += circle.dx;
requestAnimationFrame(update);
}
update();