I'm trying to merge webcam video and canvas drawing and save to an image file. It works but video image covers canvas draving. I tried to swap places context.drawImage but still same. Any ideas? :)
canvas.addEventListener("click", async function () {
var context = canvas.getContext("2d");
context.drawImage(video, 0, 0, canvas.width / 1.5, canvas.height / 1.5);
context.drawImage(canvas, 0, 0, canvas.width, canvas.height);
var dataURL = canvas.toDataURL("image/png");
$.ajax({
type: "POST",
url: "./upload.php",
data: {
dataURL: dataURL
}
});
});
Currently what you code does is to draw the canvas over itself, with the video already painted on it.
You can draw behind the existing content by using the globalCompositeOperation = "destination-over"
.
const canvas = document.querySelector("canvas"); const ctx = canvas.getContext("2d"); ctx.font = "16px sans-serif"; ctx.textAlign = "center"; const img = new Image(); // a video is the same img.src = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png"; img.decode().then(() => { canvas.onclick = (evt) => { ctx.globalCompositeOperation = "destination-over"; ctx.drawImage(img, 0, 0, canvas.width, canvas.height); // reset to default ctx.globalCompositeOperation = "source-over"; }; ctx.fillText("click on the canvas", canvas.width / 2, canvas.height / 3); ctx.fillText("to draw the image", canvas.width / 2, canvas.height / 3 + 20); ctx.fillText("behind this text", canvas.width / 2, canvas.height / 3 + 40); });
canvas { outline: 1px solid }
<canvas></canvas>
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.