簡體   English   中英

有人可以告訴我如何在畫布上移動圖像嗎?

[英]Can someone tell me how to make an image inside a canvas move?

有人可以告訴我如何使畫布上的圖像移動嗎? 在游戲的先前版本中,我將圖像設置為div,因此它的移動效果還不錯,但我無法弄清楚。 這讓我寫得更多,所以請忽略此部分:

 //this is the variable for the image i want to move var blinky = { x: 0, y: 0 }; //this makes the image only appear when the page is loaded var byReady = false; var byImage = new Image(); byImage.onload = function(){ byReady = true; }; byImage.src = "blinky.jpg" //this puts the images on the canvas var render = function(){ if(bgReady){ ctx.drawImage(bgImage,0,0); } if(hrReady){ ctx.drawImage(hrImage,hero.x, hero.y); } if(emReady){ ctx.drawImage(emImage,monster.x, monster.y); } if(byReady){ ctx.drawImage(byImage,blinky.x,blinky.y); } //this moves a div around the screen randomly $(document).ready(function(){ animateDiv(); }); function makeNewPosition(){ // Get viewport dimensions (remove the dimension of the div) var h = $(window).height() - 30; var w = $(window).width() - 30; var nh = Math.floor(Math.random() * h); var nw = Math.floor(Math.random() * w); return [nh,nw]; } function animateDiv(){ var newq = makeNewPosition(); var oldq = $('#blinky').offset(); var speed = calcSpeed([oldq.top, oldq.left], newq); $('#blinky').animate({ top: newq[0], left: newq[1] }, speed, function(){ animateDiv(); }); }; function calcSpeed(prev, next) { var x = Math.abs(prev[1] - next[1]); var y = Math.abs(prev[0] - next[0]); var greatest = x > y ? x : y; var speedModifier = 0.1; var speed = Math.ceil(greatest/speedModifier); return speed; } 

基本上,您需要一個繪制循環(使用requestAnimationFrame ),以在畫布的上下文上繪制圖像。

這是完整的jsfiddle: http : //jsfiddle.net/ety656yq/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM