简体   繁体   中英

Vue.js Canvas element follow mouse

I made color picker in Vue, basing on HTML canvas and I want to add transparent circle showing active color on color picker, that will follow mouse on canvas.

I tried to change this code to my usage: Make "ball" follow mouse on canvas , and this is what I got:

在此处输入图像描述

As You can see, my circle is following mouse position, but leaves trace. Mouse position is updated dynamically to state and XY data in my function is recived from state.

loop(X, Y) {
   this.moveCursor(X, Y)
   requestAnimationFrame(this.loop)
},
moveCursor(X, Y) {
   const colorPickerBlock = document.getElementById('color_picker-block');
   const blockCtx = colorPickerBlock.getContext('2d');

   blockCtx.beginPath();
   blockCtx.arc(X, Y, 6, 0, 2 * Math.PI);
   blockCtx.fillStyle = "transparent";
   blockCtx.fill();
   blockCtx.lineWidth = 1;
   blockCtx.strokeStyle = "white";
   blockCtx.stroke();                
   },
mousedown(event) {
   this.isDragActive = true;
},
mousemove(event) {
  if (this.isDragActive) {
        this.changeLocalColor(event)
        this.loop(this.getActiveElementColor.X, this.getActiveElementColor.Y)
 }
},
mouseup(event) {
   if (this.isDragActive) {
        this.isDragActive = false;
   }
}

You have to reset state of canvas to initial before moveCursor. I dont know if canvas is only used to show circle or also to show color pallete. If canvas shows only circles then you need to

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

otherwise you need to also draw whole palette again.

resetPalette ()
{
    this.context.clearRect(0, 0, canvas.width, canvas.height);
    // steps to init palette from the start
}

I would also suggest to assign context as variable rather than getting it each time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM