Reputation: 37
I am having an issue with my webcam project. The webpage is able to access my webcam and the camera turns on, but nothing is displayed. The error which I get is: "Uncaught TypeError: Cannot set property 'src' of null". Thanks in advance for any help.
index.html
<html>
<head>
<title>Pi Webcam Server</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="webcam.js"></script>
</head>
<body>
<div id="camDiv">
<video autoplay id="camVideo">
</video>
</div>
</body>
</html>
webcam.js
var camvideo = document.querySelector('camVideo');
navigator.getUserMedia = navigator.getUserMedia
||navigator.webkitGetUserMedia//Chrome;
||navigator.mozGetUserMedia//Firefox
||navigator.msGetUserMedia//IE
||navigator.oGetUserMedia;//Safari
if(navigator.getUserMedia){
navigator.getUserMedia({video:true},
function(stream){camvideo.src = window.URL.createObjectURL(stream);},
function(){alert('error');});
}
EDIT: Whilst my question is sort of similar in nature to the suggested thread, I am unsure what could be corrected in my code to fix it. I cannot move the tags anywhere to affect the DOM in index.html. I have also declared 'camvideo' before I use it and the 'src' element which is giving me trouble is a native HTML attribute and it isn't something which I can declare?
Upvotes: 0
Views: 342
Reputation: 37
I have managed to achieve a working webcam feed. All I needed was to include an Event Listener (as well as the # symbol in the other answer).
window.addEventListener("DOMContentLoaded", function(){
var camvideo = document.querySelector('#camVideo');
navigator.getUserMedia = navigator.getUserMedia
||navigator.webkitGetUserMedia//Chrome;
||navigator.mozGetUserMedia//Firefox
||navigator.msGetUserMedia//IE
||navigator.oGetUserMedia;//Safari
if(navigator.getUserMedia){
navigator.getUserMedia({video:true},
function(stream){camvideo.src = window.URL.createObjectURL(stream);},
function(){alert('error');});
}
}, false);
Upvotes: 0
Reputation: 3308
Try adding the #
character to this line:
var camvideo = document.querySelector('camVideo');
So that it looks like this:
var camvideo = document.querySelector('#camVideo');
Reason: The document.querySelector method works just like everything inside of jQuery's $('...') method. So you can use your `#id .className' selector chains inside of document.querySelector().
This JavaScript code: document.querySelector('#id .className')
is the same as this jQuery code: $('#id .className')
.
Here is a JSFiddle, which shows that without the #
, it will return a null but with it, it will return the video tag/object from the DOM.
Upvotes: 2