开发者

Implementing stretching rubber band effect in Canvas

I'm making a simple prototype in HTML5 开发者_开发知识库canvas, and want to basically draw a slingshot. When someone clicks down and pulls back, I want the rubber band to stretch. It doesnt have to be perfect.

Any suggestions on how I can do this? I'm not too certain how to mimic the effect :)

thanks


It would be easier to do with SVG than with canvas, especially using a library like Raphaël. See this demo – that is not very different from what you want to do. If you use Raphaël then it will be much more portable than canvas, because it will work even on IE 6 (using VML).

Update:

(Fixed the Fiddle example - it had some outdated dependencies - now it's fixed)

Ok, see THIS DEMO. It should be pretty much what you explained or at least it should get you started. Here is the code:

var R = Raphael(10, 10, 400, 400);

var l = R.path("M100 200L200 200L300 200");
l.attr({
    stroke: 'red',
    'stroke-width': 4
});

var c = R.circle(200, 200, 10).attr({
    fill: 'white',
    stroke: 'red',
    'stroke-width': 4
});

function move(dx, dy) {
    var x = 200 + dx, y = 200 + dy; 
    this.attr({cx: x, cy: y});
    l.attr({path: "M100 200L"+x+" "+y+"L300 200"});
}
function start() {
    c.stop();
    l.stop();
}
function end() {
    this.animate({cx: 200, cy: 200}, 2000, "elastic");
    l.animate({path: "M100 200L200 200L300 200"},
             2000, "elastic");
}
c.drag(move, start, end);


a lot of these kind of behaviours have been implemented and written about in the Flash community. Krazy dad has some nice articles + code on elasticity. http://www.krazydad.com/bestiary/bestiary_springyTitles.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜