我有相机视频输入和画布.
<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用于上传pic:
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)
>添加一些重叠的文本(或其他东西)作为水印:tempContext.fillText(‘Mine!’,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://dl.dropBoxusercontent.com/u/139992952/earth.jpg"; function start(){ canvas.width=img.width; canvas.height=img.height; ctx.drawImage(img,0); 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); 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>