2014-09-23 4 views
0

캔버스를 처음 사용하여 간단한 선형 모션 애니메이션 예제를 HTML Canvas Tutorials에서 시작했습니다.HTML5 캔버스 선형 이미지 애니메이션

대신 이미지를 표시하도록 사각형을 대체 할 수 있습니까?

코드를 편집하려고 할 때마다 출력되는 이미지가 정적이므로 분명히 잘못된 것이 있습니다.

window.requestAnimFrame = (function(callback) { 
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || 
              function(callback) { 
               window.setTimeout(callback, 1000/60); 
             }; 
            })(); 

            function drawRectangle(myRectangle, context) { 
             context.beginPath(); 
             context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height); 
             context.fillStyle = '#8ED6FF'; 
             context.fill(); 
             context.lineWidth = myRectangle.borderWidth; 
             context.strokeStyle = 'black'; 
             context.stroke(); 
             context.drawImage = 'images/player.png'; 
            } 

            function animate(myRectangle, canvas, context, startTime) { 
             // update 
             var time = (new Date()).getTime() - startTime; 

             var linearSpeed = 200; 
             // pixels/second 
             var newX = linearSpeed * time/1000; 

             if (newX < canvas.height - myRectangle.height - myRectangle.borderWidth/2) { 
              myRectangle.y = newX; 
             } 

             // clear 
             context.clearRect(0, 0, canvas.width, canvas.height); 

             drawRectangle(myRectangle, context); 

             // request new frame 
             requestAnimFrame(function() { 
              animate(myRectangle, canvas, context, startTime); 
             }); 
            } 
            var canvas = document.getElementById('monopoly-piece'); 
            var context = canvas.getContext('2d'); 
            var img = new Image; 

            var myRectangle = { 
             x: 20, 
             y: 0, 
             width: 50, 
             height: 50, 
             borderWidth: 5, 
             img: 'images/player.png' 
            }; 

            drawRectangle(myRectangle, context); 

            // wait one second before starting animation 
            setTimeout(function() { 
             var startTime = (new Date()).getTime(); 
             animate(myRectangle, canvas, context, startTime); 
            }, 1000); 

어떤 도움을 주시면 감사하겠습니다. 미리 감사드립니다. :) jsfiddle에서

+0

작동 할 수이 도움이 될 수 있습니다 : http://www.w3schools.com/tags/canvas_drawimage.asp 응답 @snies에 대한 – snies

+0

덕분에 내가 알고 있어요 drawImage 메서드를 사용하지만 캔버스의 완전한 초보자로서 나는 그것을 기존 코드로 구현하는 방법을 완전히 모릅니다 ... – user2879183

답변

3

좋아, 여기 당신이 이동 작업 예제 : http://jsfiddle.net/zymz2dLo/61/

window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.oRequestAnimationFrame; 

// get canvas and create drawing context 
// this assumes there is some canvas with id 'myCanvas' 
var canvas = document.getElementById('myCanvas'); 
var context = canvas.getContext('2d'); 

// create image 
var img = document.createElement("img"); 

// fill image from data string 
//img.src = "data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; // insert a dot image contains 1px 

// or fill image from url 
img.src = "http://www.w3schools.com/tags/img_the_scream.jpg" 


// define the linear speeds 
var xSpeed = 0.05; //px per ms 
var ySpeed = 0.01; 

// this function will animate the next 'frame' 
// based on input from the last 
function animate(nowTime, lastTime, xPos, yPos) { 
    if ((img.style.width + xPos) > canvas.width) { 
     xPos = 0; 
     yPos = 0; 
    } 

    // calculate the delta in order to match the speed 
    var timeDelta = nowTime - lastTime; 
    var xDelta = xSpeed * timeDelta; 
    var yDelta = ySpeed * timeDelta; 

    // clear 
    context.clearRect(0, 0, canvas.width, canvas.height); 

    //draw img 
    context.drawImage(img, xPos, yPos); 

    //schedule animation for the next available frame 
    requestAnimationFrame(
     //wrap animate in a anonymous function to 
     //match the callback signature 
     function(timestamp){ 
      animate(timestamp, nowTime, xPos + xDelta, yPos + yDelta); 
     } 
    ); 
} 

animate(0, 0, 10, 1); 

추가 정보는 여기에서 찾을 수 있습니다 :

http://www.w3schools.com/tags/canvas_drawimage.asp

How to generate an Image from imageData in javascript?

https://developer.mozilla.org/en/docs/Web/API/window.requestAnimationFrame

편집 : 위의 예는 setTimeout 호출에서 requestAnimationFrame으로 통화를 조금 감싸기 위해 최대한 빨리 업데이트합니다.

+0

와우 덕분에 많은 @snies. 하나의 작은 것은 내가 사각형을 캔버스 가장자리에 맞추면 애니메이션이 멈추도록 이미지가 필요하다는 것입니다.이 튜토리얼에서는 사각형을 사용합니다. requestAnimationFrame 함수와 관련이 있습니까? – user2879183

+0

예,'if (xPos snies

0

고맙습니다. @snies. 나는 다음 코드로 내가 찾고 있던 효과를 얻을 수 있었다. 아마 정리하는의 비트와 함께 할 수 있지만, 지금

window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.oRequestAnimationFrame; 

            var canvas = document.getElementById('monopoly-piece'); 
            var context = canvas.getContext('2d'); 

            var img = document.createElement("img"); 
            img.src = "images/player.png" 

            var xSpeed = 0; //px per ms 
            var ySpeed = 0.1; 

            function animate(nowTime, lastTime, xPos, yPos) { 
             // update 
             if ((img.style.height + yPos) > canvas.height) { 
              xPos = 0; 
              yPos = 0; 
             } 
             var timeDelta = nowTime - lastTime; 
             var xDelta = xSpeed * timeDelta; 
             var yDelta = ySpeed * timeDelta; 

             // clear 
             context.clearRect(0, 0, canvas.width, canvas.height); 

             //draw img 
             context.drawImage(img, xPos, yPos); 

             if (yPos > canvas.height - img.height) { 

             } 
             else { 
              requestAnimationFrame(
                function(timestamp){ 
                 animate(timestamp, nowTime, xPos + xDelta, yPos + yDelta); 
                } 
               ); 
              } 

            } 

           animate(0, 0, 20, 1); 
관련 문제