1

I've been developing a spike graph using JavaScript and HTML5's canvas element.

To accomplish what I'm going after though, I need to layer upwards of 3 canvas elements on top of each other (using position: absolute).
However, despite there being no opacity property on the canvas' - nor am I filling the rectangles with Alpha colors, the 1st layer canvas (light grey) always manages to affect the layer colors above it.

I have used straight red (#ff0000) on the red layer, but notice how it is affected by both the blue layer (blue is also affected), and the grey layer:

Reference

Relevant code:

function drawCanvas(ctx, samples, color){
    for(var i = 0; i < samples.length; i++){
        ctx.beginPath();
        ctx.fillStyle = color;
        ctx.rect(i + (i * 2), 60 - samples[i], 2, samples[i]);
        ctx.fill();
    }
}

var samples = [121,105,107,125,94,96,121];  
// grey layer
drawCanvas(canvasA.getContext("2d"), samples, "#313131");
// blue layer
drawCanvas(canvasB.getContext("2d"), samples, "blue");
// red layer
drawCanvas(canvasC.getContext("2d"), samples, "red");

JsFiddle: https://jsfiddle.net/yk2hjuk5/8/

Can't wrap my head around why this might be occurring, and I'm pretty new to using the canvas element - so all help is appreciated.

Cheers.

GROVER.
  • 4,071
  • 2
  • 19
  • 66
  • Try using [`fillRect`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillRect) instead of `rect`, or [translate](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/translate) by half-pixels. Your current `rect` code is drawing straight lines through the middle of pixels, rather than between pixels, which results in a blur. – Sebastian Simon Mar 27 '18 at 12:35
  • Possible duplicate of [Canvas drawings, like lines, are blurry](https://stackoverflow.com/questions/8696631/canvas-drawings-like-lines-are-blurry) – Sebastian Simon Mar 27 '18 at 12:37
  • @Xufox can you possibly make an answer, because none of those solutions are working :/ – GROVER. Mar 27 '18 at 12:44
  • Can you provide a live minimal demo? Are you somehow resizing your canvases by CSS to an other size that is being set in their attributes? – Kaiido Mar 27 '18 at 13:46
  • @Kaiido https://jsfiddle.net/yk2hjuk5/8/ :) – GROVER. Mar 27 '18 at 22:13
  • Is your browser zoom level set to something else than 100%? This would cause antialiasing to kick on all your layers, and indeed to spread on transparent areas. To fix it, you could [use a single canvas](https://jsfiddle.net/yk2hjuk5/10/). – Kaiido Mar 28 '18 at 01:51
  • @Kaiido would be perfect if the mouse controlled layer didn't disappear as it hovered away from the layer :) – GROVER. Mar 28 '18 at 04:08
  • @GROVER. I might have misplaced the clearRect call in mousemove... Also, if you want to keep the set colors, here is an other approach: https://jsfiddle.net/yk2hjuk5/12/ – Kaiido Mar 28 '18 at 04:27

0 Answers0