企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 线性渐变 语法: ```js let gnt = cxt.createLinearGradient(x1, y1, x2, y2) gnt.addColorStop(value1, color1) gnt.addColorStop(value2, color2) cxt.fillStyle = gnt cxt.fill() ``` 说明:在 Canvas 中,实现线性渐变有以下三个步骤 (1) 调用 createLinearGradient() 方法创建一个 linearGradient 对象,并赋值给变量 gnt (2) 调用 linearGradient 对象的 addColorStop() 方法 N 次,第 1 次表示渐变开始的颜色,第 2 次表示渐变结束时的颜色。然后第 3 次则以第 2 次渐变颜色作为开始颜色,进行渐变,依此类推。 (3) 把 linearGradient 对象赋值给 fillStyle 属性,并调用 fill() 方法来绘制有渐变色的图形。 ``` var gnt = cxt.createLinearGradient(x1, y1, x2, y2) ``` x1、y1 表示渐变色开始点的坐标,x2、y2 表示渐变色结束点的坐标,其有以下关系: - 如果 y1 与 y2 相同,表示沿水平方向从左到右渐变 - 如果 x1 与 x2 相同,表示沿着垂直方向从左到右渐变 - 如果 x1 与 x2 不相同,且 y1 与 y2 也不相同,则表示渐变色沿着矩形对角线方向渐变 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>渐变</title> </head> <body> <canvas id="canvas" style="margin:0 auto; border: 1px solid gray"></canvas> <script> window.onload = function () { let canvas = document.getElementById('canvas') canvas.width = 600 canvas.height = 600 let context = canvas.getContext('2d') let linearGrad = context.createLinearGradient(0,0,400,400) // 改变坐标来改变渐变方向 linearGrad.addColorStop(0,'white') // ColorStop 可以添加无数个,相当于一个中间状态 linearGrad.addColorStop(0.25,'yellow') // 只能用小数不能用百分号... linearGrad.addColorStop(0.5,'green') linearGrad.addColorStop(0.75,'blue') linearGrad.addColorStop(1,'black') context.fillStyle = linearGrad context.fillRect(0,0,800,800) } </script> </body> </html> <!-- createLinearGradient(xstart,ystart,xend,yend) 渐变开始及结束的 x y 坐标 创建线性渐变 addColorStop(stop,color) 规定渐变对象中的颜色和停止位置 --> ``` 下图分别是横向,纵向,对角的线型渐变的效果 ![](https://img.kancloud.cn/7f/f0/7ff01ccb2d7d2c0f0bc5e9444e9a302f_761x761.png =150x) ![](https://img.kancloud.cn/97/b7/97b7cb5f4c1cf15f3f04b8b4327dc553_755x757.png =150x) ![](https://img.kancloud.cn/cb/1e/cb1eb839368757eeef7642a2e44abfea_752x757.png =150x) ## 阴影 | 属性 | 说明 | | --- | --- | | shadowOffsetX | 阴影与图形的水平距离,默认值为 0。大于 0 时向右偏移,小于 0 时向左偏移 | | shadowOffsetY | 阴影与图形的垂直距离,默认值为 0。大于 0 时向下偏移,小于 0 时向上偏移 | | shadowColor | 阴影的颜色,默认为黑色 | | shadowBlur | 阴影的模糊值,默认为 0。该值越大,模糊度越强 | ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>canvas</title> </head> <body> <canvas id="canvas" width="1024" height="700" style="border: 1px solid gray; display: block; margin: 0 auto"></canvas> <script> window.onload = function(){ let cnv = document.getElementById('canvas') let cxt = cnv.getContext('2d') // 定义文字 const text = 'Canvas 阴影' cxt.font = "bold 60px 微软雅黑" // 定义阴影 cxt.shadowOffsetX = 5 cxt.shadowOffsetY = 5 cxt.shadowColor = 'LightSkyBlue' cxt.shadowBlur = 10 // 填充文字 cxt.fillStyle = 'HotPink' cxt.fillText(text, 10, 90) // 图片阴影 let image = new Image() image.src = './image.jpg' image.onload = function () { cxt.shadowOffsetX = 0 cxt.shadowOffsetY = 0 cxt.shadowColor = '#FF6666' cxt.shadowBlur = 10 cxt.fillRect(10, 150, 500, 281) cxt.drawImage(image, 10, 150) } } </script> </body> </html> ``` ![](https://img.kancloud.cn/ea/98/ea9856c762f9ea09a06742c084995cda_1332x600.png)