gpt4 book ai didi

javascript - 避免在 HTML5 Canvas 中混合颜色

转载 作者:行者123 更新时间:2023-11-30 13:09:56 26 4
gpt4 key购买 nike

我在 html5 canvas 元素中绘制两个矩形。矩形 a 的一条边在矩形 b 的边上。

矩形 a 是绿色,矩形 b 是蓝色。

结果是公共(public)边既不是蓝色也不是绿色:它的颜色是两者的某种混合。

我尝试将 globalCompositeOperation 设置为 source over,但没有帮助。

enter image description here

最佳答案

那是因为在不止一个屏幕像素上绘制了线条。

绘图模型基于浮点坐标,舍入值屏幕像素之间。

为避免混合,请始终在坐标 Math.round(x)+0.5 处绘制线宽为一个像素的线条。

这是 a related answer附上图片。

这是我编写的一些代码来帮助绘制细线和矩形:

function drawThinHorizontalLine(c, x1, x2, y) {
c.lineWidth = 1;
var adaptedY = Math.floor(y)+0.5;
c.beginPath();
c.moveTo(x1, adaptedY);
c.lineTo(x2, adaptedY);
c.stroke();
}

function drawThinVerticalLine(c, x, y1, y2) {
c.lineWidth = 1;
var adaptedX = Math.floor(x)+0.5;
c.beginPath();
c.moveTo(adaptedX, y1);
c.lineTo(adaptedX, y2);
c.stroke();
}

function Rect(x,y,w,h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}

Rect.prototype.drawThin = function(context) {
drawThinHorizontalLine(context, this.x, this.x+this.w, this.y);
drawThinHorizontalLine(context, this.x, this.x+this.w, this.y+this.h);
drawThinVerticalLine(context, this.x, this.y, this.y+this.h);
drawThinVerticalLine(context, this.x+this.w, this.y, this.y+this.h);
}

示例:

context.strokeColor = 'red';
var r = new Rect(20, 23, 433, 14);
r.drawThin(context);

关于javascript - 避免在 HTML5 Canvas 中混合颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14262625/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com