在画布上绘制具有透明背景的图像

时间:2018-11-13 08:34:53

标签: javascript html image html5-canvas transparent

我需要在画布上绘制具有透明背景的图像。我有一个应该执行此操作的代码:

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>

但是背景不是透明的:

screenshot

2 个答案:

答案 0 :(得分:1)

您要显示的图像不是透明的,只是具有透明的方格背景。

可以找到指向具有透明背景的图像的链接here

使用此链接可解决您的问题:

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>

答案 1 :(得分:0)

您的代码可以完美运行-您只需要具有透明背景的图像-像这样的问号:

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>

为了证明它不仅具有白色背景图像,我将身体的背景图像设置为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>