Rafael de Castro
Rafael de Castro

Reputation: 1078

How to "paint" on an image on Canvas?

I want to use an image like this on canvas:

enter image description here

The user will "paint and fill" the image, but not on top of the outline.

The problem is:
If I put behind the canvas, the paint will cover the outline.
If I put over the canvas the image block canvas interaction.

Can you help me guys?

Upvotes: 1

Views: 3695

Answers (2)

user1693593
user1693593

Reputation:

Use compositing mode "destination-over" to draw behind existing content (from image, vectors etc.). It's necessary that the existing content provide an alpha channel or composition won't work. If there is no alpha-channel you can convert inverse luma / matte (the white) to alpha channel.

// a quick-n-dirty demo
var ctx = c.getContext("2d");
ctx.lineWidth = 10;
ctx.moveTo(100, 0); ctx.lineTo(150, 150); ctx.stroke();
ctx.fillStyle = "#09f";

// KEY: composite mode -
ctx.globalCompositeOperation = "destination-over";

// draw behind the line
c.onmousemove = function(e) {
  ctx.fillRect(e.clientX - 10, e.clientY - 10, 20, 20);
};
body {margin:0}
canvas {border:#777 solid 1px}
<canvas id="c"></canvas>

Upvotes: 3

Anton Jebrak
Anton Jebrak

Reputation: 602

Here is the example of drawImage function. You can draw any preloaded image onto canvas. You can also try to place the <img> overlay in front of the canvas and disable mouse events for it using pointer-events: none CSS property.

Upvotes: 0

Related Questions