简体   繁体   中英

How to “paint” on an image on Canvas?

I want to use an image like this on canvas:

在此处输入图片说明

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?

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> 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM