0

I have a canvas that currently draws an image and is draggable. The only problem is that the image moves when you drag anywhere on the canvas and not specifically when you drag the image. Looking to make it so that the image only drags when you drag over it. Any help is appreciated.

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));
    }
});
user401708
  • 23
  • 1
  • 6
  • It's a lot easier to show the image in a separate canvas, and drag that canvas. If you need to store the canvas with the image, add the image into its current position just before saving. – Teemu Oct 08 '18 at 14:31
  • put a canvas in a canvas? – user401708 Oct 08 '18 at 14:33
  • No, put the image on a separate canvas ... – Teemu Oct 08 '18 at 14:34
  • it already is in a canvas – user401708 Oct 08 '18 at 14:35
  • No it isn't, it is in the internet, you're drawing it into a particular canvas, change that to another canvas. – Teemu Oct 08 '18 at 14:37
  • 1
    I don't have experience with Polymer, but it's as simple as storing the coordinates of the image and then checking on mousedown whether or not the mouse is within the boundaries of that image. – zfrisch Oct 08 '18 at 14:49

0 Answers0