[英]Canvas image object is not moving with style.left
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和HTML5制作动画或说移动对象:但是我被困住了,谁能告诉我我的代码有什么问题:
javascript code (whats wrong in this code below): javascript代码(以下这段代码有什么错误):
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: HTML5代码:
** **
"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>
** **
Your mistake is that your image is not a DOM object and you are trying to move it with DOM style. 您的错误是您的图像不是DOM对象,并且您尝试使用DOM样式移动它。 Instead you must recall drawImage() with updated coordinates.
相反,您必须使用更新后的坐标调用drawImage()。
var X = 0
function moveRight(){
X += 10;
context.drawImage(imageObj,X,0,360,240);
}
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.