Reputation: 11
Recently i am trying to animate or say move a object using javascript and HTML5: but i am stuck , can anybody tell me what's wrong with my code:
javascript code (whats wrong in this code below):
var canvas = document.getElementById('my-first');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj,0,0,360,240);
};
imageObj.src = 'img/bakshi.jpg';
imageObj.style.position= 'relative';
imageObj.style.left = '0px';
function moveRight(){
imageObj.style.left = parseInt(imageObj.style.left)+10+'px';
};
HTML5 code:
**
"My experimentation"
<canvas id="my-first" width="360" height="240">
your browser doesn't support canvas
</canvas>
<script src="file.js"></script>
<audio src="i_am_bakshi.mp3" controls autoplay> </audio>
<input type="button" value="Click Me" onclick="moveRight();" />
</body>
</html>
**
Upvotes: 0
Views: 361
Reputation: 33890
Your mistake is that your image is not a DOM object and you are trying to move it with DOM style. Instead you must recall drawImage() with updated coordinates.
var X = 0
function moveRight(){
X += 10;
context.drawImage(imageObj,X,0,360,240);
}
Upvotes: 1
Reputation: 454
You shouldn't move the image using the styles, in fact, you're drawing it into canvas.
You should draw it to another position:
context.drawImage(imageObj,parseInt(imageObj.style.left)+10,0,360,240);
Upvotes: 0