javascript - 如何设置画布图像透明度
问题描述
我创建了一个小程序,用于使用 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);
如何设置图像背景透明度?
解决方案
扩展对评论的讨论:
如果问题出在图像上,您的代码没有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');
}
推荐阅读
- python-3.x - 从python中的第二个元素转置列表列表
- unix - 如何使用列值作为使用 unix ksh 脚本从表创建的文件名的一部分
- c++ - 地图中的 .end()->first 是什么意思
- recursion - temp 如何访问丢失的数据
- vba - 在 Excel VBA 中接收 Next 而没有 For 错误
- bash - 在 bash 脚本中,循环必须继续,直到输入特定的关键字
- red-black-tree - 插入红黑树
- yaml - YAML 中的索引数组是什么?
- python - 我无法使用 python 从电子表格上的电子邮件列表中发送电子邮件
- python - RPLidarException:描述符起始字节不正确