【问题标题】:Make image drawn on canvas draggable with JavaScript使用 JavaScript 使画在画布上的图像可拖动
【发布时间】:2016-08-26 01:56:53
【问题描述】:

我能够成功地在 HTML 画布上绘制图像。但我需要能够在画布上拖动图像。

我知道这个功能可以通过一些 JavaScript 库(如 KinectJS)轻松实现。但我只想用简单的 JavaScript 来做。

window.onload = function(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var destX = 0;
var destY = 0;
var imageObj = new Image();

imageObj.onload = function(){
  context.drawImage(imageObj, destX, destY);
};
imageObj.src = "westeros.png";
<canvas id="myCanvas" height=1024 width=360></canvas>

【问题讨论】:

    标签: javascript html5-canvas


    【解决方案1】:

    要进行拖动处理 3 个鼠标事件:

    1. mousedown -- 设置一个标志,指示拖动已经开始。

    2. mouseup -- 清除拖动标志,因为拖动结束

    3. mousemove -- 如果设置了拖动标志,则清除画布并在鼠标位置绘制图像

    这里有一些代码:

    <!doctype html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    
    <style>
        body{ background-color: ivory; }
        canvas{border:1px solid red;}
    </style>
    
    <script>
    $(function(){
    
    
        var img = new Image();
        img.onload = function(){
            ctx.drawImage(img, 0,0);
        };
        img.src = "http://images.christmastimeclipart.com/images/2/1271716593176_1788/img_1271716593176_17881.jpg";
    
        var canvas=document.getElementById("canvas");
        var ctx=canvas.getContext("2d");
        var canvasOffset=$("#canvas").offset();
        var offsetX=canvasOffset.left;
        var offsetY=canvasOffset.top;
        var canvasWidth=canvas.width;
        var canvasHeight=canvas.height;
        var isDragging=false;
    
        function handleMouseDown(e){
          canMouseX=parseInt(e.clientX-offsetX);
          canMouseY=parseInt(e.clientY-offsetY);
          // set the drag flag
          isDragging=true;
        }
    
        function handleMouseUp(e){
          canMouseX=parseInt(e.clientX-offsetX);
          canMouseY=parseInt(e.clientY-offsetY);
          // clear the drag flag
          isDragging=false;
        }
    
        function handleMouseOut(e){
          canMouseX=parseInt(e.clientX-offsetX);
          canMouseY=parseInt(e.clientY-offsetY);
          // user has left the canvas, so clear the drag flag
          //isDragging=false;
        }
    
        function handleMouseMove(e){
          canMouseX=parseInt(e.clientX-offsetX);
          canMouseY=parseInt(e.clientY-offsetY);
          // if the drag flag is set, clear the canvas and draw the image
          if(isDragging){
              ctx.clearRect(0,0,canvasWidth,canvasHeight);
              ctx.drawImage(img,canMouseX-128/2,canMouseY-120/2,128,120);
          }
        }
    
        $("#canvas").mousedown(function(e){handleMouseDown(e);});
        $("#canvas").mousemove(function(e){handleMouseMove(e);});
        $("#canvas").mouseup(function(e){handleMouseUp(e);});
        $("#canvas").mouseout(function(e){handleMouseOut(e);});
    
    }); // end $(function(){});
    </script>
    
    </head>
    
    <body>
        <canvas id="canvas" width=400 height=300></canvas>
    </body>
    </html>
    

    【讨论】:

    • 易于添加触摸。对于触摸,您将处理类似于鼠标事件的这 3 个事件:touchstart、touchend 和 touchmove。
    • 触摸是一个概括性的话题,可以根据操作系统而变化,但通常:(1)监听“touchmove”,然后(2)通过 touches[0].pageX & 获取位置。 pageY 和 (3) 在 x/y 处绘制图像。您必须 event.preventDefault() 来停止触摸事件拖动页面。 [canvas.addEventListener("touchmove", handleMove, false);函数句柄移动(e){ e.preventDefault(); var touches = e.originalEvent.touches; if(isDragging){ ctx.clearRect(0,0,canvasWidth,canvasHeight); ctx.drawImage(img,touches[0].pageX-128/2,touches[0].pageY-120/2,128,120);}}]
    • 如何让它在画布的外部可拖动?
    • 不要将画布绘图与 DOM 元素混淆。画布绘图只是画布表面上的像素。因此,它们仅限于在画布内显示,不能拖到画布外。
    • @Sid 这是一个previous Q&A,其中的示例展示了如何拖动多个图像。干杯!
    【解决方案2】:

    markE's answer 让我走了大部分路,但我在识别我的鼠标所在的位置时遇到了一些问题。我附上了我的代码,尽管因为我使用的是 OO JS,所以它的结构会有所不同:

        hitImage: function() {
          return (this.startX > this.imageX && this.startX < this.imageX + this.imageWidth && this.startY > this.imageY && this.startY < this.imageY + this.imageHeight);
        },
    
        handleMouseDown: function(e){
          this.startX = parseInt(e.clientX - this.offsetX);
          this.startY = parseInt(e.clientY - this.offsetY);
          // set the drag flag
          this.isDragging= this.hitImage;
        },
    
        handleMouseUp: function(e,img){
          this.startX=parseInt(e.clientX-this.offsetX);
          this.startY=parseInt(e.clientY-this.offsetY);
          // clear the drag flag
          this.isDragging=false;
          this.drawImage(e,img);
        },
    
        handleMouseOut: function(e,img){
          this.handleMouseUp(e,img);
        },
    
        handleMouseMove: function(e,img){
          // only compute new positions if in drag
          if(this.isDragging){
    
            this.canMouseX=parseInt(e.clientX - this.offsetX);
            this.canMouseY=parseInt(e.clientY - this.offsetY);
          // move the image by the amount of the latest drag
            var dx = this.canMouseX - this.startX;
            var dy = this.canMouseY - this.startY;
    
            this.imageX += dx;
            this.imageY += dy;
            // Negative image locations break the pattern in this.fillPattern
            this.imageY = Math.max(0, this.imageY);
            this.imageX = Math.max(0, this.imageX);
    
            // reset the startXY for next time
            this.startX = this.canMouseX;
            this.startY = this.canMouseY;
    
            this.drawImage(e,img);
          }
    

    【讨论】:

    • 我正在学习使用 HTML5 画布拖动图像。我对你的方法很感兴趣,但我发现了一个问题:我在你的代码中的任何地方都找不到 drawImage() 函数。你能为这个sn-p提供一个plunker或fiddle吗?谢谢。
    • 你可以在这里了解drawImage函数:developer.mozilla.org/en-US/docs/Web/API/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2022-10-07
    • 2012-08-16
    • 1970-01-01
    相关资源
    最近更新 更多