如何在Two.js中为位图添加颜色滤镜(色调调整)?
解决Two.js Sprite位图色调调制无效的问题
为什么原有方法不生效
- CSS
filter是DOM元素的样式,Two.js创建Texture时只会读取图片的原始像素数据,不会应用DOM的CSS样式,因此设置el.style.filter无效。 - Sprite的
fill属性仅针对矢量图形生效,位图Sprite不支持该属性。
解决方案
方法1:用Canvas预处理图片(静态色调)
先通过Canvas绘制并调整图片颜色,再用处理后的Canvas创建Two.js纹理:
const img = new Image(); img.crossOrigin = "anonymous"; img.src = "https://i.imgur.com/Dx200x9.png"; img.onload = () => { // 创建临时Canvas处理色调 const canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; const ctx = canvas.getContext('2d'); // 绘制原始图片 ctx.drawImage(img, 0, 0); // 用混合模式叠加绿色半透明色调 ctx.globalCompositeOperation = 'multiply'; ctx.fillStyle = 'rgba(0, 255, 0, 0.5)'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.globalCompositeOperation = 'source-over'; // 恢复默认合成模式 // 基于处理后的Canvas创建Sprite const texture = two.makeTexture(canvas); const sprite = two.makeSprite(texture, 0, 0); };
你也可以用Canvas原生filter实现更复杂效果,替换上面的混合模式代码:
ctx.filter = 'opacity(0.5) drop-shadow(0 0 5px green)'; ctx.drawImage(img, 0, 0);
方法2:自定义着色器(动态调整色调)
如果需要动态修改色调,可使用Two.js的自定义着色器直接在WebGL层面调整像素颜色:
const img = new Image(); img.crossOrigin = "anonymous"; img.src = "https://i.imgur.com/Dx200x9.png"; img.onload = () => { const texture = two.makeTexture(img); const sprite = two.makeSprite(texture, 0, 0); // 自定义着色器实现色调调整 sprite.shader = new Two.Shader( // 顶点着色器(保持默认逻辑) ` attribute vec2 position; attribute vec2 uv; varying vec2 vUv; void main() { vUv = uv; gl_Position = vec4(position, 0.0, 1.0); } `, // 片段着色器:叠加绿色色调并调整透明度 ` precision mediump float; uniform sampler2D texture; varying vec2 vUv; void main() { vec4 color = texture2D(texture, vUv); // 调整RGB通道实现绿色色调,同时降低透明度 color.r *= 0.5; color.b *= 0.5; color.g *= 1.5; color.a *= 0.5; gl_FragColor = color; } ` ); };
内容的提问来源于stack exchange,提问作者Hydroper
相关产品推荐
相关产品推荐

