Itay Ganor Itay Ganor -5 years ago 409
jQuery Question

HTML Canvas - 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 = "";
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);


Answer Source

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

<canvas id="canvs" width="500" height="500">
<img src="" id="img">

function onld(){
var can = document.getElementById('canvs');
var img = document.getElementById('img');
var ctx = can.getContext('2d');
ctx.fillStyle = 'rgba(217, 87, 83, 0.8)';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download