7-1使用Canvas绘制简易几何坐标系

1.使用canvas技术绘制一个几何坐标系,每次刷新页面,每个矩形的颜色都不同。

1-1 HTML

设置画布宽高分别为600px,400px

<canvas id="canvas" width="600" height="400"></canvas>

1-2 CSS

设置画布边框

 <style>
        canvas {
            border: 2px solid rgb(214, 213, 213);
        }
</style>

1-3 JavaScript

<script>
    // 获取画布上下文对象
    const context = document.querySelector('#canvas').getContext('2d');

    // 绘画直角坐标系
    // 设置起始坐标:moveTo(x,y)
    context.moveTo(20, 20);
    // 设置拐点坐标
    context.lineTo(20, 380);
    // 设置线段粗细
    context.lineWidth = 3;
    // 设置拐角类型  可选值: miter(直角) round(圆角) bevel(斜切)
    context.lineJoin = 'bevel';
    // 设置线段描边样式  :默认黑色
    context.strokeStyle = '#999';
    // 设置终点坐标
    context.lineTo(580, 380);
    // 绘制线段
    context.stroke();

    // 绘制小三角箭头
    // beginPath():开辟一个新的绘制路径, 开启一个独立的作用域, 让不同的图形属性之间不要相互影响
    // y轴的小三角箭头
    context.beginPath();
    context.moveTo(10, 20);
    context.lineTo(20, 10);
    context.lineTo(30, 20);
    // 设置填充样式
    context.fillStyle = '#999';
    // 填充绘制小三角箭头
    context.fill();

    // x轴的小三角箭头
    context.beginPath();
    context.moveTo(580, 370);
    context.lineTo(590, 380);
    context.lineTo(580, 390);
    context.fillStyle = '#999';
    context.fill();

    // 绘制矩形  x,y:矩形的起始坐标,宽为:40px,  x:[20,570],y:[20,380]
    context.beginPath();
    // 定义每个矩形的起始坐标
    const rect = [{
            // h+y=380
            x: 40,
            y: 130,
            w: 40,
            h: 250
        },
        {
            x: 120,
            y: 30,
            w: 40,
            h: 350
        },
        {
            x: 200,
            y: 260,
            w: 40,
            h: 120
        },
        {
            x: 280,
            y: 50,
            w: 40,
            h: 330
        },
        {
            x: 360,
            y: 180,
            w: 40,
            h: 200
        },
        {
            x: 440,
            y: 280,
            w: 40,
            h: 100
        },
        {
            x: 520,
            y: 210,
            w: 40,
            h: 170
        }
    ];

    // 循环遍历矩形坐标列表
    rect.forEach(item => {
        // 生成[0,255]的随机数
        const r = getRandom(0, 255);
        const g = getRandom(0, 255);
        const b = getRandom(0, 255);
        // 设置每个矩形的填充颜色
        context.fillStyle = `rgb(${r},${g},${b})`;
        context.fillRect(item.x, item.y, item.w, item.h);
    });

    // 生成指定范围的随机函数
    function getRandom(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min);
    }
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值