Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Javascript automatically blending my colors?

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.

Here is the output I'm getting:

Weird, wrong image (Try it yourself!)

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, 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);
like image 357
Richard Rast Avatar asked Jan 15 '23 06:01

Richard Rast


1 Answers

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.

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(); 
like image 144
fdreger Avatar answered Jan 16 '23 20:01

fdreger