简体   繁体   中英

JCanvas: Erasing Canvas doesn't erase draggable elements

I wanted to enhance the drawing application I built with JS by allowing the user to draw various shapes. I want to make it convenient for the users by allowing them to drag these shapes around. So I used jCanvas, since it offers a simple way of dragging a shape:

$("#can").drawRect({
   draggable: true,
   fillStyle: "#000",
   width: 100, height: 100,
   x: 100,
   y: 100,
});

The problem is, I need a function to erase it again. So I made this script:

<script>
   $("#can").drawRect({
      draggable: true,
      fillStyle: "#000",
      width: 100, height: 100,
      x: 100,
      y: 100,
   });

   $("#erase").click(function () {
      $("#can").clearCanvas();
   });
</script>
<canvas id="can" width="200px" height="150px"></canvas>
<button id="erase">Clear Canvas</button>

This doesn't work though. When I erase, it clears out everything at first, but when I try to draw on the Canvas, the shape appears again.

I checked the code of jCanvas, and it appears that it just draws tons of rectangles when dragged, and clears them away to create the illusion of the shape being dragged. But when this happens, the cleared Canvas retreats itself and the shape is visible again.

Is there a way to clear the shape away for eternity? Or do I have to reload the page for that to work?

Thanks in advance

You are not using Layer explicitly, but when you set drag property the Canvas create a layer:

Layers can be made draggable using the draggable property.

https://projects.calebevans.me/jcanvas/docs/draggableLayers/

So, clearCanvas is not suitable:

This method is not meant to be used if you are using the jCanvas Layer API, because the API handles redrawing for you in many cases, and so if you try to clear the canvas. you layers will eventually be redrawn by jCanvas when it deems necessary .

You need remove the layer:

$('canvas').removeLayer(0);

or

$('canvas').removeLayers();

Look more options in Doc: https://projects.calebevans.me/jcanvas/docs/manipulateLayers/

If this help you, check my answer as correct or voteup!

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