新手在画布中不断丢失alpha值 [英] newbie keeps losing alpha values in canvas

查看:135
本文介绍了新手在画布中不断丢失alpha值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能在这里做了一些蠢事,但是我很难在Alpha中使用alpha值进行合作。我试图从画布上的一个点上采样不透明的颜色,让它更透明,然后将它放在另一个地方 - 但是alpha部分似乎不起作用。剥离它有点像这样(从散布在脚本中的函数缩小):

I'm probably doing something boneheaded here but I'm having difficulties getting alpha values to cooperate in Canvas. I'm trying to sample an opaque color from a spot on the canvas, make it more transparent, and lay it down in another spot -- but the alpha part doesn't seem to be working. Stripped down it goes sort of like this (condensed from functions strewn across the script):

p = ground.ctx.getImageData(loc.x, loc.y, 1, 1).data; 
col = {R: p[0], G: p[1], B: p[2], a: p[3]};
col.a = col.a - 0.1;
ground.ctx.fillStyle = 'rgba(' + col.R + ', ' + col.G + ', ' + col.B + ', ' + col.a + ')';
ground.ctx.fillRect(nuLoc.x, nuLoc.y, sqrSize, sqrSize);

这一切都在运行,但是当我测试fillStyle的值时,我只得到一个标准的RGB#fa674c 或者其他什么 - 没有提到任何alpha - 当我从新绘制的Rect得到ImageData()时,该值再次完全不透明。

It all runs, but when I test the value of fillStyle I get just a standard RGB "#fa674c" or whatever -- no mention of any alpha -- and when I getImageData() from the newly drawn Rect the value is fully opaque again.

我还有另外一件事'能够通过经验或通过阅读每个教程(和规范)来确定alpha是否想要0-1.0或0-255。大多数消息来源谈论0-1.0 - 但是getImageData()返回0-255 ......我不能让它工作。

Another thing I haven't been able to figure out either empirically or by reading every tutorial (and the spec) is whether alpha wants to be 0-1.0 or 0-255. Most sources talk about 0-1.0 -- but getImageData() returns 0-255... and I can't make it work either way.

推荐答案

使用context.globalAlpha而不是使用rgba fill:

p = ground.ctx.getImageData(loc.x, loc.y, 1, 1).data; 
col = {R: p[0], G: p[1], B: p[2], a: p[3]};

// note: globalAlpha uses a scale of 0-1
// and getImageData uses a scale of 0-255
ground.ctx.globalAlpha = a/255-.1;

ground.ctx.fillStyle = 'rgb(' + col.R + ', ' + col.G + ', ' + col.B + ')';
ground.ctx.fillRect(nuLoc.x, nuLoc.y, sqrSize, sqrSize);

// reset globalAlpha when you're done
ground.ctx.globalAlpha = 1;

这篇关于新手在画布中不断丢失alpha值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆