在html5中绘制路径然后绘制图像

时间:2012-04-22 05:31:56

标签: javascript html5 canvas html5-canvas

我正在尝试绘制一个圆圈,然后让图像跟随周围的圆圈。后来我想旋转并相对于绘制的圆圈移动图像。我面临的问题是,当我尝试旋转图像时,它不会旋转。它也没有在控制台中显示错误。我有功能允许我移动圆圈,图像随之移动,我似乎无法旋转图像。

以下是代码:

draw: function(){
//draw self on canvas;
//intended only to be called from update, should never
//need to be deliberately called
ctx = this.context;

ctx.save();
ctx.fillStyle="#000000";
ctx.beginPath();

//void arc(double x, double y,
//         double radius, double startAngle, double endAngle,
//          optional boolean anticlockwise = false);
ctx.arc(this.x,this.y,this.size,0,Math.PI*2,true);
ctx.closePath();
ctx.fill();
//ctx.translate(this.x, this.y);
ctx.rotate(this.imgAngle);
//draw the hammer

ctx.drawImage(this.hammer,this.hammerX,this.hammerY,100,100)
ctx.rotate(Math.PI/2);

ctx.restore();

},

2 个答案:

答案 0 :(得分:0)

旋转只会影响旋转完成后的图纸。

您可以尝试将旋转调用移动到需要旋转的对象之前吗?

答案 1 :(得分:0)

<强> Live Demo

尝试将代码更改为以下内容。您需要在绘制之前执行旋转。您可以将画布转换为实体位置,然后在x:0,y:0处绘制图像以获得所需效果。注意我做了0-50,0-50,因为它将原点放在中心,因为宽度和高度都是100.这意味着你的图像将围绕它的中心而不是它的角落旋转。

//draw the hammer
ctx.translate(this.hammerX, this.hammerY);
ctx.rotate(this.imgAngle);
ctx.drawImage(this.hammer,0-50,0-50,100,100);
相关问题