我需要在画布内旋转图像..我用Google搜索并在stackoverflow中看到类似的问题。我学到的是
我不能在canvas中旋转单个对象。
我只能旋转整个画布。
所以我需要翻译到对象的中心,然后旋转 画布。
我跟着完全相同的东西,但我对翻译到图像中心感到震惊。下面是我正在使用的代码。这是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位置
答案 0 :(得分:0)
答案 1 :(得分:0)
Hero的drawX和drawY需要更新到画布的新坐标系,如果你想让它在画布的中间,它需要是0,0。
像这样:jsfiddle.net/J6Pfa/3