# 颜色样式控制
# 改变颜色
需要在绘制之前设置绘制的颜色
# 设置全局透明度
const ctx = c1.value.getContext('2d')
//设置全局透明度
ctx.globalAlpha = 0.1
# strokeStyle属性 改变描边颜色
//设置爱心描边颜色
ctx.strokeStyle = "#ff00ff"
//绘制爱心
ctx.stroke(love)
# fillStyle属性 改变填充颜色
//设置爱心填充颜色
ctx.fillStyle = 'rgba(255,0,0,.5)'
//填充爱心
ctx.fill(love)
# 线性渐变
createLinearGradient(渐变起点x,渐变起点y,渐变终点x,渐变终点y)设置渐变的起点和终点addColorStop(颜色范围0~1,范围颜色)设置当前渐变范围的颜色
const ctx = c2.value.getContext('2d')
//设置渐变属性
//设置渐变的起点和终点
const linearGradient = ctx.createLinearGradient(0, 0, 300, 200)
//设置渐变的起点颜色和终点颜色
linearGradient.addColorStop(0, 'red')
linearGradient.addColorStop(0.5, 'green')
linearGradient.addColorStop(1, '#000')
ctx.fillStyle = linearGradient
//创建并填充一个矩形
ctx.fillRect(0, 0, 300, 200)
# 使用请求动画帧动态改变颜色值
const ctx = c2.value.getContext('2d')
let index = 0
const render = () => {
//清除画布
ctx.clearRect(0, 0, 300, 200)
index += 0.001
if ((index >= 1)) index = 0
//设置渐变属性
//设置渐变的起点和终点
const linearGradient = ctx.createLinearGradient(0, 0, 300, 200)
//设置渐变的起点颜色和终点颜色
linearGradient.addColorStop(0, 'red')
linearGradient.addColorStop(index, 'green')
linearGradient.addColorStop(1, '#000')
ctx.fillStyle = linearGradient
//创建并填充一个矩形
ctx.fillRect(0, 0, 300, 200)
//请求动画帧函数
requestAnimationFrame(render)
}
requestAnimationFrame(render)
# 径向渐变
createRadialGradient()接收两个圆作为参数 每个圆都包含 圆心坐标 半径createRadialGradient(渐变起点圆心x,渐变起点圆心y,渐变起点圆半径,渐变终点圆心x,渐变终点圆心y,渐变终点圆半径)
const ctx = c3.value.getContext('2d')
let index = 0
const render = () => {
//清除画布
ctx.clearRect(0, 0, 300, 200)
index += 0.001
if ((index >= 1)) index = 0
//设置渐变属性
//设置渐变的起点和终点
//createRadialGradient()接收两个圆作为参数 每个圆都包含 圆心坐标 半径
const radiaGradient = ctx.createRadialGradient(150, 100, 0, 150, 100, 100)
//设置渐变的起点颜色和终点颜色
radiaGradient.addColorStop(0, 'red')
radiaGradient.addColorStop(index, 'green')
radiaGradient.addColorStop(1, '#000')
ctx.fillStyle = radiaGradient
//创建并填充一个矩形
ctx.fillRect(0, 0, 300, 200)
//请求动画帧函数
requestAnimationFrame(render)
}
requestAnimationFrame(render)
# 圆锥渐变
createConicGradient()接收三个参数createConicGradient(开始渐变角度,渐变圆心位置x,渐变圆心位置y)
const ctx = c4.value.getContext('2d')
let index = 0
const render = () => {
//清除画布
ctx.clearRect(0, 0, 300, 200)
index += 0.001
if ((index >= 1)) index = 0
//设置渐变属性
//设置渐变的起点和终点
//createConicGradient()接收三个参数 createConicGradient(开始渐变角度,渐变圆心位置x,渐变圆心位置y)
const coneGradient = ctx.createConicGradient(0, 150, 100)
//设置渐变的起点颜色和终点颜色
coneGradient.addColorStop(0, 'red')
coneGradient.addColorStop(index, 'green')
coneGradient.addColorStop(1, '#000')
ctx.fillStyle = coneGradient
//创建并填充一个矩形
ctx.fillRect(0, 0, 300, 200)
//请求动画帧函数
requestAnimationFrame(render)
}
requestAnimationFrame(render)
# 填充图案样式
createPattern()方法接收两个参数createPattern(图片对象,图片重复方式)
const ctx = c5.value.getContext('2d')
//导入图片
const img = new Image()
img.src = 'src/assets/vue.svg'
//图片加载函数
img.onload = () => {
//创建图案加载对象
//createPattern()方法接收两个参数 createPattern(图片对象,图片重复方式)
const pattern = ctx.createPattern(img, "no-repeat")
//设置图形填充模式
ctx.fillStyle = pattern
//绘制图形
ctx.fillRect(0, 0, 300, 200)
}