gpt4 book ai didi

jquery - HTML5 Canvas 绘图拖放

转载 作者:行者123 更新时间:2023-11-28 13:33:09 25 4
gpt4 key购买 nike

我有如下 HTML 5 圆形绘图示例

http://i.stack.imgur.com/SVPO9.jpg

这是它的绘图脚本(HTML5 和 jQuery)

http://jsfiddle.net/eGjak/275/

$.each(circles, function() {
drawCircle(this);
drawLine(mainCircle, this);
});

我需要将其升级为拖放(用户可以用线拖动主圆周围的子圆)

我如何使用 html5、css3、jQuery 做到这一点?

最佳答案

http://jsfiddle.net/eGjak/503/

你必须在 Canvas 上找到局部的 x 和 y,然后计算距离(想想勾股定理,aSquared + bSquare = cSquared),看看距离是否小于圆的半径(也就是鼠标在圆内)圆圈)

在您当前拥有的代码之后添加此代码

var focused_circle, lastX, lastY ; 

function test_distance( n, test_circle ){ //see if the mouse is clicking circles
var dx = lastX - test_circle.x,
dy = lastY - test_circle.y;

//see if the distance between the click is less than radius
if( dx * dx + dy * dy < test_circle.r * test_circle.r ){
focused_circle = n;
$(document).bind( 'mousemove.move_circle' , drag_circle );
$(document).bind( 'mouseup.move_circle' , clear_bindings);
return false; // in jquery each, this is like break; stops checking future circles
}
}
$('#cv').mousedown( function( e ){
lastX = e.pageX - $(this).offset().left;
lastY = e.pageY - $(this).offset().top;
$.each( circles, test_distance );
});

function drag_circle( e ){
var newX = e.pageX - $('#cv').offset().left,
newY = e.pageY - $('#cv').offset().top;

//set new values
circles[ focused_circle ].x += newX - lastX;
circles[ focused_circle ].y += newY - lastY;

//remember these for next time
lastX = newX, lastY = newY;

//clear canvas and redraw everything
ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height );
drawCircle(mainCircle);
$.each(circles, function() {
drawCircle(this);
drawLine(mainCircle, this);
});

}

function clear_bindings( e ){ // mouse up event, clear the moving and mouseup bindings
$(document).unbind( 'mousemove.move_circle mouseup.move_circle' );
focused_circle=undefined;
}

还有其他方法可以做到这一点以及节省速度的方法,尽管这应该可以解决问题。

关于jquery - HTML5 Canvas 绘图拖放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10859694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com