我有一个相机视频源和一个画布。
当用户单击“提交”时,画布会获取提要的图像
<video id="video" width="300" height="200" autoplay></video>
</section>
<section class="btn">
<button id="btnClick">Submit</button><br>
</section>
<section>
<canvas id="canvas" width="300" height="300">
</section>
用户点击提交后,可以点击分享上传图片。
<input type="button" onclick="uploadEx()" value="Share" />
<form method="post" accept-charset="utf-8" name="form1">
<input name="hidden_data" id='hidden_data' type="hidden"/>
</form>
我希望能够在用户通过单击共享按钮提交第一个快照之前在图像顶部覆盖另一个 png。
上传图片的JS:
function uploadEx() {
var canvas = document.getElementById("canvas");
var dataURL = canvas.toDataURL("image/png");
document.getElementById('hidden_data').value = dataURL;
var fd = new FormData(document.forms["form1"]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'uploadscript.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + '% uploaded');
alert('Image uploaded');
}
};
xhr.onload = function() {
};
xhr.send(fd);
};
上传时如何在顶部叠加第二张图片(如水印)?
这是使用临时画布的一种方法:
创建临时内存画布:
document.createElement('canvas')
将主画布绘制到临时画布上:
tempContext.drawImage(mainCanvas,0,0)
添加一些重叠的文本(或其他内容)作为水印:
tempContext.fillText('Mine!',0,0)
获取临时画布的dataURL:
tempCanvas.toDataURL()
示例代码和演示:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
var img = new Image();
img.crossOrigin = 'anonymous';
img.onload = start;
img.src = "https://i.sstatic.net/ithV0ACj.png";
function start() {
const canvasWidth = Math.min(img.width, 450);
const canvasHeight = Math.min(img.height, 450);
canvas.width = canvasWidth
canvas.height = canvasHeight;
ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight);
var dataURL = watermarkedDataURL(canvas, "It's Mine!");
}
function watermarkedDataURL(canvas, text) {
var tempCanvas = document.createElement('canvas');
var tempCtx = tempCanvas.getContext('2d');
var cw, ch;
cw = tempCanvas.width = canvas.width;
ch = tempCanvas.height = canvas.height;
tempCtx.drawImage(canvas, 0, 0);
tempCtx.font = "24px verdana";
var textWidth = tempCtx.measureText(text).width;
tempCtx.globalAlpha = .50;
tempCtx.fillStyle = 'white'
tempCtx.fillText(text, cw - textWidth - 10, ch - 20);
tempCtx.fillStyle = 'black'
tempCtx.fillText(text, cw - textWidth - 10 + 2, ch - 20 + 2);
// just testing by adding tempCanvas to document
document.body.appendChild(tempCanvas);
return (tempCanvas.toDataURL());
}
body {
background-color: ivory;
padding: 20px;
}
canvas {
border: 1px solid red;
}
<canvas id="canvas" width=300 height=300></canvas>
<h2>Watermarked...</h2>