2012-06-13 49 views
2

注:我只是想在一个时间是否可以在html5画布上移动已绘制的形状?

Circle.prototype.create = function(){ 
    if (this.canvas === null){ 
     throw "Circle has no canvas"; 
    } 
    if (this.canvas.getContext){ 
     this.context = this.canvas.getContext("2d"); 
     this.context.fillStyle = this.color; 
     this.context.beginPath(); 
     this.context.arc(this.x,this.y,this.r,0,Math.PI*2); 
     this.context.closePath(); 
     this.context.fill(); 
    } 
} 

这打圈移动1种形状,注意context变量保存为一个对象的属性

我已经写了这个功能移动现有的这圆圈使用原始圆圈context

Circle.prototype.move_to = function(x,y){ 
    if (this.context === null){ 
     throw "Circle has no context to move"; 
    } 
    this.x = x; this.y = y; 
    this.context.translate(x, y); 
    this.context.beginPath(); 
    this.context.arc(this.x,this.y,this.r,0,Math.PI*2); 
    this.context.closePath(); 
    this.context.fill(); 
} 

但是,这只是绘制另一个圆圈。

我怎样才能让它移动现有的?

没有清除原来的和绘图的另一个!

+3

你不能,你需要(例如)在内存中拥有一个画布,这将被清零,重新绘制并复制到画布上可见每一帧。看看 - https://developer.mozilla.org/en/Canvas_tutorial/Basic_animations – Yaniro

+1

看一下像[Fabric.js](http://fabricjs.com)这样的画布库, – kangax

回答

4

这是从我的另一个答案复制,但简短的答案是你不能这样做。你可以做的就是将信息存储在一个对象中。

var rectangle = {x:10,y:20,width:20,height:40}; 

然后就可以改变的任何值和重绘它,必须首先清除画布,或至少你重绘到画布的那部分。

//clear the canvas then draw 
rectangle.width = 60; 
ctx.fillRect(rectangle.x,rectangle.y,rectangle.width,rectangle.height); 

Live Demo