Itay Ganor Itay Ganor - 5 months ago 10
Javascript Question

Fill with background color, and then overlay a PNG

I'm trying to make a canvas have a background color, and then overlay a PNG above it.

This is the png texture:

enter image description here
 ‏

for example, If

backgroundColor = #D95753
(bright-red), the canvas filling levels will be:

1.- Setting the background color

enter image description here

2.- Overlaying the png above the background color

enter image description here

That's the code I have, but it is not working. you can't see the background color, only the png image.

var background = new Image();
background.src = "http://i.stack.imgur.com/LF1P0.png";
background.height = y; // set it before
background.width = x; // set it before

ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, background.width, background.height);

background.onload = function() {
ctx.drawImage(background,0,0, background.width, background.height);
memeEverything();
}


Thanks!

Answer

Try that by define fillRect() and color in rgba format as below,

<canvas id="canvs" width="500" height="500">
<img src="http://i.stack.imgur.com/LF1P0.png" id="img">
</canvas>

function onld(){
var can = document.getElementById('canvs');
var img = document.getElementById('img');
var ctx = can.getContext('2d');
ctx.fillStyle = 'rgba(217, 87, 83, 1)';
ctx.fillRect(10,10,500,500);
ctx.globalAlpha=0.6;
ctx.drawImage(img,10,10);
}
window.addEventListener('load',onld);