【发布时间】:2014-02-18 18:27:08
【问题描述】:
我需要在画布内旋转图像..我用谷歌搜索并在 stackoverflow 中看到了类似的问题。我学到的是
我无法在画布内旋转单个对象。
我只能旋转整个画布。
所以我需要平移到对象的中心,然后旋转 画布。
我遵循完全相同的东西,但我对翻译到图像中心感到震惊。下面是我正在使用的代码。这里是 jsfiddle http://jsfiddle.net/J6Pfa/1/。这个正在旋转整个画布,无论图像..有人指导我哪里错了。谢谢
//hero canvas
ball = new Hero();
var ang = 0;
herocanvas = document.createElement("canvas");
herocanvas.width = herocanvas.width = 500;
herocanvas.height = herocanvas.height = 500;
heroctx = herocanvas.getContext('2d');
document.body.appendChild(herocanvas);
var requestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
var imgSprite = new Image();
imgSprite.src = 'http://i.imgur.com/WTgOHGg.png';
imgSprite.addEventListener('load',init,false);
function init()
{
startloop();
}
function startloop()
{
heroctx.save(); //saves the state of canvas
clearherobg() ; // clear canvas
heroctx.translate(ball.drawX, ball.drawY); //let's translate
heroctx.rotate(Math.PI / 180 * (ang += 4));
ball.draw(); // draw image here
heroctx.restore();
requestAnimFrame(startloop);
}
function Hero() {
this.srcX = 0;
this.srcY = 500;
this.drawX = 220;
this.drawY = 200;
this.width = 100;
this.height = 40;
this.speed = 5;
this.isUpKey = false;
this.isRightKey = false;
this.isDownKey = false;
this.isLeftKey = false;
}
Hero.prototype.draw = function () {
heroctx.drawImage(imgSprite,this.srcX,this.srcY,this.width,this.height,this.drawX,this.drawY,this.width,this.height);
};
function clearherobg() {
heroctx.clearRect(0,0,500,500);
}
看不懂完整代码的朋友请查看startloop(),这是主要的无限循环。ball.drawX and ball.drawY是画布内图像的x和y位置
【问题讨论】:
-
Hero 的 drawX 和 drawY 需要更新到画布的新坐标系,如果你希望它在画布的中间它需要是 0,0。
-
类似这样的东西:jsfiddle.net/J6Pfa/3
-
感谢 tomasz 工作.. 你能回答吗?所以我可以接受
标签: javascript html canvas