javascript - 如何拥有多个 globalCompositeOperation
问题描述
我的画布是 512x256 像素
这是我想要实现的目标:
- 在画布上打印本地图像(图像 1)。
- 用特定颜色填充此图像。
- 打印另一个不应与图像 1 重叠的本地图像(图像 2)。
所以我所做的是:
- .drawImage(image1)
- 创建一个 512x256 的矩形( ctx.rect(0, 0, 512, 256); )
- ctx.globalCompositeOperation = "目的地输入";
- 绘制这个矩形( ctx.fill() )(使用destination-in 它应该具有用矩形颜色填充第一张图像的效果)
- ctx.globalCompositeOperation = "目的地输出";
- .drawImage(image2) (使用destination-out它应该使这个图像在图像1下)
但它不显示任何东西。我认为这是因为我们不能有不同的 globalCompositeOperation... 但我确信这是有可能的,我发现人们在谈论它并解决了这个问题,但他们正在为他们的特定任务使用特定的代码,而我只是不这样做'不明白。我喜欢我的脚本的一个例子:
<script>
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var img1 = new Image();
img1.onload = function () {
ctx.drawImage(img1, 0, 0);
};
ctx.globalCompositeOperation = "destination-in";
ctx.rect(0, 0, 512, 256);
ctx.fillStyle = "green";
ctx.fill()
ctx.globalCompositeOperation = "destination-out";
img2.onload = function () {
ctx.drawImage(img2, 0, 0);
};
img1.src = "C:/Users/... file1.png" // replaced the path for this example
img2.src = "C:/Users/... file2.png";
</script>
这是我的 html 正文:
<body>
<canvas id="canvas" width="512" height="256"></canvas>
</body>
解决方案
推荐阅读
- javascript - 如何在 FullCalendar 中禁用星期一的点击?
- neural-network - 计算卷积神经网络中 MAC 数量的公式?
- mysql - MySQL Row more 出现多行相同的结果
- c++ - 多行原始字符串混淆 Visual Studio
- events - 当其他文本字段更改时触发特定文本字段的计算
- amazon-ec2 - 如何在 AWS EC2 中安装 Confluent
- android - 尝试在android上进行wifi连接时检查密码是否不正确
- database - 用于搜索属性的数据库表的优化设计
- python - 如何将一个字节串连接在一起?让b'\x1D\x12'变成b'\x121D'?
- python - Tensorflow:有没有办法将元数据保存在 TFRecords 文件中