3

I need to draw an image with transparent background on canvas. I have a code that should do that:

var can = document.getElementById('canvasId');
var ctx = can.getContext('2d');

ctx.fillRect(50,50,500,500); // something in the background

var img = new Image();
img.onload = function() {
    ctx.drawImage(img, 0, 0);
}
img.src = "https://i.stack.imgur.com/7JXBD.png"; //transparent png
<canvas id="canvasId"></canvas>

But the background is not transparent:

screenshot

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44

2 Answers2

2

The image that you are trying to display isn't transparent, it simply just has a transparent checkered background.

A link to an image which does have a transparent background can be found here

Using this link fixes your issue:

var can = document.getElementById('canvasId');
var ctx = can.getContext('2d');


ctx.fillRect(50, 50, 500, 500); // something in the background

var img = new Image();
img.src = "https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded"; //transparent png
img.onload = function() {
  ctx.drawImage(img, 0, 0);
}
canvas {
  border: 1px solid black;
}
<canvas id="canvasId" height="300" width="500"></canvas>
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
2

Your code works perfectly - you just need an image with a transparent background - like this question mark:

var can = document.getElementById('canvasId');
var ctx = can.getContext('2d');


ctx.fillRect(50,50,500,500); // something in the background

var img = new Image();
img.onload = function() {
    ctx.drawImage(img, 0, 0);
}
img.src = "https://i.stack.imgur.com/RPEQQ.png"; //transparent png
<canvas id="canvasId"></canvas>

And to prove it's not just got a white background image, I set the background image of the body to red:

var can = document.getElementById('canvasId');
var ctx = can.getContext('2d');


ctx.fillRect(50,50,500,500); // something in the background

var img = new Image();
img.onload = function() {
    ctx.drawImage(img, 0, 0);
}
img.src = "https://i.stack.imgur.com/RPEQQ.png"; //transparent png
body {
    background-color: red;
}
<canvas id="canvasId"></canvas>
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79