用鼠标在画布中拖动图像

时间:2017-08-27 16:07:00

标签: javascript html5 canvas

我是html5画布的新手。我不明白为什么图像不会在鼠标附近移动,当点击图像时,图像在鼠标下移动几个像素,这是我的javacript代码

var pressed=false;

var mousex=0,mousey=0;
function pressMous(){
  pressed=true;
}
var prevX=0,prevY=0;
function movemouse(evt){
var rect = canvas.getBoundingClientRect();
  if(pressed){
     mousex=evt.clientX - rect.left;
    mousey=evt.clientY - rect.top;
    updateImagen();
  }
}
function upmouse(){
  pressed=false;
}
var ima;

var  radianes = Math.PI/180;
var image = new Image();
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
canvas.addEventListener('mousedown',pressMous,false); canvas.addEventListener('mousemove',movemouse,false); canvas.addEventListener('mouseup',upmouse,false);

paint();

/*********/
var offsetX = canvas.offsetLeft;
var offsetY = canvas.offsetTop;
/*****************/

function updateImagen() {

        ctx.save();

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

        console.log("mousex "+mousex+" mousey " +mousey);

 ctx.drawImage(image, mousex, mousey, image.width, image.height);

        ctx.restore();
    }

function paint(){
ctx.clearRect(0, 0, canvas.width, canvas.height);

    //image.src = "https://cfl.dropboxstatic.com/static/images/logo_catalog/glyph_2016-vfl3-TV2d.svg";
image.src = "https://cfl.dropboxstatic.com/static/images/index/animation-strips/static-images/work-on-slides-together-vfligazGL.png";

    image.onload = function () {
        var cxt = canvas.getContext('2d');
        cxt.drawImage(image,canvas.width / 2 - image.width / 2,canvas.height / 2 - image.height / 2);
}

}

这是我的jsfiddle,我不知道这种行为 https://jsfiddle.net/93x8209b/

0 个答案:

没有答案