开发者

Programmatically use RGBa values in fillStyle in <canvas>?

Using <canvas>, I want to set the RGBa value of the rectangle using a variable.

for开发者_运维问答 example:

ctx.fillStyle = "rgba(32, 45, 21, 0.3)";

works fine, but using it with a variable:

var r_a =  0.3;
ctx.fillStyle = "rgba(32, 45, 21, r_a)";

doesn't work.

Apparently fillStyle only accepts a string. So how do I set a value of the rgba value using some variable instead of explicitly defining the values?


You just need to concatenate the r_a variable to build the string correctly:

var r_a = 0.3; 
ctx.fillStyle = "rgba(32, 45, 21, " + r_a + ")"; 


ctx.fillStyle = "rgba(32, 45, 21, "+r_a+")"; 

It is string concatenation.


I'm very late to the party but I had a similar problem and solved it in a slightly different way that may be useful.

Since I needed to reuse the fill colours at different alpha levels, I used the JavaScript replace method:

colurfill = "rgba(255, 255, 0, [[opacity]])";
ctx.fillStyle = colurfill.replace("[[opacity]]", "0.5");
:
:
ctx.fillStyle = colurfill.replace("[[opacity]]", "0.75");

Obviously it doesn't have to be the alpha level that varies, it could be one of the other channels.


var r_a = 0.3
ctx.fillStyle = `rgba(32, 45, 21, ${r_a})`;

These are called template literals https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

The back-ticks `` are often found left of the number 1 on the keyboard on US keyboards.


I was looking for something similar and ran into your post, after reading it, I came up with a solution for myself, I'm working with the audio API and wanted a dynamic color based on a variable coming from the frequency in the sound file. Here's what I came up with and it woks for now, thought I'd post it in case it helps since I got the inspiration from your question:

function frameLooper(){ 
    window.requestAnimationFrame(frameLooper); 
    fbc_array = new Uint8Array(analyser.frequencyBinCount); 
    analyser.getByteFrequencyData(fbc_array); 
    ctx.clearRect(0, 0, canvas.width, canvas.height); 
// Clear the canvas 

    bars = 100; 
        for (var i = 0; i < bars; i++) { 
            bar_x = i * 3; 
            bar_width = 2; 
            bar_height = -(fbc_array[i] / 2); 
            bar_color = i * 3;

    //fillRect( x, y, width, height ) 
    // Explanation of the parameters below 
        ctx.fillRect(bar_x, canvas.height, bar_width, bar_height); 
            ctx.fillStyle = "rgb(100," + bar_color + "," + bar_color + ")" ; 
// Color of the bars


let colo = "blue";
ctx.Style=`${colo}`;


let colo = 
arr[Math.floor(Math.random()*3)];
console.log(colo);
ctx.fillStyle=`${colo}`;


//Example code 
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

//This function changes a number to it's HEX equivelent (for n<=255)
function hex(n){
    let letters = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];

    if(n>255){ n = 255;}  // Bounding parameters 0 <= n <= 255
    if(n < 0){ n = 0; }

    let a = n;    
    let b = n%16;
    a = Math.floor(a/16);
    b = Math.floor(b/16);
    a = letters[a];
    b = letters[b];
    return a+b;
}

//This function concatenates three hex values into one string preceeded by #
function hexColor(r,g,b){
    let red = hex(r);
    let blue = hex(b);
    let green = hex(g);
    return "#"+red+green+blue;
}

//This function simplifies the fillStyle/fill functions for canvas
function fill(r,g,b){
    let c = hexColor(r,g,b);
    ctx.fillStyle = c;
    ctx.fill();
}

//Just an example to show how it works
function drawBall(){
    ctx.beginPath();
    ctx.rect(20, 20, 150, 100);

    //EXAMPLE OF USING (R,G,B) LIKE IN p5.js
    fill(0,133,444); 
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜