学习canvas 过程中的几点总结

1.canvas的画布大小与canvas元素大小

canvas尺寸分为两种,一种是canvas元素本身的尺寸,另一种是canvas画布的尺寸

  • canvas本身尺寸可以通过style样式来设置

    .canvas{
        width:100px;
        height:100px;
    }
    /* 设置了元素在浏览器可以看见的尺寸 */
  • canvas画布尺寸通过元素widthheight两个属性设置,也可以通过js给画布设置尺寸。默认尺寸为300*150

    <canvas width="100" height="100"></canvas>
    

    或者

    var canvas=document.getElementById("canvas");
    canvas.width = 100;
    canvas.height = 100;

    如果两个尺寸不一致,那么画出来的图形,和想象中的图形是有差距的。

2.扇形渐变的规律

扇形渐变的语法:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.createRadialGradient(x1, y1, r1, x2, y2, r2);
// 创建一个从以(x1, y1)点为圆心、r1为半径的圆到以(x2, y2)点为圆心、r2为半径的圆的径向渐变对象

渐变规律可以分为两种情况:

  • 两个圆同圆心,或者两个圆属于包含关系

    渐变从一个圆的圆周向另一个圆的圆周辐射渐变

    // 包含
    var grb = ctx.createRadialGradient(245,175,20,285,175,75);
    grb.addColorStop(0, "red");
    grb.addColorStop(0.5, "green");
    grb.addColorStop(1, "yellow");
    ctx.fillStyle = grb;
    
    ctx.fillRect(210,100,150,150);

    效果如下图的包含关系:

    图片描述

    扫描二维码关注公众号,回复: 11207238 查看本文章
  • 相交或相离

    在两个圆的切线与圆周组成范围内,从开始圆的圆周向结束圆的圆周渐变

    // 相交
    grb = ctx.createRadialGradient(440,175,75,520,175,50);
    grb.addColorStop(0, "red");
    grb.addColorStop(0.5, "green");
    grb.addColorStop(1, "yellow");
    ctx.fillStyle = grb;
    
    ctx.fillRect(380,100,200,150);
    
    // 相离
    grb = ctx.createRadialGradient(675,175,75,900,175,50);
    grb.addColorStop(0, "red");
    grb.addColorStop(0.5, "green");
    grb.addColorStop(1, "yellow");
    ctx.fillStyle = grb;
    
    ctx.fillRect(600,100,300,150);

    效果如上图的相交和相离,在切线与圆周组成的范围内渐变

猜你喜欢

转载自www.cnblogs.com/baimeishaoxia/p/12902224.html
今日推荐