如何将onClick事件处理程序添加到canvas元素并控制鼠标移动操作?

时间:2017-04-12 12:16:49

标签: javascript jquery canvas html5-canvas

我在画布中有一个图像,我想要点击图像并拖动图像(不要抬起鼠标左键)和图像在释放鼠标左键的位置。现在,只要鼠标图标悬停在画布上,图像随之移动,我就会尝试添加一个onclick监听器事件,但我确信我的新手会阻碍我的进度。

这是我到目前为止所提出的。如何使用现有代码完成此工作?

var canvas = document.getElementById('customCanvas');
    var context = canvas.getContext('2d');

    make_base();

    function make_base()
    {
        upload_image = new Image();
        upload_image.src = 'https://lh3.googleusercontent.com/-6Zw-hozuEUg/VRF7LlCjcLI/AAAAAAAAAKQ/A61C3bhuGDs/w126-h126-p/eagle.jpg';
        upload_image.onload = function(){
            context.drawImage(upload_image, 0, 0);
            canvas.addEventListener('click', canvas.onmousemove = function(e) {
                /// correct mouse position so its relative to canvas
                var rect = canvas.getBoundingClientRect(),
                        constantX = 0, constantY = 0,
                        x = e.clientX - rect.left,
                        y = e.clientY - rect.top;

                context.clearRect(0, 0, canvas.width, canvas.height);
                context.drawImage(upload_image, x, y);
            });
        }
    }
* {
  margin: 0;
  padding: 0;
}

html, body {
  width: 100%;
  height: 100%;
}

.sidepane {
  height: 100%;
  background: #E8E8EA;
}

.sidepane .form {
  height: 80px;
  margin: 10px 0;
}

.sidepane .assets {
  width: 100%;
}

#assetText {
  font-size: 24px;
}

.assets .text, .assets .image {
  margin: 10px 0;
}
.assets .image ul li {
  width: 50px;
  height: 50px;
  margin-right: 5px;
  float: left;
  overflow: hidden;
}
.assets .image ul li img {
  width: 100%;
  height: 100%;
}

.canvas .block {
  position: relative;
  width: 600px; height: 600px;
  margin: 10px;
  border: 1px solid;
  box-shadow: 0px 0px 5px black;
}

.item {
  border: 1px solid transparent;
  position: absolute;
}

.item.selected {
  border-color: blue;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="sidepane col-sm-2 col-md-2 col-lg-2">
    <form method="post" action="/images" enctype="multipart/form-data">
    <!--<div class="form">-->
        <h3>Form</h3>
        <input type="file" class="form-control" placeholder="Upload Your Images" name="filefield">
        <button id="submit" class="btn btn-default">upload</button>
        <!-- Upload Form here -->
        <!--</div>-->
        <hr />
        <div class="assets">
            <h3>Assets</h3>
            <div class="text">
                <h4>Text</h4>
                <input type="text" name="textfield">
                <button id="addText" class="btn btn-default">Add Text</button>
            </div>
            <div class="image">
                <h4>Images</h4>
                <ul class="list-unstyled">
                    <!-- List of images here -->
                    <!-- <li><img src="images/sample.jpeg" class="img-rounded" /></li> -->
                </ul>
            </div>
        </div>

        <input type="submit" >
    </form>
</div>
<!-- canvas -->
<div class="canvas col-sm-8 col-md-8 col-lg-8">
    <div class="block">
        <!-- Add images and texts to here -->
        <canvas id="customCanvas" width="598" height="598" style="border: 1px solid #000000">

        </canvas>
    </div>
</div>

3 个答案:

答案 0 :(得分:0)

您正在寻找的事件将是https://developer.mozilla.org/en/docs/Web/Events/mousedown - AFAIK(如果我错了,请更正我),但点击事件只会在完成点击事件(向下和向上)时触发。

以下是一些示例代码;

var mouseX;
var mouseY; // Accessible outside the function. Easier access to canvas drawing.

var canvas = ''; // Complete this to get canvas element

canvas.addEventListener("mousedown", function(mouse){
  // Get mouse co-ordinates
})

在此事件监听器中,您可以检查当前的鼠标位置......

var canvasElement = element.getBoundingClientRect()
mouseX = mouse.pageX - canvasElement.left;
mouseY = mouse.pageY - canvasElement.top;

在将图像绘制到画布时使用这些变量来确定图像的x和y位置。当鼠标在画布上移动时,这些应该会改变。即,将它们传递给 make_base()函数;

make_base(mouseX, mouseY)

更新您的绘图功能以解释它们;

 function make_base(mouseX, mouseY)
    {
        upload_image = new Image();
        upload_image.src = 'https://lh3.googleusercontent.com/-6Zw-hozuEUg/VRF7LlCjcLI/AAAAAAAAAKQ/A61C3bhuGDs/w126-h126-p/eagle.jpg';
        upload_image.onload = function(){
            context.drawImage(upload_image, 0, 0);
            canvas.addEventListener('click', canvas.onmousemove = function(e) {
                /// correct mouse position so its relative to canvas
                var rect = canvas.getBoundingClientRect(),
                        constantX = 0, constantY = 0,
                        x = mouseX,
                        y = mouseY

                context.clearRect(0, 0, canvas.width, canvas.height);
                context.drawImage(upload_image, x, y);
            });
        }
    }

请注意上面的代码不完整,例如,X和Y将基于您的鼠标在PAGE上的位置,而不是CANVAS。需要单独计算才能解决这个问题。

答案 1 :(得分:0)

首先,您必须检查鼠标是否在图像上,然后检查是否要尝试拖动图像。要做到这一点,您需要一些事件,mousedownmouseupmousemove。要检查鼠标指针是否在图像上,您必须获得该图像的X, Y, width, height。最终代码如下。

修改

更多变化。 Image类没有XY属性,因此我必须定义将存储该数据并对isInside函数进行一些更改的变量。

&#13;
&#13;
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
var context = canvas.getContext('2d');
canvas.width = 300;
canvas.height = 300;
var upload_image;
var imageX, imageY;
var mouseX, mouseY;
var imageDrag = false;

make_base();

canvas.addEventListener("mousemove", function (evt) {
    var mousePos = getMousePos(canvas, evt);
    mouseX = mousePos.x;
    mouseY = mousePos.y;
});

function getMousePos(canvas, event) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: event.clientX - rect.left,
        y: event.clientY - rect.top
    };
}

function isInsideImage(rect) {
    var pos = { x: mouseX, y: mouseY };
    return pos.x > imageX && pos.x < imageX + rect.width && pos.y < imageY + rect.height && pos.y > imageY;
}

function make_base()
{
    upload_image = new Image();
	imageX = 0;
	imageY = 0;
    upload_image.onload = function(){
        context.drawImage(upload_image, 0, 0);
    }
    upload_image.src = 'https://lh3.googleusercontent.com/-6Zw-hozuEUg/VRF7LlCjcLI/AAAAAAAAAKQ/A61C3bhuGDs/w126-h126-p/eagle.jpg';
}

canvas.addEventListener("mousedown", function (evt) {
    if(isInsideImage(upload_image)) {
        imageDrag = true;
    }
});

canvas.addEventListener("mouseup", function (evt) {
    if(imageDrag)
        imageDrag = false;
});

setInterval(function() {
    if(imageDrag) {
		context.clearRect(0, 0, canvas.width, canvas.height);
		imageX = mouseX;
        imageY = mouseY;
        context.drawImage(upload_image, imageX, imageY);
    }
}, 1000/30);
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

或者,您可以在图片下嵌入一个外部链接,带您去任何想去的地方!