5、填充颜色

语雀

想要五彩斑斓的绘画,肯定少不了填充颜色的,颜色有两种,一种是纯色,一种是渐变的颜色

  • 填充颜色
  • 颜色的渐变

填充颜色

我们用过的fillStyle和strokeStyle 都可以为绘制设置填充的颜色。

填充的颜色可以为十六进制也可以为字符串,十六进制,十六进制简写、ragb颜色、rgb颜色

context.fillStyle = "red";//字符串
context.fillStyle = "#FF0000";//十六进制字符串
context.fillStyle = "#F00";//十六进制字符串简写
context.fillStyle = "rgba(255,0,0,1)";//rgba颜色
context.fillStyle = "rgb(255,0,0)";//rgb
context.fillStyle = "hsl(0,100%,50%)";//使用hsl()方法设置颜色,hsl(色相,饱和度,明度
)
context.fillStyle = "hsla(0,100%,50%,1)";//hsla()方法设置颜色。

渐变颜色

渐变颜色分为直线渐变和径向渐变
三部曲

  1. 添加渐变
  2. 给渐变颜色画断点
  3. 应用渐变

线性渐变

createLinearGradient(x1,y1,x2,y2)

var canvas=document.getElementById('canvas');
canvas.width=800;
canvas.height=800;
var context=canvas.getContext('2d');
context.beginPath();
context.rect(200,100,400,400);
//设置渐变 
var grd=context.createLinearGradient(200,300,600,300);
//设置渐变断点
grd.addColorStop(0,"black");//0位置
grd.addColorStop(0.5,"yellow");//0.5位置
grd.addColorStop(1,"black");//1位置
//应用渐变
context.fillStyle=grd;
//填充
context.fill();

image

填充矩形的快捷方式fillRect()

var canvas=document.getElementById('canvas');
canvas.width=800;
canvas.height=800;
var context=canvas.getContext('2d');
context.beginPath();
//添加渐变
var grd=context.createLinearGradient(10,10,200,10);
//给渐变颜色打断点
grd.addColorStop(0,"#2F9B2C")
grd.addColorStop(0.25,"#FBD220");
grd.addColorStop(0.5,"#7B006A");
grd.addColorStop(0.75,"#0396F3");
grd.addColorStop(1,"#9AC8FC");
//应用渐变颜色
context.fillStyle=grd;//记住这一步填充渐变颜色
context.fillRect(10,10,200,30);//想到与fill和rect组合
context.fillRect(10,40,150,30);
context.fillRect(10,70,200,30);

绘边矩形的快捷方strokeRect();

var canvas=document.getElementById('canvas');
canvas.width=800;
canvas.height=800;

var context=canvas.getContext('2d');
context.beginPath();
//添加渐变
var grd=context.createLinearGradient(10,10,200,10);
//添加颜色断点
grd.addColorStop(0,"#7388C1");
grd.addColorStop(0.25,"#6FC4C9");
grd.addColorStop(0.5,"#68BE81");
grd.addColorStop(0.75,"#F4C448");
grd.addColorStop(1,"#FDE0A6");
//应用渐变
context.strokeStyle=grd;
context.strokeRect(10,10,200,50);
context.strokeRect(10,60,150,50);
context.strokeRect(10,110,200,50);

径向渐变

径向渐变和线性渐变基本是一样的,只是在创建渐变的时候不一样。 createRadialGradient(x1,y1,r1,x2,y2,r2)

var canvas=document.getElementById('canvas');
canvas.width=800;
canvas.height=800;
var context=canvas.getContext('2d');
context.beginPath();
//创建渐变
var grd=context.createRadialGradient(400,400,150,400,400,800);
//设置颜色断点
grd.addColorStop(0,"#7388C1");
grd.addColorStop(0.25,"#6FC4C9");
grd.addColorStop(0.5,"#68BE81");
grd.addColorStop(0.75,"#F4C448");
grd.addColorStop(1,"#FDE0A6");
//应用渐变
context.fillStyle=grd;
context.fillRect(10,10,800,800);

猜你喜欢

转载自blog.csdn.net/weixin_39704454/article/details/81111070