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

标签 javascript html html5-canvas

我在 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/

相关文章:

javascript - 外部JS : No output from console

javascript - 在同一页面中打开链接,链接打开后,执行一些代码

javascript - Google Maps Api 未将 map 显示到 div 中

javascript - Fabric js 自定义旋转图标在初始加载时不显示

javascript - ctx.fillText 不绘制连接

javascript将对象复制到引用的内存中

javascript - Jasmine spyOn 范围函数中断测试

javascript - Fabric.js 动态裁剪区域以不同方式影响图像和 SVG/形状

javascript - 功能不起作用,我不明白为什么

javascript - 使用javascript选中复选框后如何验证 "textarea"