图像:位图,方大易失真,由像素点组成。
图形:矢量图,方大不易失真,由数学公式和函数计算得到。
canvas使用步骤:
在html中创建画布
<canvas class="myCanvas"></canvas>
在css中为画布做一个边框显示出范围:默认范围300px*150px,内联元素。
在js中
let canvas=document.querySelector(".myCanvas"); //获得画布
let ctx=canvas.getContext("2d"); //获得画笔
画布的尺寸可以在js中修改,
例:canvas.width=1000;canvas.height=400; 画布不会变形
1.绘制直线
ctx.moveTo(x,y); //起点
ctx.lineTo(x1,x2); //端点
ctx.strokeStyle="#颜色代码";
ctx.stroke(); //把起点端点连起来,描边
ctx.fillStyle="#颜色代码";
ctx.fill(); //路径填充
ctx.closePath(); //最后一个端点与起点连接
2.绘制矩形
ctx.rect(x,y,width,height); //绘制普通矩形
ctx.stroke();ctx.fill(); //普通矩形需要描边或填充
ctx.fillRect(x,y,width,height); //绘制填充矩形
ctx.strokeRect(x,y,width,height); //绘制描边矩形
ctx.clearRect(x,y,width,height); //清除矩形内图形
ctx.clearRect(0,0,canvas.offsetWidth/2,canvas.offsetHeight/2); //清除整个画布
ctx.moveTo(x,y);
ctx.lineTo(x1,y);
ctx.lineTo(x1,y1);
ctx.lineTo(x,y1);
ctx.closePath(); //将端点3与起点连接,对路径封口
ctx.stroke();
3.绘制弧形
ctx.arc(x,y,r,startAngle,endAngle,clockwise); //圆心,半径,起始角度,顺逆时针
ctx.stroke();
ctx.beginPath(); //重新绘制一条路径,上一条路径结束
4.文本文字
ctx.font="font-size font-family"; //文字样式设置
ctx.textAlign=" "; //水平方向对齐方式,取值:left/right/center
ctx.textBaseLine=" "; //垂直方向对齐方式,取值:top/middle/bottom/
ctx.strokeText(textContent,x,y); //描边文字
ctx.fillText(textContent,x,y); //填充文字