Skip to content

How to colour/shade on canvas? #590

Answered by char101
asfand987 asked this question in Q&A
Discussion options

You must be logged in to vote

It is called clipping. You draw your first line as a closed path (including the area below it), the second path as another closed path (including the area above it), then fill the first path using the second path as clip.

// create path object for filling and clipping
export function createAreaPath(xs, ys, y) {
  const p = new Path2D();
  if (xs.length > 1) {
    p.moveTo(xs[0], y);
    for (let i = 0, n = xs.length; i < n; ++i) {
      p.lineTo(xs[i], ys[i]);
    }
    p.lineTo(xs[xs.length - 1], y);
  }
  return p;
}

// fill area where y1 > y2 with color
export function fillPathBetween(ctx, xs, y1, y2, color) {
  if (xs.length === 0) return;
  const canvas = ctx.canvas;
  ctx.save();
  c…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@asfand987
Comment options

Answer selected by asfand987
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants