为什么在 HTML5 Canvas 上反复绘制半透明填充不能完全覆盖它?

如何解决为什么在 HTML5 Canvas 上反复绘制半透明填充不能完全覆盖它?

这到底是怎么回事?

为什么混合会在 255,214,255 处突然停止?这是预期的行为吗?

我以为它最终会命中 255,255,255,但它没有。它甚至没有接近。一开始的红色矩形永远不会消失成白色,它永远保持颜色255,255

const ctx = document.querySelector('canvas').getContext('2d');

// draw "red"
ctx.fillStyle = 'red';
ctx.fillRect(0,300,200);

function loop() {
    
    // log new colors
    if (getCurrentColor() !== loop.lastColor) {
        console.log(loop.lastColor = getCurrentColor());
    }
    
    // draw "transparent white" repeatedly
    ctx.fillStyle = 'rgba(255,0.01)';
    ctx.fillRect(0,200);
    
    // schedule next iteration
    requestAnimationFrame(loop);
}
loop(); // start loop

function getCurrentColor() {
    return ctx.getImageData(0,1,1).data.join(',');
}
<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <canvas width="300" height="200"></canvas>
    </body>
</html>

非常感谢解释和解决方案! :P

解决方法

HTML/JS 画布的底层图形缓冲区是位图,它只允许从 Integer0255 颜色值。

这意味着每个渲染操作的输出都必须四舍五入

假设您从颜色值 214 开始。如果你然后混合 214 * 0.99 + 255 * 0.01,理论上你会得到 214.41。但是这然后被四舍五入到 214 以存储在画布位图中!!

因此,基本上,只要您的步数小于 214 xD

不幸的是,没有办法使用普通的 JavaScript 来规避这一点,因为您无法更改图形缓冲区架构或混合/合成操作。

但是,如果你真的想,你当然可以破解它:P
看看WebGL API。它允许您实现自定义渲染操作和图形缓冲区。例如,您可以在内部使用 0.5 图形缓冲区。

,

最后不是完全白色的原因很简单:您在某物之上添加了一个非完全透明的覆盖层。不管你多久这样做一次,你永远不会达到 100%,因为它是一种渐近线行为。只需图像以下

我有一张 100% 的红纸。我会用 50% 透明的白色玻璃覆盖它。 然后你会看到 100% => 50% 的 50%。 如果我再这样做,你的逻辑会说我有 50% + 50% = 100% 但这不是它的工作原理。 你有 50% 的红色和 50% 的白色玻璃,并用另一个 50% 的白色玻璃覆盖它。这使得玻璃呈现 25% 的红色和 75% 的白色。

如果重复几次,红色的量会下降,但永远不会达到 0%。

解决方案是再次绘制红色矩形,但不透明度更高。如果您随后到达 ctx.fillStyle = 'rgba(255,255,1.00)';,它将完全覆盖红色。

示例代码如下:

const ctx = document.querySelector('canvas').getContext('2d');

// draw "red"
ctx.fillStyle = 'red';
ctx.fillRect(0,300,200);

// draw "transparent white" repeatedly
let lastColor;
let percentDone=0;
render();

function render() {
    if (getCurrentColor() !== lastColor)
        console.log(lastColor = getCurrentColor());

    percentDone += .005;
    if (percentDone == 1) {percentDone = 1;}
    ctx.fillStyle = 'red';
    ctx.fillRect(0,200);

    ctx.fillStyle = 'rgba(255,'+percentDone+')';
    ctx.fillRect(0,200);
    requestAnimationFrame(render);
}

function getCurrentColor() {
    return ctx.getImageData(0,1,1).data.join(',');
}
<canvas width="300" height="200"></canvas>

外部:https://jsfiddle.net/Holger50/51h0yLm6/3/

€dit 1:

将要添加透明度的颜色与该位置的颜色进行比较,计算时仅考虑颜色差异,并基于整数除法。如果计算出的值小于 1,则颜色不会改变,这就是示例中颜色强度 214 时发生的情况。

我尝试了几种方法来找出为什么这会停在一个奇怪的步骤上。也许以下有助于理解问题:如果您将初始填充颜色设置为 ctx.fillStyle = 'black'; 并发出以下 ctx.fillStyle = 'rgba(255,100,150,0.01)';,则停止输出为 207,43,129,255

似乎是基于现有值以某种方式计算了具有透明度的新颜色。如果差异太小,则不会添加颜色。 例如:如果您使用 ctx.fillStyle = 'rgba(10,0.01),红色部分永远不会增长,因为内部 10*0.01 小于 1,因此不会被考虑在内(它被四舍五入到下一个整数)。您还可以在颜色值中看到这一点。红色增加 100。控制台输出每一步增加 1。蓝色增加 150,控制台增加 2,直到它达到值 44。之后,它只会随着步骤 1 增长,直到它完全停止在 129。

我附上了第二个小提琴,你可以在那里看到效果。

const ctx = document.querySelector('canvas').getContext('2d');

// draw "red"
ctx.fillStyle = 'black';
ctx.fillRect(0,200);

// draw "transparent white" repeatedly
let lastColor;
render();
function render() {
    if (getCurrentColor() !== lastColor)
    console.log(lastColor = getCurrentColor());
    ctx.fillStyle = 'rgba(10,0.01)';
    ctx.fillRect(0,');
}
<canvas width="300" height="200"></canvas>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res