【问题标题】:Html 5 Rotate image inside the CanvasHtml 5 在画布内旋转图像
【发布时间】:2014-02-18 18:27:08
【问题描述】:

我需要在画布内旋转图像..我用谷歌搜索并在 stackoverflow 中看到了类似的问题。我学到的是

  1. 我无法在画布内旋转单个对象。

  2. 我只能旋转整个画布。

  3. 所以我需要平移到对象的中心,然后旋转 画布。

我遵循完全相同的东西,但我对翻译到图像中心感到震惊。下面是我正在使用的代码。这里是 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


【解决方案1】:

Hero 的 drawX 和 drawY 需要更新到画布的新坐标系,如果你想让它在画布的中间它需要是 0,0。

类似这样的:jsfiddle.net/J6Pfa/3

【讨论】:

    【解决方案2】:

    嗯,我不完全明白你想要实现什么,一个在圆形路径上移动的图像?还是在一个地方有图像,然后旋转它?

    【讨论】:

    • 图像在一个地方,然后旋转它
    • 一定要通过html5来做吗?我猜更简单的解决方案是使用css3。这是fiddle 示例,悬停时。我不知道您是否需要始终旋转它,但是此代码可用于您希望的任何事情
    • 如果你想让它一直旋转,你可以使用类似fiddle
    • 感谢 css ..但我需要 html 兄弟 ..+1 为您的 cmets 虽然
    • okey check this 也许,但是它使用了一个 lil java
    猜你喜欢
    • 2018-12-16
    • 1970-01-01
    • 2012-04-05
    • 2021-09-27
    • 2016-03-13
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    相关资源
    最近更新 更多