Why is Javascript automatically mixing my colors?
I am just getting started with Javascript and HTML5, so it is likely that I am making some kind of nebulous mistake. In fact, I hope this is all true and that this is a simple solution.
Here is the output I get:
( Try it yourself !)
What I want is to simply draw a blue rectangle over the gray rectangle where both colors are their own thing. I'm honestly confused as to why this mixing is standard (using Chrome on my machine).
Here's a 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 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);
source to share
It's not blending, it's just that the stroke is 1 pixel wide, and the coordinates in the canvas are the squares, and the lines are between the squares. Your lines go between pixels and are anti-aliased. If you want your strokes to match pixels, you need to use coordinates such as (99,5,99,5), not (100,100). Difficult to describe, but a lot of documentation is available.
To make a long story short, you need to translate the entire drawing code to 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();
source to share
Check out the parameter globalCompositeOperation
. It looks like you've set it to "lighter"
where you want the default "source-over"
.
source to share