如何在拖动画布​​图像/对象?画布、拖动、图像、对象

由网友(丶隐伤残)分享简介:1)在画布我画SVG文件(awesome_tiger.svg)与drawSvg(canvg)。2)在该SVG文件我绘制的图像*的(green1.png和pink.png)的*的坐标从JSON越来越。VAR dataJSON =数据|| [];VAR dataJSON2 =数据2 || [];3)所以,在我能够平移该...

1)在画布我画SVG文件(awesome_tiger.svg)与drawSvg(canvg)。

2)在该SVG文件我绘制的图像*的(green1.png和pink.png)的*的坐标从JSON越来越。

  VAR dataJSON =数据|| [];
VAR dataJSON2 =数据2 || [];
 

3)所以,在我能够平移该我是 DRAW1(scaleValue)绘制完整的绘制。

4)当我点击green.png和pink.png然后他们各自的提示是能够查看在 tooltipFunc 函数来完成。

5)我想要做的是,当点击green.png / pink.png并拖动它,我应该能够拖动这些图像不仅没有SVG文件。如果我点击SVG文件,并将其拖动再正常平移应该是工作在默认情况下。

谁能请帮助?

其它参考我的问题:这个话题提的内容下面,我得到这个计算器上的链接。有了这个帮助谁能帮助我与我的项目要求的问题?

以下是我的源$ C ​​$ C:

JSON数据:

 数据= [
        {ID:[第一],
            ×:[195],
            Y:150],
            tooltiptxt:[地区1]

        },
        {
            ID:第二个],
            ×:[255],
            Y:180],
            tooltiptxt:区域2]
        },
        {
            ID:第三],
            ×:[200],
            Y:240],
            tooltiptxt:区域3]
        }

    ]。

数据2 = [
        {ID:first2],
            ×:[225],
            Y:150],
            tooltiptxt:区域21]

        },
        {
            ID:秒2]
            ×:[275],
            Y:180],
            tooltiptxt:区域22]
        },
        {
            ID:third3],
            ×:[300],
            Y:240],
            tooltiptxt:区域23]
        }

    ]。


Javascript的code:

VAR dataJSON =数据|| [];
VAR dataJSON2 =数据2 || [];
在window.onload =功能(){
    VAR帆布=的document.getElementById(myCanvas);
    VAR上下文= canvas.getContext(2D);
    VAR提示=空,
            定时器;

    // SVG文件和PNG文件收集在文件中。
    var中的文件= [/static/images/awesome_tiger.svg,/static/images/green1.png,/static/images/pink.png],
    图像= [],
    numOfFiles = files.length,
    数= numOfFiles;

    ///功能加载所有图像一气呵成
    功能loadImages(){
        ///通过文件名称的数组
        对于(VAR I = 0; I< numOfFiles;我++){
            ///创建一个图像元素
            VAR IMG = document.createElement方法('IMG');
            ///使用普通装载机,因为我们需要计算文件
            img.onload = imageLoaded;

            //img.onerror = ...处理错误
            img.src =文件[I]
            ///推图像投影到阵列中的顺序相同的文件名
            images.push(IMG);

        }
    }
    loadImages();
    功能imageLoaded(五){
        ///每一个成功的负荷,我们倒计时
        计数 - ;
        如果(计数=== 1)
        开始(); //启动没事的时候多到数不清
    }
    函数的start(){
        context.drawSvg(文件[0],0,0,400 * scaleValue,400 * scaleValue);

       对于(VAR I = 0,POS机,POS = dataJSON [我];我++){
           ///我们知道阿尔法球有指数1我们使用这里的图像
           context.drawImage(图像[1],pos.x,pos.y,20 / scaleValue,20 / scaleValue);
       }
        对于(VAR I = 0,POS机,POS = dataJSON2 [我];我++){
           context.drawImage(图像[2],pos.x,pos.y,20 / scaleValue,20 / scaleValue);
       }
    }
    //绘制SVG文件与drawSvg和图像的drawImage(dataJSON和dataJSON2都JSON通过与将获得的X的Y坐标为那些图像来绘制)

    功能DRAW1(scaleValue){
        context.save();
        context.setTransform(1,0,0,1,0,0)
        context.globalAlpha = 0.5;
        context.clearRect(0,0,canvas.width,canvas.height);
        context.restore();
        context.save();
        context.drawSvg(文件[0],0,0,400 * scaleValue,400 * scaleValue)
        context.scale(scaleValue,scaleValue);
        对于(VAR I = 0,POS机,POS = dataJSON [我];我++){
               ///我们知道阿尔法球有指数1我们使用这里的图像
               context.drawImage(图像[1],pos.x,pos.y,20 / scaleValue,20 / scaleValue);
           }
        对于(VAR I = 0,POS机,POS = dataJSON2 [我];我++){
               ///我们知道阿尔法球有指数1我们使用这里的图像
               context.drawImage(图像[2],pos.x,pos.y,20 / scaleValue,20 / scaleValue);
           }
        context.restore();
    };

// code为放大和缩小
    变种scaleValue = 1;
    VAR scaleMultiplier = 0.8;
    DRAW1(scaleValue);
    变种startDragOffset = {};
    VAR MOUSEDOWN = FALSE;
    //添加按钮事件监听器
    的document.getElementById(加)。的addEventListener(点击,函数(){
        scaleValue / = scaleMultiplier;
        DRAW1(scaleValue);
    }, 假);
     的document.getElementById(减)。的addEventListener(点击,函数(){
        scaleValue * = scaleMultiplier;
        DRAW1(scaleValue);
    }, 假);
    的document.getElementById(original_size)。的addEventListener(点击,函数(){
        scaleValue = 1;
        DRAW1(scaleValue);
    }, 假);

    // $ C $下平移画布

    VAR isDown = FALSE;
    变种startCoords = [];
    VAR transX,transY;
    变种最后= [0,0]。

    canvas.onmousedown =功能(E){
        clearTooltip();
        isDown = TRUE;
        startCoords = [
            e.offsetX  - 最后的[0],
            e.offsetY  - 最后的[1]
       ]。
    };

    canvas.onmouseup =功能(E){
        isDown = FALSE;
        最后= [
            e.offsetX  -  startCoords [0],//设置最后的坐标
            e.offsetY  -  startCoords [1]
        ]。
    };

    canvas.onmousemove =功能(E){
            VAR X = e.offsetX;
            变种Y = e.offsetY;

            transX = parseInt函数(parseInt函数(X) -  parseInt函数(startCoords [0]));
            transY = parseInt函数(parseInt函数(Y) -  parseInt函数(startCoords [1]));

            如果回报(isDown!);
            context.setTransform(1,0,0,1,transX,transY);
            DRAW1(scaleValue);
    }


    canvas.addEventListener('点击',功能(五){
        VAR X = e.offsetX;
        变种Y = e.offsetY;

        transX = parseInt函数(parseInt函数(X) -  parseInt函数(startCoords [0]));
        transY = parseInt函数(parseInt函数(Y) -  parseInt函数(startCoords [1]));

        tooltipFunc(即transX,transY);

    }, 假);


    // tooptip功能
    功能tooltipFunc(即transX,transY){
        //document.body.style.cursor =默认;
        VAR translationX,translationY;
        变种R = canvas.getBoundingClientRect(),
                    X = e.clientX  -  r.left,
                    Y = e.clientY  -  r.top,
                    I = 0,
                    R,
                    inTooltip = FALSE;

        如果((typeof运算startCoords [0] =='不确定'|| startCoords [0] ===男)及及(typeof运算startCoords [1] ===未定义|| startCoords [1] == =男)){
            的console.log(如果);
                对于(; R = dataJSON [我];我++){
                    如果(X GT; = parseInt函数(dataJSON [I] .X [0] * scaleValue)+ parseInt函数(scaleValue)及&安培; X  - 其中= parseInt函数(dataJSON [I] .X [0] * scaleValue)+ parseInt函数( 20 / scaleValue)及&安培y与其所连接; = parseInt函数(dataJSON [I] .Y [0] * scaleValue)及&安培; Y&其中; = parseInt函数(dataJSON [I] .Y [0] * scaleValue)+ parseInt函数(20 / scaleValue)){
                        // clearTooltip();
                        showTooltip(e.clientX,e.clientY,我);
                        inTooltip = TRUE;
                    }
                }
        }
        其他 {
            的console.log(其他);
        对于(VAR I = 0; R = dataJSON [我];我++){
                    的console.log('否则为');
                    如果(X> = parseInt函数(parseInt函数(dataJSON [I] .X [0] * scaleValue)+ parseInt函数(scaleValue)+ parseInt函数(transX))及和放大器,X< = parseInt函数(parseInt函数(dataJSON [1]。 ×〔0〕* scaleValue)+ parseInt函数(scaleValue)+ parseInt函数(transX)+ parseInt函数(20))及&安培y与其所连接; = parseInt函数(parseInt函数(dataJSON [I] .Y [0] * scaleValue)+ parseInt函数( scaleValue)+ parseInt函数(transY))及和放大器; Y< = parseInt函数(parseInt函数(dataJSON [I] .Y [0] * scaleValue)+ parseInt函数(scaleValue)+ parseInt函数(transY)+ parseInt函数(20))){
                        clearTooltip();
                        showTooltip(e.clientX,e.clientY,我);
                        inTooltip = TRUE;
                    }
            }
            对于(VAR I = 0; R = dataJSON2 [我];我++){
                    的console.log('否则为');
                    如果(X> = parseInt函数(parseInt函数(dataJSON2 [I] .X [0] * scaleValue)+ parseInt函数(scaleValue)+ parseInt函数(transX))及和放大器,X< = parseInt函数(parseInt函数(dataJSON2 [1]。 ×〔0〕* scaleValue)+ parseInt函数(scaleValue)+ parseInt函数(transX)+ parseInt函数(20))及&安培y与其所连接; = parseInt函数(parseInt函数(dataJSON2 [I] .Y [0] * scaleValue)+ parseInt函数( scaleValue)+ parseInt函数(transY))及和放大器; Y< = parseInt函数(parseInt函数(dataJSON2 [I] .Y [0] * scaleValue)+ parseInt函数(scaleValue)+ parseInt函数(transY)+ parseInt函数(20))){
                        clearTooltip();
                        showTooltip2(e.clientX,e.clientY,我);
                        inTooltip = TRUE;
                    }
            }
        }
    }


}
 

别人对我的问题参考:

 < HTML>
< HEAD>
<冠军>测试页< /标题>
<脚本类型=文/ JavaScript的SRC =jquery.js和>< / SCRIPT>
< /头>
<身体GT;

<帆布ID =CWIDTH =500HEIGHT =500>< /帆布>

<脚本类型=文/ JavaScript的>
VAR帆布= $(#C);
变种C =帆布[0] .getContext(2D);

// VAR路径=htt​​p://wonderfl.net/images/icon/e/ec/ec3c/ec3c37ba9594a7b47f1126b2561efd35df2251bfm;
VAR路径=blue.jpg;
VAR PATH2 =purple.jpg;
变种image1的=新拖动图像(路径,200,100);
VAR IMAGE2 =新的拖动图像(PATH2,300,100);

VAR循环=的setInterval(函数(){

    c.fillStyle =灰色;
    c.fillRect(0,0,500,500);

    image1.update();
    image2.update();
},30);

变种mouseX = 0,
    mouseY的= 0;
VAR鼠标pressed = FALSE;
VAR拖动= FALSE;
canvas.mousemove(功能(E){
    mouseX = e.offsetX;
    mouseY的= e.offsetY;
})

$(文件).mousedown(函数(){
    鼠标pressed = TRUE;
})。鼠标松开(函数(){
    鼠标pressed = FALSE;
    拖动= FALSE;
});

功能拖动图像(源中,x,y)的{
    VAR的=这一点;
    变种运行startx = 0,
        startY = 0;
    VAR拖动= FALSE;

    this.x = X;
    this.y = Y;
    VAR IMG =新的图像();
    img.src = SRC;
    this.update =功能(){
        如果(鼠标pressed){

                VAR左= that.x;
                无功权= that.x + img.width;
                VAR顶部= that.y;
                VAR底部= that.y + img.height;
                如果(!拖){
                    STARTX = mouseX  -  that.x;
                    startY = mouseY的 -  that.y;
                }
                如果(mouseX<右放;&安培; mouseX>左&功放;&安培; mouseY的<底部&安培;&安培; mouseY的>顶部){
                    如果(!拖){
            拖着= TRUE;
                        阻力= TRUE;
                    }

                }

        } 其他 {

            拖动= FALSE;
        }
        如果(拖){
            that.x = mouseX  -  STARTX;
            that.y = mouseY的 -  startY;
        }
        c.drawImage(IMG,that.x,that.y);
    }
}
< / SCRIPT>
< /身体GT;
< / HTML>
 

解决方案

希望我明白你的问题...!

下面是如何既平移画布并拖动对象在画布上

这说明任何拖动或平移前的画布:

注意绿色矩形是在老虎的左眼。

这说明了画布后的绿色矩形一直拖到右眼:

这说明在画布平移后。

无论是老虎和所有rects将同时平移。

最重要code是在鼠标按下鼠标移动和事件处理程序

在鼠标按下:

如果鼠标在1 +彩色图像,然后将图像(S)。 如果鼠标不超过任何彩色图像,然后平移画布。

下面是鼠标按下code:

 函数handleMouseDown(五){

  //获取鼠标坐标

  mouseX = parseInt函数(e.clientX-offsetX);
  mouseY的= parseInt函数(e.clientY-offsetY);

  //设置开始拖动位置
  //这是需要在鼠标移动来确定有多远,我们都拖
  lastX = mouseX;
  lastY = mouseY的;

  //测试,如果我们在任何图像
  如果//是的,把这些图像(S)的称为阵列拖曳
  拖动= imagesHitTests(mouseX,mouseY的);

  //设置拖动标记
  isDown = TRUE;

}
 

在鼠标移动:

在确定我们是否拖动或平移。 如果在拖动[]数组不为空,我们就拖。 如果在拖动[]数组是空的,我们就平移。 在拖动时,由我们拖着量改变每个拖累图像的XY。 在当前平移,改变老虎位被我们拖量。

下面是鼠标移动code:

 函数handleMouseMove(五){

  //如果我们不能拖,退出
  如果(isDown!){返回;}

  //获取鼠标坐标
  mouseX = parseInt函数(e.clientX-offsetX);
  mouseY的= parseInt函数(e.clientY-offsetY);

  //计算多少鼠标已经移动,因为我们这里是最后一个
  变种DX = mouseX-lastX;
  变种DY = mouseY的-lastY;

  //设置lastXY下一次我们在这里
  lastX = mouseX;
  lastY = mouseY的;

  //处理一拖再拖/锅
  如果(dragging.length大于0){
      //我们拖动图片
      //将所有受影响的图像多少鼠标已经移动
      对于(VAR I = 0; I< dragging.length;我++){
          IMG =图像​​[拖动[I]];
          img.x + = DX;
          img.y + = DY;
      }
  }其他{
      //我们平移虎
      //设置panXY多少鼠标已经移动
      panX + = DX;
      PANY + = DY;
  }
  绘制();
}
 

这里是code,以确定哪种颜色,图像下鼠标 - 而且将拖累

鼠标下的任何彩色图象将被添加到所谓的拖的数组。

这拖动[]数组用于鼠标移动拖动相应的彩色图像(S)。

  //创建任何打有色图像阵列
  功能imagesHitTests(X,Y){
      //调整摇摄
      X- = panX;
      Y- = PANY;
      //创建VAR持有任何命中
      变种命中= [];
      //点​​击测试每个图像
      //增加命中命中[]
      对于(VAR I = 0; I< images.length;我++){
          VAR IMG =图像​​[我]
          如果(X GT; img.x&安培;&安培; X  - 其中; img.x + img.width&安培;&安培y与其所连接; img.y&安培;&安培; Y&所述; img.y + img.height){
              hits.push(ⅰ);
          }
      }
      返程(点击);
  }
 

下面是完整的code和一个小提琴: http://jsfiddle.net/m1erickson/pbRq2/

 <!DOCTYPE HTML>
< HTML>
< HEAD>
<链接相对=样式类型=文本/ CSS媒体=所有的href =CSS / reset.css/> <! - 重置CSS  - >
<脚本类型=文/ JavaScript的SRC =HTTP://$c$c.jquery.com/jquery.min.js>< / SCRIPT>

<风格>
    身体{背景色:象牙色;填充:20像素;}
    #canvas {边界:1px的纯红色;}
< /风格>

<脚本>
$(函数(){

    VAR帆布=的document.getElementById(帆布);
    VAR CTX = canvas.getContext(2D);
    ctx.strokeStyle =红色;
    ctx.lineWidth = 5;

    。VAR canvasOffset = $(#帆布)的偏移量();
    VAR offsetX = canvasOffset.left;
    VAR offsetY = canvasOffset.top;

    变种lastX = 0;
    变种lastY = 0;
    变种panX = 0;
    变种PANY = 0;
    VAR拖动= [];
    VAR isDown = FALSE;


    //创建绿色和放大器;粉红色的图像(我们只使用rects而不是图像)
    变种图像= [];
    images.push({X:200,Y:150,宽度:25,高度:25,颜色:绿色});
    images.push({X:80 Y:235,宽度:25,高度:25,颜色:粉红色});

    //将虎图像
    VAR老虎=新的图像();
    tiger.onload =功能(){
        绘制();
    }
    tiger.src =htt​​ps://dl.dropboxusercontent.com/u/139992952/stackoverflow/tiger.png;


    功能平局(){

        ctx.clearRect(0,0,canvas.width,canvas.height);

        //画虎
        ctx.globalAlpha = 0.25;
        ctx.drawImage(虎,panX,PANY,tiger.width,tiger.height);

        //绘制彩色图像
        ctx.globalAlpha = 1.00;
        对于(VAR I = 0; I< images.length;我++){
            VAR IMG =图像​​[我]
            ctx.beginPath();
            ctx.rect(img.x + panX,img.y + PANY,img.width,img.height);
            ctx.fillStyle = img.color;
            ctx.fill();
            ctx.stroke();
        }
    }

    //创建任何打有色图像阵列
    功能imagesHitTests(X,Y){
        //调整摇摄
        X- = panX;
        Y- = PANY;
        //创建VAR持有任何命中
        变种命中= [];
        //点​​击测试每个图像
        //增加命中命中[]
        对于(VAR I = 0; I< images.length;我++){
            VAR IMG =图像​​[我]
            如果(X GT; img.x&安培;&安培; X  - 其中; img.x + img.width&安培;&安培y与其所连接; img.y&安培;&安培; Y&所述; img.y + img.height){
                hits.push(ⅰ);
            }
        }
        返程(点击);
    }


    功能handleMouseDown(五){

      //获取鼠标坐标
      mouseX = parseInt函数(e.clientX-offsetX);
      mouseY的= parseInt函数(e.clientY-offsetY);
      //设置开始拖动位置
      lastX = mouseX;
      lastY = mouseY的;
      //测试,如果我们在任何图像
      拖动= imagesHitTests(mouseX,mouseY的);
      //设置拖动标记
      isDown = TRUE;
    }

    功能handleMouseUp(五){
      //清除拖动标志
      isDown = FALSE;
    }


    功能handleMouseMove(五){

      //如果我们不能拖,退出
      如果(isDown!){返回;}

      //获取鼠标坐标
      mouseX = parseInt函数(e.clientX-offsetX);
      mouseY的= parseInt函数(e.clientY-offsetY);

      //计算多少鼠标已经移动,因为我们这里是最后一个
      变种DX = mouseX-lastX;
      变种DY = mouseY的-lastY;

      //设置lastXY下一次我们在这里
      lastX = mouseX;
      lastY = mouseY的;

      //处理一拖再拖/锅
      如果(dragging.length大于0){
          //我们拖动图片
          //将所有受影响的图像多少鼠标已经移动
          对于(VAR I = 0; I< dragging.length;我++){
              IMG =图像​​[拖动[I]];
              img.x + = DX;
              img.y + = DY;
          }
      }其他{
          //我们平移虎
          //设置panXY多少鼠标已经移动
          panX + = DX;
          PANY + = DY;
      }
      绘制();
    }

    //使用jQuery来处理鼠标事件
    $(#帆布)的mousedown(函数(E){handleMouseDown(E);});
    $(#帆布)鼠标移动(功能(E){handleMouseMove(E);});
    $(#帆布)的MouseUp(函数(E){handleMouseUp(E);});

}); //结束$(函数(){});
< / SCRIPT>

< /头>

<身体GT;
    <帆布ID =画布宽度= 300高度= 300>< /帆布>
< /身体GT;
< / HTML>
 

1) On Canvas I am drawing SVG file (awesome_tiger.svg) with drawSvg (canvg).

2) On that SVG file I am plotting images*(green1.png and pink.png)* whose co-ordinates are getting from JSON.

var dataJSON = data || [];
var dataJSON2 = data2 || [];

3) So on I am able to pan complete drawing which I am drawing with draw1(scaleValue).

4) When I click on green.png and pink.png then their respective tooltip is able to view that is done in tooltipFunc function.

5) What I want to do is, when click on green.png / pink.png and drag it I should be able to drag those images only not the Svg file. If I click on svg file and drag it then normal pan should work which is working by default.

Can Anyone please help?

"Others reference for my problem:" Content of this topic mention below, I got this on stackoverflow link. With the help of this can anyone help me with my project requirement problem?

Following is my source code :

JSON Data :

data = [  
        {   "id" :["first"],        
            "x": ["195"],
            "y": ["150"],
            "tooltiptxt": ["Region 1"]

        },  
        {
            "id" :["second"],
            "x": ["255"],
            "y": ["180"],
            "tooltiptxt": ["Region 2"]      
        },
        {
            "id" :["third"],
            "x": ["200"],
            "y": ["240"],
            "tooltiptxt": ["Region 3"]      
        }       

    ];

data2 = [  
        {   "id" :["first2"],       
            "x": ["225"],
            "y": ["150"],
            "tooltiptxt": ["Region 21"]

        },  
        {
            "id" :["second2"],
            "x": ["275"],
            "y": ["180"],
            "tooltiptxt": ["Region 22"]     
        },
        {
            "id" :["third3"],
            "x": ["300"],
            "y": ["240"],
            "tooltiptxt": ["Region 23"]     
        }       

    ];


Javascript Code:        

var dataJSON = data || [];
var dataJSON2 = data2 || [];
window.onload = function(){ 
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext('2d');      
    var tooltip = null,
            timer;

    //svg file and png files are collected in files.
    var files = ["/static/images/awesome_tiger.svg", "/static/images/green1.png", "/static/images/pink.png"],
    images = [],
    numOfFiles = files.length,
    count = numOfFiles;

    /// function to load all images in one go
    function loadImages() {
        /// go through array of file names
        for(var i = 0; i < numOfFiles; i++) {
            /// create an image element
            var img = document.createElement('img');
            /// use common loader as we need to count files
            img.onload = imageLoaded;

            //img.onerror = ... handle errors
            img.src = files[i];                 
            /// push image onto array in the same order as file names
            images.push(img);

        }
    }
    loadImages();
    function imageLoaded(e) {
        /// for each successful load we count down
        count--;            
        if (count === 1)            
        start(); //start when nothing more to count
    }
    function start() {      
        context.drawSvg(files[0], 0, 0, 400*scaleValue, 400*scaleValue);    

       for(var i = 0, pos; pos = dataJSON[i]; i++) {         
           /// as we know the alpha ball has index 1 we use that here for images
           context.drawImage(images[1], pos.x, pos.y, 20/scaleValue, 20/scaleValue);
       }
        for(var i = 0, pos; pos = dataJSON2[i]; i++) {             
           context.drawImage(images[2], pos.x, pos.y, 20/scaleValue, 20/scaleValue);
       }
    }
    //Drawing the svg file with drawSvg and images with drawImage(dataJSON and dataJSON2 are JSON through with will get the x an y co-ordinates for those images to draw)

    function draw1(scaleValue){             
        context.save();     
        context.setTransform(1,0,0,1,0,0)   
        context.globalAlpha = 0.5;                      
        context.clearRect(0, 0, canvas.width, canvas.height);   
        context.restore();          
        context.save(); 
        context.drawSvg(files[0], 0, 0, 400*scaleValue, 400*scaleValue)
        context.scale(scaleValue, scaleValue);
        for(var i = 0, pos; pos = dataJSON[i]; i++) {
               /// as we know the alpha ball has index 1 we use that here for images
               context.drawImage(images[1], pos.x, pos.y, 20/scaleValue, 20/scaleValue);
           }    
        for(var i = 0, pos; pos = dataJSON2[i]; i++) {
               /// as we know the alpha ball has index 1 we use that here for images
               context.drawImage(images[2], pos.x, pos.y, 20/scaleValue, 20/scaleValue);
           }
        context.restore();
    }; 

//Code for Zoom In and Zoom Out
    var scaleValue = 1;
    var scaleMultiplier = 0.8;
    draw1(scaleValue);
    var startDragOffset = {};
    var mouseDown = false;          
    // add button event listeners
    document.getElementById("plus").addEventListener("click", function(){           
        scaleValue /= scaleMultiplier;                          
        draw1(scaleValue);              
    }, false);
     document.getElementById("minus").addEventListener("click", function(){
        scaleValue *= scaleMultiplier;              
        draw1(scaleValue);      
    }, false);
    document.getElementById("original_size").addEventListener("click", function(){
        scaleValue = 1;                 
        draw1(scaleValue);  
    }, false);

    //Code for panning on canvas

    var isDown = false;
    var startCoords = [];
    var transX, transY;
    var last = [0, 0];

    canvas.onmousedown = function(e){
        clearTooltip();
        isDown = true;          
        startCoords = [
            e.offsetX - last[0],
            e.offsetY - last[1]
       ];
    };

    canvas.onmouseup  = function(e){        
        isDown = false;         
        last = [
            e.offsetX - startCoords[0], // set last coordinates
            e.offsetY - startCoords[1]
        ];
    };

    canvas.onmousemove = function(e){   
            var x = e.offsetX;              
            var y = e.offsetY;

            transX = parseInt(parseInt(x) - parseInt(startCoords[0]));
            transY = parseInt(parseInt(y) - parseInt(startCoords[1]));

            if(!isDown) return; 
            context.setTransform(1, 0, 0, 1, transX, transY);                                   
            draw1(scaleValue);  
    }


    canvas.addEventListener('click', function(e) {          
        var x = e.offsetX;              
        var y = e.offsetY;

        transX = parseInt(parseInt(x) - parseInt(startCoords[0]));
        transY = parseInt(parseInt(y) - parseInt(startCoords[1]));

        tooltipFunc(e, transX, transY); 

    }, false);


    //tooptip function
    function tooltipFunc(e, transX, transY){
        //document.body.style.cursor = 'default';
        var translationX, translationY;
        var r = canvas.getBoundingClientRect(),
                    x = e.clientX - r.left,
                    y = e.clientY - r.top,
                    i = 0,
                    r,
                    inTooltip = false;

        if((typeof startCoords[0] == 'undefined' || startCoords[0] === 'NaN') && (typeof startCoords[1] === 'undefined' || startCoords[1] === 'NaN')){  
            console.log('if');
                for (; r = dataJSON[i]; i++) {              
                    if (x >= parseInt(dataJSON[i].x[0] * scaleValue) + parseInt(scaleValue) && x <= parseInt(dataJSON[i].x[0] * scaleValue) + parseInt(20/scaleValue) && y >= parseInt(dataJSON[i].y[0] * scaleValue) && y <= parseInt(dataJSON[i].y[0] * scaleValue) + parseInt(20/scaleValue)) {
                        //clearTooltip();
                        showTooltip(e.clientX, e.clientY, i);
                        inTooltip = true;
                    }
                }
        }
        else {
            console.log('else');                                    
        for (var i = 0; r = dataJSON[i]; i++) { 
                    console.log('else for');                    
                    if(x >= parseInt(parseInt(dataJSON[i].x[0] * scaleValue) + parseInt(scaleValue) + parseInt(transX)) && x <= parseInt(parseInt(dataJSON[i].x[0] * scaleValue) + parseInt(scaleValue) + parseInt(transX) + parseInt(20)) && y >= parseInt(parseInt(dataJSON[i].y[0] * scaleValue) + parseInt(scaleValue) + parseInt(transY)) && y <= parseInt(parseInt(dataJSON[i].y[0] * scaleValue) + parseInt(scaleValue) + parseInt(transY) + parseInt(20))) {                        
                        clearTooltip();                                             
                        showTooltip(e.clientX, e.clientY, i);
                        inTooltip = true;
                    }
            }
            for (var i = 0; r = dataJSON2[i]; i++) {    
                    console.log('else for');                    
                    if(x >= parseInt(parseInt(dataJSON2[i].x[0] * scaleValue) + parseInt(scaleValue) + parseInt(transX)) && x <= parseInt(parseInt(dataJSON2[i].x[0] * scaleValue) + parseInt(scaleValue) + parseInt(transX) + parseInt(20)) && y >= parseInt(parseInt(dataJSON2[i].y[0] * scaleValue) + parseInt(scaleValue) + parseInt(transY)) && y <= parseInt(parseInt(dataJSON2[i].y[0] * scaleValue) + parseInt(scaleValue) + parseInt(transY) + parseInt(20))) {                        
                        clearTooltip();                         
                        showTooltip2(e.clientX, e.clientY, i);
                        inTooltip = true;
                    }
            }
        }
    }


}           

Others reference for my problem:

<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 = "https://p.xsw88.cn/allimgs/daicuo/20230907/5527.png.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>

解决方案

Hopefully I understand your question...!

Here’s how to both pan a canvas and drag objects on the canvas

This illustrates the canvas before any dragging or panning:

Notice the green rect is over the tiger's left eye.

This illustrates the canvas after the green rect has been dragged to the right eye:

This illustrates the canvas after panning.

Both the tiger and all rects will pan simultaneously.

Most of the important code is in the mousedown and mousemove event handlers

On mousedown:

If the mouse is over 1+ colored-images, then drag the image(s). If the mouse is not over any colored-images, then pan the canvas.

Here is the mousedown code:

function handleMouseDown(e){

  // get mouse coordinates

  mouseX=parseInt(e.clientX-offsetX);
  mouseY=parseInt(e.clientY-offsetY);

  // set the starting drag position 
  // this is needed in mousemove to determine how far we have dragged
  lastX=mouseX;
  lastY=mouseY;

  // test if we're over any of the images
  // if yes, put those image(s) in an array called dragging
  dragging=imagesHitTests(mouseX,mouseY);

  // set the dragging flag
  isDown=true;

}

On mousemove:

Determine if we’re dragging or panning. If the dragging[] array is not empty, we’re dragging. If the dragging[] array is empty, we’re panning. When dragging, change each dragged image’s XY by the amount we have dragged. When panning, change the tiger position by the amount we have dragged.

Here is the mousemove code:

function handleMouseMove(e){

  // if we're not dragging, exit
  if(!isDown){return;}

  //get mouse coordinates
  mouseX=parseInt(e.clientX-offsetX);
  mouseY=parseInt(e.clientY-offsetY);

  // calc how much the mouse has moved since we were last here
  var dx=mouseX-lastX;
  var dy=mouseY-lastY;

  // set the lastXY for next time we're here
  lastX=mouseX;
  lastY=mouseY;

  // handle drags/pans
  if(dragging.length>0){
      // we're dragging images
      // move all affected images by how much the mouse has moved
      for(var i=0;i<dragging.length;i++){
          img=images[dragging[i]];
          img.x+=dx;
          img.y+=dy;
      }
  }else{
      // we're panning the tiger
      // set the panXY by how much the mouse has moved
      panX+=dx;
      panY+=dy;
  }
  draw();
}

And here is code to determine which color-images are under the mouse--and will be dragged.

Any color-image under the mouse is added to an array called "dragging".

This dragging[] array is used in mousemove to drag the appropriate color-image(s).

  // create an array of any "hit" colored-images
  function imagesHitTests(x,y){
      // adjust for panning
      x-=panX;
      y-=panY;
      // create var to hold any hits
      var hits=[];
      // hit-test each image
      // add hits to hits[]
      for(var i=0;i<images.length;i++){
          var img=images[i];
          if(x>img.x && x<img.x+img.width && y>img.y && y<img.y+img.height){
              hits.push(i);
          }
      }
      return(hits);
  }

Here is complete code and a Fiddle: http://jsfiddle.net/m1erickson/pbRq2/

<!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; padding:20px;}
    #canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    ctx.strokeStyle="red";
    ctx.lineWidth=5;

    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;

    var lastX=0;
    var lastY=0;
    var panX=0;
    var panY=0;
    var dragging=[];
    var isDown=false;


    // create green & pink "images" (we just use rects instead of images)
    var images=[];
    images.push({x:200,y:150,width:25,height:25,color:"green"});
    images.push({x:80,y:235,width:25,height:25,color:"pink"});

    // load the tiger image
    var tiger=new Image();
    tiger.onload=function(){
        draw();
    }
    tiger.src="https://p.xsw88.cn/allimgs/daicuo/20230907/5528.png";


    function draw(){

        ctx.clearRect(0,0,canvas.width,canvas.height);

        // draw tiger
        ctx.globalAlpha=0.25;
        ctx.drawImage(tiger,panX,panY,tiger.width,tiger.height);

        // draw color images
        ctx.globalAlpha=1.00;
        for(var i=0;i<images.length;i++){
            var img=images[i];
            ctx.beginPath();
            ctx.rect(img.x+panX,img.y+panY,img.width,img.height);
            ctx.fillStyle=img.color;
            ctx.fill();
            ctx.stroke();
        }
    }

    // create an array of any "hit" colored-images
    function imagesHitTests(x,y){
        // adjust for panning
        x-=panX;
        y-=panY;
        // create var to hold any hits
        var hits=[];
        // hit-test each image
        // add hits to hits[]
        for(var i=0;i<images.length;i++){
            var img=images[i];
            if(x>img.x && x<img.x+img.width && y>img.y && y<img.y+img.height){
                hits.push(i);
            }
        }
        return(hits);
    }


    function handleMouseDown(e){

      // get mouse coordinates
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      // set the starting drag position
      lastX=mouseX;
      lastY=mouseY;
      // test if we're over any of the images
      dragging=imagesHitTests(mouseX,mouseY);
      // set the dragging flag
      isDown=true;
    }

    function handleMouseUp(e){
      // clear the dragging flag
      isDown=false;
    }


    function handleMouseMove(e){

      // if we're not dragging, exit
      if(!isDown){return;}

      //get mouse coordinates
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);

      // calc how much the mouse has moved since we were last here
      var dx=mouseX-lastX;
      var dy=mouseY-lastY;

      // set the lastXY for next time we're here
      lastX=mouseX;
      lastY=mouseY;

      // handle drags/pans
      if(dragging.length>0){
          // we're dragging images
          // move all affected images by how much the mouse has moved
          for(var i=0;i<dragging.length;i++){
              img=images[dragging[i]];
              img.x+=dx;
              img.y+=dy;
          }
      }else{
          // we're panning the tiger
          // set the panXY by how much the mouse has moved
          panX+=dx;
          panY+=dy;
      }
      draw();
    }

    // use jQuery to handle mouse events
    $("#canvas").mousedown(function(e){handleMouseDown(e);});
    $("#canvas").mousemove(function(e){handleMouseMove(e);});
    $("#canvas").mouseup(function(e){handleMouseUp(e);});

}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

阅读全文

相关推荐

最新文章