1

My canvas is used for drawing and animating some lines in different colors, which could look like this: http://jsfiddle.net/swknhg3t/

HTML:

<canvas id="myCanvas" width="400px" height="400px"></canvas>

JavaScript:

var elem = document.getElementById('myCanvas');
var c = elem.getContext('2d');

var count = 0;

function draw() {
    c.save();
    c.clearRect(0, 0, 400, 400);

    // red
    c.beginPath();
    c.moveTo(20, 50);
    c.lineCap = "round";
    c.lineWidth = 20;
    c.lineTo(380, 50);
    c.strokeStyle = "#f00";
    c.stroke();

    // green
    c.beginPath();
    c.moveTo(20, 350);
    c.lineCap = "round";
    c.lineWidth = 20;
    c.lineTo(380, 350);
    c.strokeStyle = "#0f0";
    c.stroke();

    // blue
    c.translate(200, 200);
    c.rotate(count * (Math.PI / 180));
    c.beginPath();
    c.moveTo(0, 0);
    c.lineCap = "round";
    c.lineWidth = 20;
    c.lineTo(180, 0);
    c.strokeStyle = "#00f";
    c.stroke();

    c.restore();

    count++;
}

setInterval(draw, 20);

When those lines intersect, I want their colors being multiplied (like the Photoshop filter).

I found a nice explanation on how to do this pixelwise, but since my canvas will hold an animation I wonder if there is a better option than iterating over every pixel and calculating the color value manually in every loop.

alpo
  • 40
  • 6

1 Answers1

1

You shouldn't need to do it on an entire canvas per-pixel basis.

If you're only using modern browsers, you could do...

c.globalCompositeOperation = "multiply";

jsFiddle.

Otherwise, you could...

  1. Figure out the line intersections
  2. Use those offset to grab getImageData() (depending on grabbing smaller portions and modifying is more performant than grabbing it all and then using the offsets)
  3. Modify the surrounding portion related to the thickness of your lines. If the colour is transparent, simply bail early when iterating.
  4. Use putImageData() to render it back.
Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
  • 1
    That is what I was looking for, thank you.I came across the globalCompositeOperation property already, I don't find any source that lists "multiply" as a valid value though. Do you know a source that provides a complete listing? – alpo Dec 10 '14 at 00:58
  • 2
    @alpo Check this: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D.globalCompositeOperation – alex Dec 10 '14 at 00:59
  • 1
    Just note that (surprise) IE incl. version 11 do not support the new blending modes yet (status: recommendation). For this pixel iteration would be necessary. –  Dec 10 '14 at 01:37