canvas快速入门(二)直线与折线的绘画

注释很详细,直接上代码

新增内容:
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();

效果演示:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码对我眨眼睛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值