注释很详细,直接上代码
新增内容:
1. 直线绘制方法
2. 折线绘制方法
3. 画笔颜色调整方法
4. 画笔粗细调整方法
项目结构:
源码:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
*{
margin: 0;
padding: 0;
}
</style>
<body>
</body>
<script src="./js/canvas.js"></script>
</html>
canvas.js
/**
* 创建画布
* @param {number} width - 宽度
* @param {number} height - 高度
* @returns {HTMLCanvasElement} -返回画布
*/
function createCanvas(width,height) {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
document.body.append(canvas);
return canvas;
}
/**
* 绘制直线
* @param {HTMLCanvasElement} canvas - 画布
* @param {string} color - 颜色
* @param {number} x1 - 起点x坐标
* @param {number} y1 - 起点y坐标
* @param {number} x2 - 终点x坐标
* @param {number} y2 - 终点y坐标
* @param {number} [lineWidth=1] - 线宽
* @returns {void} - 无返回值
*/
function drawLine(canvas,color,x1,y1,x2,y2,lineWidth=1) {
const ctx = canvas.getContext('2d');
ctx.beginPath();
//设置线条宽度
ctx.lineWidth = lineWidth;
//设置颜色
ctx.strokeStyle = color;
//移动到起点
ctx.moveTo(x1,y1);
//绘制直线
ctx.lineTo(x2,y2);
//绘制
ctx.stroke();
}
/**
* 绘制折线
* @param {HTMLCanvasElement} canvas - 画布
* @param {string} [color="red"] - 颜色
* @param {number[]} points - 坐标数组
* @param {number} [lineWidth=1] - 线宽
* @returns {void} - 无返回值
*/
function drawPolyline(canvas,color="red",points,lineWidth=1) {
const ctx = canvas.getContext('2d');
ctx.beginPath();
//设置线条宽度
ctx.lineWidth = lineWidth;
//设置颜色
ctx.strokeStyle = color;
//移动到起点
ctx.moveTo(points[0][0],points[0][1]);
//绘制折线
for(let i = 1; i < points.length; i++) {
ctx.lineTo(points[i][0],points[i][1]);
}
//绘制
ctx.stroke();
}
/**
* 开始
* @returns {void} - 无返回值
*/
function start() {
const canvas_1 = createCanvas(400,400);
drawLine(canvas_1,'red',0,0,100,100,3);
const canvas_2 = createCanvas(400,400)
let points=[[100,100],[200,300],[300,200],[400,100]]
drawPolyline(canvas_2,'blue',points,10);
}
start();
标签:canvas,入门,ctx,number,param,points,折线,lineWidth From: https://blog.csdn.net/m0_73756108/article/details/140379398效果演示: