如何为画布渲染使用栏选取渐变颜色?
问题描述:
我试图使用HTML5画布的功能为我的Google Chrome扩展程序中的使用栏添加颜色。酒吧本身是一个简单的DIV:如何为画布渲染使用栏选取渐变颜色?
<div id="idUsgBar"></div>
这个CSS:
#idUsgBar{
margin: 0;
padding: 0;
background: -webkit-canvas(bkgfill);
}
所以工作是在JS做:
//'perc' = percent value from [0 to 100]
//'w' = width of the bar for 100%
//'h' = height of the bar
var w_f = w * perc/100;
var ctx = document.getCSSCanvasContext("2d", "bkgfill", w, h);
ctx.clearRect(0, 0, w, h);
//The issue is calculating r, g, b components for the fill based on 'perc'???
ctx.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
ctx.fillRect(0, 0, w_f, h);
所以我创建了一个梯度在Photoshop中看起来像这样,但我认为我可以简单地设置与perc
的值成比例的R
组件完全关闭。这个图表可说明我的意思:
那么什么是做到这一点的呢?
答
我能够这样做,以解决这一以下内容:
在Photoshop中与所需的渐变/彩色图案创建一个像素高PNG。 (叫我上面的示例中的“颜色源”。)
它添加到页面作为一种无形的
<img>
设置为display: none;
它的CSS样式。然后得到一个彩色的“使用条”的百分比值,使用
canvas
从<img>
简单地品尝它。首先用drawImage()加载它,然后用getImageData()获取像素的RGB分量。
PS。为了加快速度,我在页面加载时缓存全局数组中<img>
所需的所有像素,以便稍后在绘制“使用条”时可以稍后使用它来检索RGB值。
1)这里没有定义渐变(使用createLinearRadiant),但是只使用了实心填充,所以难怪为什么颜色是均匀的。 2)你可能想要使用hsl颜色,更容易处理。 – GameAlchemist 2014-09-19 10:23:12