实现在画布中拖动图像

Implement dragging an image within a canvas

本文关键字:拖动 图像 布中 实现      更新时间:2023-09-26

我想实现在画布中拖动图像。我想要最简单的代码。到目前为止,我已经看到了很多例子,但它们使用了复杂的实现方式。我想要一个易于学习和实施的示例。

这很难。您首先需要编写一个函数,该函数可以在您单击特定元素时进行检测。然而,在我们能够做到这一点之前,我们必须定义我们所说的"元素"的含义。它是单一绘图指令(例如矩形或圆弧)的产物,还是复杂的东西?(想象一下,我想画一只猫,把整只猫作为一个单元拖动。)

画布不过是像素的集合。如果你想让你的程序有一个"形状"甚至"作为一个单元处理的形状集合"的概念,你需要自己将它们实现为画布本身外部的数据结构。一旦你有了它,你就可以编写一个onmousedown处理程序,它接受点击的x/y点,并确定点击属于哪个形状(如果有的话)(如果它属于多个形状,请检查哪个具有最前面的z索引)。然后添加一个onmousemove处理程序,该处理程序根据形状数据对象中的信息擦除并重新绘制画布上的形状。

这是一个中等难度的问题,具有非常困难的先决条件问题(创建可以描述各种形状以及形状集合的数据结构)。我强烈建议您使用已经解决了这些问题的画布绘图库。我使用cake.js,但有很多选项可用。

如果您不必使用HTML5画布,jQuery UI会简单得多:

HTML:

<img class="drag-me" src="http://www.google.com/images/srpr/logo3w.png">​

JavaScript:

$(function() {
    $('.drag-me').draggable();
});

​看看它在行动:

http://jsfiddle.net/flackend/TQzSe/

jQuery UI API也有很多选项,可以让它按照您想要的方式运行:http://jqueryui.com/demos/draggable/

此外,如果它不能满足您的需要,那么您自己也很容易实现。如果你需要帮助,请在这里发帖。

jsfiddle.net/Zevan/QZejF/5这可能会对您有所帮助。

<html>
<head>
<title>Test Page</title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<canvas id="c" width = "500" height = "500" ></canvas>

<script type="text/javascript">
var canvas = $("#c");
var c = canvas[0].getContext("2d");
//var path = "http://wonderfl.net/images/icon/e/ec/ec3c/ec3c37ba9594a7b47f1126b2561efd35df2251bfm";
var path = "blue.jpg";
var path2 = "purple.jpg";
var image1 = new DragImage(path, 200, 100);
var image2 = new DragImage(path2, 300, 100);
var loop = setInterval(function() {
    c.fillStyle = "gray";
    c.fillRect(0, 0, 500, 500);
    image1.update();
    image2.update();
}, 30);
var mouseX = 0,
    mouseY = 0;
var mousePressed = false;
var dragging = false;
canvas.mousemove(function(e) {
    mouseX = e.offsetX;
    mouseY = e.offsetY;
})
$(document).mousedown(function() {
    mousePressed = true;
}).mouseup(function() {
    mousePressed = false;
    dragging = false;
});
function DragImage(src, x, y) {
    var that = this;
    var startX = 0,
        startY = 0;
    var drag = false;
    this.x = x;
    this.y = y;
    var img = new Image();
    img.src = src;
    this.update = function() {
        if (mousePressed ) {
                var left = that.x;
                var right = that.x + img.width;
                var top = that.y;
                var bottom = that.y + img.height;
                if (!drag) {
                    startX = mouseX - that.x;
                    startY = mouseY - that.y;
                }
                if (mouseX < right && mouseX > left && mouseY < bottom && mouseY > top) {
                    if (!dragging){
            dragging = true;
                        drag = true;
                    }
                }
        } else {
            drag = false;
        }
        if (drag) {
            that.x = mouseX - startX;
            that.y = mouseY - startY;
        }
        c.drawImage(img, that.x, that.y);
    }
}
</script>
</body>
</html>