当前位置:网站首页>Fabric. Keep the original level when JS element is selected

Fabric. Keep the original level when JS element is selected

2022-06-10 17:09:00 Director of Moral Education Division

I didn't know you were using Fabric.js Did you find it when , If there are multiple elements in a canvas , And they were stacked before , When you select the underlying element , That element will jump to the top ; When you release the element , It runs back to its original level . This is a Fabric.js Default state of .

If you don't want this to happen during operation , You want to keep the level of the element when it is selected , Then I recommend that you initialize the canvas , Set up preserveObjectStacking by true .

《preserveObjectStacking file 》

Next, I will illustrate the effect and usage of this attribute .

By default

By default, the selected element will run to the top , When it is released, it runs back to its original level .

<canvas id="canvasBox" width="600" height="600" style="border: 1px solid #ccc;"></canvas>

<!--  introduce  Fabric.js -->
<script src="https://cdn.bootcdn.net/ajax/libs/fabric.js/521/fabric.js"></script>

<script>
  const canvas = new fabric.Canvas('canvasBox')
  
  //  circular 
  circle = new fabric.Circle({
    name: 'circle',
    top: 60,
    left: 60,
    radius: 30, //  The radius of the circle  30
    fill: 'yellowgreen'
  })

  //  rectangular 
  rect = new fabric.Rect({
    name: 'rect',
    top: 30, //  From the top of the container  60px
    left: 100, //  To the left of the container  200px
    fill: 'orange', //  fill a  Orange 
    width: 60, //  Width  60px
    height: 60 //  Height  60px
  })
  
  //  Add rectangle to canvas 
  canvas.add(circle, rect)
</script>
 Copy code 

The above code , I created a green circle and an orange rectangle .

stay canvas.add(circle, rect) in , Add a circle first , Add rectangle again , So the level of rectangle will be higher than that of circle .

I deliberately adjusted the position of the two figures , Let them overlap in part .

So the final result is that the circle is under the rectangle .

Fabric.js By default , The selected element will jump to the top , So you can see the operation effect in the above figure .

Keep the same level

If you don't want to do it by default , Especially when there are many objects in the canvas , You want the object to be manipulated to remain at its original level , This operation will be more intuitive in some cases . Then you can initialize the canvas preserveObjectStacking Set to true

//  Omitted code 

const canvas = new fabric.Canvas('canvasBox', {
  //  The element object remains current when it is selected z Axis , Will not jump to the top 
  preserveObjectStacking: true //  Default false
})
 Copy code 

Code warehouse

Keep the original level when the element is selected

原网站

版权声明
本文为[Director of Moral Education Division]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101602369047.html