美文网首页
2020-06-22-Canvas笔记02-矩形绘制

2020-06-22-Canvas笔记02-矩形绘制

作者: cherry_liulei | 来源:发表于2020-06-22 11:31 被阅读0次

    矩形的绘制

    Canvas的API 提供了3个方法,分别用于矩形的清除、描边及填充

    • clearRect(double x, double y, double w, double h)

    • strokeRect(double x, double y, double w, double h)

    • fillRect(double x, double y, double w, double h)

    • 绘制一个最简单的矩形,起始位置(10,10),宽度100,高度100

    const canvas = document.getElementById('canvas');
    const context = canvas.getContext('2d');
    
    context.strokeRect(10, 10, 100, 100);
    
    绘制矩形.png
    • 给矩形填充颜色
    const canvas = document.getElementById('canvas');
    const context = canvas.getContext('2d');
    
    context.strokeRect(10, 10, 100, 100);
    
    context.fillStyle = 'orange';
    context.fillRect(20, 20, 100, 100);
    
    填充矩形.png
    • 清除矩形
      清除矩形的操作有点类似橡皮擦的效果。
    const canvas = document.getElementById('canvas');
    const context = canvas.getContext('2d');
    
    context.strokeRect(10, 10, 100, 100);
    
    context.fillStyle = 'orange';
    context.fillRect(20, 20, 100, 100);
    
    context.canvas.onmousedown = function(e) {
      context.clearRect(0, 0, 100, 100);
    }
    
    清除矩形.png
    • 设置绘制矩形的线宽
    const canvas = document.getElementById('canvas');
    const context = canvas.getContext('2d');
    context.lineWidth = 30;
    context.strokeRect(50, 50, 400, 200);
    
    设置lineWidth.png
    • 设置绘制矩形的lineJoin
      lineJoin的取值有3个:
      • bevel 斜角
      • round 圆角
      • miter 斜切
    const canvas = document.getElementById('canvas');
    const context = canvas.getContext('2d');
    context.lineJoin = 'round';
    context.lineWidth = 30;
    context.strokeRect(50, 50, 400, 200);
    
    绘制矩形的lineJoin-bevel.png 绘制矩形的lineJoin-round.png 绘制矩形的lineJoin-miter.png

    相关文章

      网友评论

          本文标题:2020-06-22-Canvas笔记02-矩形绘制

          本文链接:https://www.haomeiwen.com/subject/ftcytktx.html