[英]Canvas image object is not moving with style.left
最近,我試圖使用javascript和HTML5制作動畫或說移動對象:但是我被困住了,誰能告訴我我的代碼有什么問題:
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代碼:
**
我的實驗
<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>
**
您的錯誤是您的圖像不是DOM對象,並且您嘗試使用DOM樣式移動它。 相反,您必須使用更新后的坐標調用drawImage()。
var X = 0
function moveRight(){
X += 10;
context.drawImage(imageObj,X,0,360,240);
}
您不應該使用樣式移動圖像,實際上是將其繪制到畫布中。
您應該將其繪制到另一個位置:
context.drawImage(imageObj,parseInt(imageObj.style.left)+10,0,360,240);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.