
一、设计思路光的色散是光学经典实验白光经三棱镜折射分解为红橙黄绿蓝靛紫。技术演示做两层①Canvas 画白光入射 → 三棱镜 → 七色光散开 → 屏幕承接的完整光路图七种色光按不同折射角画出②用七色块横向排列渲染光谱条与口诀对应。数据上把七色做成数组绘制与渲染共用一份数据。二、七色光谱数据单一数据源import{router}fromkit.ArkUI;EntryComponentstruct LightDispersion{// 七色光谱数据颜色值数组按 红→紫 排列privatespectrum:string[][#EF4444,#F97316,#FACC15,#22C55E,#3B82F6,#4F46E5,#7C3AED];// 与颜色一一对应的色名privatespectrumNames:string[][红,橙,黄,绿,蓝,靛,紫];privatesettings:RenderingContextSettingsnewRenderingContextSettings(true);privatectx:CanvasRenderingContext2DnewCanvasRenderingContext2D(this.settings);}三、Canvas 绘制色散光路核心代码privatedraw():void{constctxthis.ctx;constwctx.width;consthctx.height;ctx.clearRect(0,0,w,h);// 三棱镜三角形Path 三点闭合 填充描边ctx.fillStyle#E0F2FE;ctx.strokeStyle#0EA5E9;ctx.lineWidth2;ctx.beginPath();ctx.moveTo(w*0.42,h*0.2);ctx.lineTo(w*0.68,h*0.5);ctx.lineTo(w*0.42,h*0.8);ctx.closePath();ctx.fill();ctx.stroke();// 入射白光左上 → 棱镜左面ctx.strokeStyle#111827;ctx.lineWidth3;ctx.beginPath();ctx.moveTo(w*0.06,h*0.22);ctx.lineTo(w*0.42,h*0.5);ctx.stroke();ctx.fillStyle#111827;ctx.font13px sans-serif;ctx.textAligncenter;ctx.fillText(白光,w*0.14,h*0.16);// 出射七色光从棱镜右面散开越靠后偏折越大越向下for(leti0;ithis.spectrum.length;i){ctx.strokeStylethis.spectrum[i];// 每条光线用对应颜色ctx.lineWidth2.5;ctx.beginPath();conststartYh*0.5(i-3)*5;// 起点在棱镜右棱附近微错开constendYh*0.5(i-3)*22;// 终点逐渐散开ctx.moveTo(w*0.67,startY);ctx.lineTo(w*0.94,endY);ctx.stroke();// 色名标注颜色与光线一致ctx.fillStylethis.spectrum[i];ctx.fillText(this.spectrumNames[i],w*0.955,endY4);}// 承接屏幕竖线ctx.strokeStyle#E5E7EB;ctx.lineWidth3;ctx.beginPath();ctx.moveTo(w*0.94,h*0.1);ctx.lineTo(w*0.94,h*0.9);ctx.stroke();}四、光谱条 UIForEach 渲染七色块build(){Column(){// 顶部标题栏略Scroll(){Column({space:14}){// 原理卡Text(白光通过三棱镜后被分解成红、橙、黄、绿、蓝、靛、紫七种色光这是光的折射造成的不同色光折射率不同紫光偏折最大红光最小。).fontSize(13).fontColor(#4B5563).lineHeight(22).width(100%)// 色散光路示意图Canvas(this.ctx).width(100%).height(240).onReady((){this.draw();})// 七色光谱条ForEach 渲染 7 个色块每个带色名Column({space:8}){Text(七色光谱按顺序).fontSize(14).fontWeight(FontWeight.Bold).fontColor(#111827).width(100%)Row({space:2}){ForEach(this.spectrum,(color:string,index:number){Column({space:4}){Column().width(100%).height(34).backgroundColor(color)// 色块颜色取自数组.borderRadius(6)Text(this.spectrumNames[index])// 色名与颜色同下标对应.fontSize(11).fontColor(#4B5563)}.layoutWeight(1)// 七列均分宽度},(color:string)color)// key 颜色值}.width(100%)Text(顺序口诀红橙黄绿蓝靛紫).fontSize(12).fontColor(#9CA3AF).width(100%)}.width(100%).padding(16).borderRadius(16).backgroundColor(Color.White).border({width:1,color:#E5EAF2})}.padding(14)}.layoutWeight(1).scrollBar(BarState.Off)}.height(100%).width(100%).backgroundColor(#F4F6FA)}五、代码要点单数据源spectrum数组同时服务 Canvas 绘制与光谱条 UI改一处颜色全局生效。循环绘制七条出射光线用for循环 (i - 3)偏移量实现等差散开比手写七遍 draw 优雅。同下标对应spectrumNames[index]与颜色数组按下标对齐ForEach 第二个参数正是 index。Canvas 坐标系三棱镜、入射光、出射光、屏幕的相对位置全部按w/h比例计算适配任意屏幕。六、光的色散核心知识点要点内容现象白光经三棱镜分解为红橙黄绿蓝靛紫七色光色散原因不同色光折射率不同紫光偏折最大红光偏折最小结论白光不是单色光是复色光红绿蓝是光的三原色彩虹雨后小水珠充当三棱镜把阳光色散成七色红外线热效应强遥控器、红外夜视、测温枪在红光外侧紫外线荧光效应验钞、消毒在紫光外侧过量有害易错色散是折射不是反射七色顺序红橙黄绿蓝靛紫不可颠倒口诀红橙黄绿蓝靛紫白光分解有规律红外紫外看不见各有用途记心间