javascripthtmlasp.netwebcam.js

Calling two javascript functions with one button click gives a different result than with two


So, I am currently using webcam.js in order to first capture a still of an image. Then, I have written some java script code to pass this to a hidden variable so I can grab it on the ASP.NET code behind so I can save it to the database. This is what my javascript code looks like:

<script src="webcam.js"></script>
<script>
    function transfer() {
        var c = document.getElementById("myCanvas");
        var dataURL = myCanvas.toDataURL("image/png");
        dataURL = dataURL.replace('data:image/png;base64,', '');

        var hf = document.getElementById('<%=hiddensquare.ClientID%>');
            hf.value = dataURL;

        }
</script>
<script>
    function take_snapshot() {
        Webcam.snap(function () {
        }, myCanvas);
    }
</script>

I am calling these with two html buttons that use their onclick event in order to call them, like this:

<input id="btnSnap" type="button" value="Take Snapshot" onclick="take_snapshot();" />
<input id="btnTran" type="button" value="Transfer" onclick="transfer();" />

Just in case this has anything to with it, this is what my hidden variable looks like:

<asp:HiddenField ID="hiddensquare" runat="server" Value="" />

I would like to call these two javascript functions with one button click, rather than two. However, when I try to do so, say, by simply putting in take_snapshot(); transfer(); in one of the button's onclick, or making a new javascript function that calls both of them, I always get a lot less data being passed into the hidden variable (I mean like much less than 1/10th) than if I have it done so I need to press two html buttons to allows to me to save.

Does anyone have any idea of what is going on here? Thanks!


Solution

  • The issue is that Webcam.snap() is asynchronous, so it's not necessarily complete when transfer() is executed.

    Fortunately the first argument of snap is a callback function which will wait until snap is complete to execute, so you can simply pass transfer as the first argument to snap and you should achieve the results you're looking for:

    function take_snapshot() {
            Webcam.snap(transfer, myCanvas);
        }