我是Canvas的新手,我已經開始使用來自HTML Canvas Tutorials的簡單線性動畫動畫的示例。HTML5 Canvas線性圖像動畫
是否可以替換矩形,使其顯示圖像?
每次我試圖編輯代碼時,輸出的圖像都是靜態的,所以我顯然做錯了什麼。
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);
任何幫助將不勝感激,在此先感謝。 :)
這可能幫助:http://www.w3schools.com/tags/canvas_drawimage.asp – snies 2014-09-23 12:18:20
感謝您的答覆@snies我知道的drawImage方法,但作爲一個Canvas的完整新手我不完全確定如何將其實現到現有的代碼... – user2879183 2014-09-23 13:17:27