首页 > 解决方案 > 如何设置画布图像透明度

问题描述

我创建了一个小程序,用于使用 node.js 和画布生成 Minecraft 锭纹理。我想让背景(不是锭的一部分)透明。

我有我所有的矩形:

let canvas = document.createElement("canvas");
canvas.width = canvas.height = 800
let ctx = canvas.getContext('2d');

ctx.fillRect(0, 200, 50, 50);
ctx.fillRect(0, 250, 50, 50);
ctx.fillRect(0, 300, 50, 50);
ctx.fillRect(0, 350, 50, 50);
ctx.fillRect(0, 400, 50, 50);
ctx.fillRect(50, 150, 50, 50);
ctx.fillRect(100, 150, 50, 50);
ctx.fillRect(150, 150, 50, 50);
ctx.fillRect(200, 100, 50, 50);
ctx.fillRect(250, 100, 50, 50);
ctx.fillRect(300, 100, 50, 50);
ctx.fillRect(350, 50, 50, 50);
ctx.fillRect(400, 50, 50, 50);
ctx.fillRect(450, 50, 50, 50);
ctx.fillRect(500, 0, 50, 50);
ctx.fillRect(550, 0, 50, 50);
ctx.fillRect(600, 50, 50, 50);
ctx.fillRect(650, 100, 50, 50);
ctx.fillRect(700, 150, 50, 50);
ctx.fillRect(150, 550, 50, 50);
ctx.fillRect(100, 500, 50, 50);
ctx.fillRect(50, 450, 50, 50);

document.body.appendChild(canvas);

如何设置图像背景透明度?

标签: javascriptcanvashtml5-canvas

解决方案


扩展对评论的讨论:

如果问题出在图像上,您的代码没有drawImage我希望看到的内容。
画布默认是透明的,你可以在下面看到我的示例 我在 html 元素中添加了一些带有背景图像的 CSS,我们可以看到图像在画布后面并且可见。

let canvas = document.createElement("canvas");
canvas.width = canvas.height = 800
let ctx = canvas.getContext('2d');

ctx.fillRect(0, 200, 50, 50);
ctx.fillRect(0, 250, 50, 50);
ctx.fillRect(0, 300, 50, 50);
ctx.fillRect(0, 350, 50, 50);
ctx.fillRect(0, 400, 50, 50);
ctx.fillRect(50, 150, 50, 50);
ctx.fillRect(100, 150, 50, 50);
ctx.fillRect(150, 150, 50, 50);
ctx.fillRect(200, 100, 50, 50);
ctx.fillRect(250, 100, 50, 50);
ctx.fillRect(300, 100, 50, 50);
ctx.fillRect(350, 50, 50, 50);
ctx.fillRect(400, 50, 50, 50);
ctx.fillRect(450, 50, 50, 50);
ctx.fillRect(500, 0, 50, 50);
ctx.fillRect(550, 0, 50, 50);
ctx.fillRect(600, 50, 50, 50);
ctx.fillRect(650, 100, 50, 50);
ctx.fillRect(700, 150, 50, 50);
ctx.fillRect(150, 550, 50, 50);
ctx.fillRect(100, 500, 50, 50);
ctx.fillRect(50, 450, 50, 50);

document.body.appendChild(canvas);
html {
  background-image: url('http://i.stack.imgur.com/UFBxY.png');
}


推荐阅读