简体   繁体   English

javascript - 最后一张图片被点击带到前面

[英]javascript - last image clicked bring to front

I'm trying to make a really simple website in javascript. I want the website to have a stack of images that you can drag.我正在尝试在 javascript 中创建一个非常简单的网站。我希望该网站有一堆可以拖动的图像。 So far I managed to do it.到目前为止,我设法做到了。 But now I want to always bring to front the last clicked image.但现在我想始终将最后点击的图像放在前面。 How can I do this?我怎样才能做到这一点? Thanks !谢谢 !

Here is my code:这是我的代码:

<!DOCTYPE html>
<html>
  <head>
    <script src="https://unpkg.com/konva@8.4.0/konva.min.js"></script>
    <meta charset="utf-8" />
    <title></title>

    <style>

    body {
        margin: 0;
        padding: 0;
        overflow: hidden;
        background-color: #f0f0f0;
        }

    </style>

  </head>
  <body>
    <div id="container"></div>
    <script>
      var width = window.innerWidth;
      var height = window.innerHeight;

      var stage = new Konva.Stage({
        container: 'container',
        width: width,
        height: height,
      });

      var layer = new Konva.Layer();
      stage.add(layer);

      var img1 = new Konva.Image({
        x: 20,
        y: 20,
        width: 400,
        height: 566,
        
        draggable: true,
      });
      layer.add(img1);

      var img2 = new Konva.Image({
        x: 100,
        y: 20,
        width: 400,
        height: 566,
        draggable: true,
        
      });
      layer.add(img2);

      var imageObj1 = new Image();
      imageObj1.onload = function () {
        img1.image(imageObj1);
      };
      imageObj1.src = 'imgs/img1.jpg';

      var imageObj2 = new Image();
      imageObj2.onload = function () {
        img2.image(imageObj2);
      };
      imageObj2.src = 'imgs/img2.jpg';

      
    </script>
  </body>
</html>

I've seen this code on another post, but I don't know how to make it work..我在另一篇文章中看到过这段代码,但我不知道如何让它工作。

$("img.myclass").click(function() {
     $("img.myclass").not(this).css("z-index", 0);
     $(this).css("z-index", 100);
});

The "code on another post" is written in jQuery wich is an javascript library and need to be added to your page as you do with konva . “另一篇文章中的代码”是在jQuery中编写的,它是一个 javascript 库,需要像使用konva一样添加到您的页面。 Konva is a tool that draw an canvas . Konva 是一个绘制canvas的工具。 You can change zIndex (property that will change order of your stack) when you click on image.单击图像时,您可以更改zIndex (将更改堆栈顺序的属性)。 For example:例如:

img1.zIndex(0);
img2.zIndex(1); // will set img2 higher

If image didn't have zIndex() function you can try to wrap it to a group .如果图像没有zIndex() function 你可以尝试将它包装到一个中。

const group1 = new Konva.Group();

group1.add(img1);
group1.zIndex(0);

Edit:编辑:

Increase zIndex on click.单击时增加 zIndex。

let zIndex = 0;

img.onclick = function () {
   zIndex += 1;
   img.zIndex(zIndex);
}

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

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