开发者

Problem in Javascript colors and canvas

I have used this code to exactly try to have the RGB code of color:

var huePixel = HueCanvas.css('background-color').match(/开发者_StackOverflow^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);//["rgb(0, 70, 255", "0", "70", "255"]
var svPixel = SVCanvas.get(0).getContext("2d").getImageData(satPos,valPos,1,1).data;
//opacity*original + (1-opacity)*background = resulting pixel
var opacity =(svPixel[3]/255);
var r =parseInt((opacity*svPixel[0])+((1-opacity)*huePixel[1]));
var g =parseInt((opacity*svPixel[1])+((1-opacity)*huePixel[2]));
var b =parseInt((opacity*svPixel[2])+((1-opacity)*huePixel[3]));

The problem is that in some pixels , the RGB is not exactly the same . If i use Math.round than parseInt there is more problems , and more pixels have little changes than real ones.

I know that the problem is in var opacity =(svPixel[3]/255); , but i dont know how to put the equation to not have that problems.

Thanks for your attention.


I don't know the definite answer to your question (I'm not even sure I understand the question itself), but I'll take a shot.

It appears that you're trying to calculate the RGB value that you see when something else (the browser?) blends a non-opaque canvas on top of opaque background. (Are you sure this is the right thing to do at all?)

First, please don't use parseInt to round a number. It's used to parse strings and you should use it to convert huePixel[i] to an integer: parseInt(huePixel[i], 10) (note that I specify the radix explicitly to avoid numbers being parsed as octal).

To round values, you should use Math methods: Math.round (to closest integer), Math.ceil (round up) or Math.floor (round down).

Maybe the problem you're having is caused by rounding errors (hard to say without the specific inputs and expected outputs of the calculation). To minimize the rounding errors, you could try rewriting the formula like this:

(opacity * svPixel[0]) + ((1-opacity) * huePixel[1]) =
  huePixel[1] + opacity * (svPixel[0]-huePixel[1]) =
  huePixel[1] + svPixel[3] * (svPixel[0]-huePixel[1]) / 255
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜