相信在工做中你们都会接触到canvas的使用,通常状况下工做中都不会要求画特别可贵图形(用到特别难的图形,大多数选择插件实现)基于此,咱们学会一些常规的操做,而后结合项目进行一些扩展便可知足要求。html
canvas的画布是一个H5新增的标签。canvas
<canvas id="canvas" width="1000" height="600" style="background-color: aliceblue;">您的浏览器不支持canvas</canvas>
复制代码
canvas主要经过js画图,接下来咱们详细讲讲怎么画一些图形。浏览器
class Draw {
constructor(ctx) {
this.ctx = ctx;
}
// 画图方法
// ...
}
window.onload = function() {
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
const draw = new Draw(ctx);
// 一些画图操做
// ...
}
复制代码
strokeStyle和stroke是成对出现的。markdown
drawLine() {
this.ctx.moveTo(10,10); // 开始位置
this.ctx.lineTo(50, 10);
this.ctx.lineWidth = 5;
this.ctx.strokeStyle = 'red';
this.ctx.stroke();
}
复制代码
rect和strokeRect效果是同样的ui
// rect
drawRect() {
this.ctx.strokeStyle = 'red';
this.ctx.strokeRect(10, 50, 40, 20);
this.ctx.fillStyle = 'red';
this.ctx.fillRect(60, 50, 40, 20);
}
复制代码
上述的参数中,x,y 表示圆心的坐标,radius 是半径,start 开始弧度,end 结束弧度,anticlockwise 表示是不是逆时针。this
画圆或者弧形的时候要注意,若是没有beginPath,将会以画布的最左侧为起始点,图形以下
复制代码
// arc
drawArc() {
this.ctx.beginPath();
this.ctx.arc(100, 150, 50, Math.PI * 2, false);
this.ctx.closePath();
this.ctx.lineWidth = 5;
this.ctx.strokeStyle = 'red';
this.ctx.stroke();
this.ctx.fillStyle = 'green',
this.ctx.fill();
}
复制代码
无spa
drawText() {
this.ctx.fillStyle = 'red';
this.ctx.font = 'bold 40px 微软雅黑';
this.ctx.fillText('实心文本', 150, 200);
this.ctx.strokeStyle = 'green';
this.ctx.font = 'bold 40px 微软雅黑';
this.ctx.lineWidth = 1;
this.ctx.strokeText('空心文本', 150, 250)
}
复制代码
若是以为对你有帮助,请点赞或评论,我会更新下去插件