简体   繁体   English

JCanvas:擦除 Canvas 不会擦除可拖动元素

[英]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.我想通过允许用户绘制各种形状来增强我用 JS 构建的绘图应用程序。 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:所以我使用了 jCanvas,因为它提供了一种简单的拖动形状的方法:

$("#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.问题是,我需要一个 function 来再次擦除它。 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.当我擦除时,它首先清除了所有内容,但是当我尝试在 Canvas 上绘图时,形状再次出现。

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.我检查了 jCanvas 的代码,它似乎只是在拖动时绘制了大量的矩形,并清除它们以创建被拖动形状的错觉。 But when this happens, the cleared Canvas retreats itself and the shape is visible again.但是当这种情况发生时,被清除的 Canvas 会自行后退,形状再次可见。

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:您没有明确使用图层,但是当您设置拖动属性时,Canvas 创建一个图层:

Layers can be made draggable using the draggable property.可以使用 draggable 属性使图层可拖动。

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

So, clearCanvas is not suitable:所以,clearCanvas 不适合:

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.如果您使用的是 jCanvas 层 API,则不应使用此方法,因为 API 在许多情况下会为您处理重绘,因此如果您尝试清除 ZFCC790C72A86190DE1B549D0DDC6F55C。 you layers will eventually be redrawn by jCanvas when it deems necessary .当它认为有必要时,你的图层最终会被 jCanvas 重绘

You need remove the layer:您需要删除图层:

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

or或者

$('canvas').removeLayers();

Look more options in Doc: https://projects.calebevans.me/jcanvas/docs/manipulateLayers/在文档中查看更多选项: https://projects.calebevans.me/jcanvas/docs/manipulateLayers/

If this help you, check my answer as correct or voteup!如果这对您有帮助,请检查我的答案是否正确或投票!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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