(七)渐变 矩形渐变 放射渐变

createLinearGradient() 【4个参数,1起点x坐标,2起点y坐标,3终点x 4终点y】
addColorStop(0,"white")【接收两个参数,1开始渐变的位置0代表开始的位置】
addColorStop(1,"black")【参数同上,1代表结束的位置(可以写小数点)】

createRadialGradient() 【6个参数。1(x)/2(y) 开始渐变的中心点,3,圆的半径,4(x)/5(y)结束渐变圆的中心点,6结束渐变圆的半径】
addColorStop(0,"white")【同上】
addColorStop(1,"black")【同上】
【放射渐变的两个圆是同心圆,也就是参数 1,2 === 4,5】

var canvas = document.getElementById("canvas");

    if(canvas.getContext){
        var ctx = canvas.getContext("2d");

        //【要确保渐变元素的开始坐标和结束坐标与渐变对象的一致】

        //////////////////
        /////矩形渐变
        /////////////////

        // 编写渐变1:
        var gradient1 = ctx.createLinearGradient(70,70,120,120);//规定开始渐变跟结束渐变的坐标点
        gradient1.addColorStop(0,"blue");//规定开始渐变的颜色
        gradient1.addColorStop(1,"red");//规定结束渐变的颜色

        // 编写渐变2:
        var gradient2 = ctx.createLinearGradient(50,50,100,100);
        gradient2.addColorStop(0,"grey");
        gradient2.addColorStop(1,"black");

        ctx.beginPath();

        ctx.fillStyle = gradient2;//使用渐变
        ctx.fillRect(50,50,50,50);

        ctx.fillStyle = gradient1;//使用渐变
        ctx.fillRect(70,70,50,50);

        ctx.stroke();
        ctx.closePath();

        ////////////////////
        ////// 放射渐变
        ///////////////////

        var gradientArc = ctx.createRadialGradient(75,225,10,75,225,50);
            gradientArc.addColorStop(0,"white");
            gradientArc.addColorStop(1,"black");
        ctx.beginPath();

        ctx.fillStyle = gradientArc;
        ctx.fillRect(50,200,50,50);

        ctx.stroke();
        ctx.closePath();
    }
原文地址:https://www.cnblogs.com/chefweb/p/6046482.html