为什么Javascript会自动混合我的颜色? [英] Why is Javascript automatically blending my colors?

查看:131
本文介绍了为什么Javascript会自动混合我的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用Javascript和HTML5,所以我很可能犯了一些非常愚蠢的错误。事实上,我希望这就是一切,这是一个简单的解决方案。

I'm just starting out with Javascript and HTML5 so it's entirely likely that I'm making some really dumb mistake. In fact I hope that's all it is and that this is an easy fix.

这是我得到的输出:

自己尝试一下!)

我想要发生的只是在灰色矩形上绘制一个蓝色矩形,其中两种颜色是他们自己的事情。我真的很困惑为什么这种混合是默认的(在我的机器上使用Chrome)。

What I want to happen is just to draw a blue rectangle over the gray rectangle, where both colors are their own thing. I'm honestly confused as to why this blending is the default (using Chrome on my machine).

这是最小的工作示例(同样,对于我的机器):

Here is the minimal working example (again, for my machine):

(html)

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Simple Canvas Game</title>
    </head>
    <body>
        <script src="js/game.js"></script>
    </body>
</html>

(javascript,这是game.js)

(javascript, this is the game.js)

//set up the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);

// Draw everything
var render = function () {
    ctx.clearRect(50, 50, 100, 100);

    ctx.fillStyle = "rgb(240, 240, 240)";
    ctx.fillRect(0, 0, 100, 100);

    ctx.strokeStyle="rgb(0, 0, 255)";
    ctx.strokeRect(20,20,150,100);
}

setInterval(render, 10);


推荐答案

这不是混合,只是笔画是1像素宽,画布中的坐标是正方形,而线条在正方形之间。你的线在像素之间,并且是消除锯齿的。如果希望笔划与像素对齐,则需要使用(99.5,99.5),而不是(100,100)的坐标。很难描述,但有大量的文档可用。

This is not blending, it's just that the stroke is 1 pixel wide, and the coordinates in canvas are those of squares, while lines go between squares. Your lines go between pixels and are anti-aliased. If you want your strokes to align with pixels, you need to use coordinates like (99.5,99.5), not (100,100). Hard to describe, but there is plenty of documentation available.

长话短说,你必须将整个绘图代码翻译0.5,0.5。尝试类似:

To make long story short, you have to translate the whole drawing code by 0.5,0.5. Try something like:

ctx.save();
ctx.translate(0.5,0.5);

ctx.clearRect(50, 50, 100, 100);

ctx.fillStyle = "rgb(240, 240, 240)";
ctx.fillRect(0, 0, 100, 100);

ctx.strokeStyle="rgb(0, 0, 255)";
ctx.strokeRect(20,20,150,100);
ctx.restore(); 

这篇关于为什么Javascript会自动混合我的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆