在画布中拖动图像-JavaScript

时间:2018-10-08 14:29:07

标签: javascript canvas drag

我有一个画布,当前正在绘制图像并且可以拖动。唯一的问题是,当您将其拖动到画布上的任意位置时,图像会移动,而不是具体地拖动图像时。力图使其仅在您拖动图像时才拖动。任何帮助表示赞赏。

Polymer({
is: 'sensor-map',

onCreateCanvas: function(){

    var canvas = this.$.myCanvas;
    var context = canvas.getContext('2d');
    var imageObj = new Image();
    var currentX = 0;
    var currentY = 0;

    var isDraggable = false;
    var imagedrawn = false;

    imageObj.onload = function() {
        context.drawImage(imageObj, 0, 0);
        currentX = canvas.width/2;
        currentY = canvas.height/2;
    };
    imageObj.src = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
    //https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png
    //https://wonderfulengineering.com/wp-content/uploads/2014/03/high-resolution-wallpapers-12.jpg

    imagedrawn = true;

    canvas.addEventListener('mousedown', function(e){
        currentX = e.pageX - this.offsetLeft;
        currentY = e.pageY - this.offsetTop;
        console.log(currentX);
        console.log(currentY);
        isDraggable = true;
    });

if (imagedrawn){
canvas.addEventListener('mousemove', function(e){
    if (isDraggable) {
        currentX = e.pageX - this.offsetLeft;
        currentY = e.pageY - this.offsetTop;
        context.fillStyle = '#e2e8ed';
        context.fillRect(0,0, canvas.width, canvas.height);
        context.drawImage(imageObj, currentX-(imageObj.width/2), currentY- 
(imageObj.height/2));
    }
});

0 个答案:

没有答案