canvas入门

一、创建canvas画布

我们要在html里添加一个canvas标签,在js里获取这个元素。

canvas的主要属性有width height,我们可以用js修改这两个属性让canvas布满整个屏幕,达到自适应,然后就是获取2d画布:

<canvas id='canvas'></canvas>
/* 创建画布 */
let canvas = document.querySelector('#canvas');
//宽高自适应
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 获取2d画布
let ctx = canvas.getContext('2d');

二、绘制样式

/* 绘制样式 */
ctx.fillStyle = 'green'; // 填充属性
ctx.strokeStyle = 'black'; // 描边属性
ctx.lineWidth = 3; // 线条属性

三、绘制形状

ctx.beginPath(); // 开始路径

矩形(默认)

//填充矩形:ctx.fillRect(x坐标,y坐标,width宽度,height高度);
ctx.fillRect(50,50,100,100);
//描边矩形:ctx.strokeRect(x坐标,y坐标,width宽度,height高度);
ctx.strokeRect(200,200,100,100);

圆(弧)

//圆路径:ctx.arc(x坐标,y坐标,r半径,开始弧度,结束弧度,布尔值);
ctx.arc(200,400,50,Math.PI/180*0,Math.PI/180*360,false);
//填充圆
ctx.fill();
//描边圆
ctx.stroke();

线

//定义线的起始点
ctx.moveTo(460,460);
//定义目标点
ctx.lineTo(500,500);
//折线
ctx.lineTo(400,600);
//折线
ctx.lineTo(200,600);
//绘制线条
ctx.stroke();

多边形

//绘制等腰三角形
ctx.beginPath();
ctx.moveTo(200,200);
ctx.lineTo(150,300);
ctx.lineTo(250,300);
//闭合路径
ctx.closePath();
ctx.stroke();
原文地址:https://www.cnblogs.com/biubiuxixiya/p/8144268.html