繁体   English   中英

如何将图像的一部分从父元素传输到子元素

[英]How can I transfer part of an image from a parent element to a child

我正在尝试使用 HTML、CSS 和 JavaScript 编写一个谜题。 目前我的代码接受一个图像,然后将该图像设置为 div 元素的背景。 然后 JavaScript 将 16 个子 div 元素附加到 html 文件中。 我希望我的代码将每个图像段从父元素移动到其各自的子元素。

我的 HTML 中有一个 div 元素:

<div id="image"></div>

JavaScript 代码附加了 16 个子 div 元素,每个元素都有一个唯一的 id:

$(document).ready(function(){
    let $url;
    $('#gameImage').keypress(function(e){
        if(e.keyCode == 13){
            $url = $('#gameImage').val();
            console.log($url);
            $('#gameImage').val('');
            $('#image').css("background-image", `url(${$url})`);
            for(let i=0;i<16;i++){
                console.log(i);
                $('#image').append('<div class="piece" id= "segment'+i+'"></div>')
            }
        }
    });
})

我希望能够点击这些子元素并围绕拼图的各个部分进行争夺,但是图像是父元素的背景图像。

我已经尝试按照这篇文章中的一些建议通过 Javascript 将图像切割成碎片,但是如果为每个碎片设置背景位置,我将无法移动图像。 使用画布提到的其他解决方案,但我无法使用画布制作可移动的 div 元素。

  • 设置多个切片(本演示中为 4 × 4)。
  • 获取每个盒子的尺寸
  • Foreach 并将您的 DIV 元素推入数组
  • 计算子级 CSS backgroundPosition
  • 使用shuffle功能
  • 填充你的拼图

 const slices = 4, img = "https://i.stack.imgur.com/QpnpY.jpg", // Desired image $puzzle = $("#puzzle"), // Puzzle square selector // Careful editing below this line... shuffle = a => { //stackoverflow.com/a/6274381/383904 let j, x, i; for (i = a.length - 1; i > 0; i--) { j = Math.floor(Math.random() * (i + 1)); x = a[i]; a[i] = a[j]; a[j] = x; } return a; }, pieces = slices * slices, size = $puzzle.width(), // so same height? boxSize = size / slices; // Create boxes let boxes = []; for (let i = 0; i < pieces; i++) { const x = -~~(i % slices) * boxSize, // Background position x y = -~~(i / slices) * boxSize; // y boxes.push($("<div>", { 'class': 'box', data: { index: i }, css: { width: boxSize, height: boxSize, backgroundImage: `url(${img})`, backgroundPosition: `${x}px ${y}px` }, html: `<b>${i}</b><br> x ${x}<br> y ${y}`, on: { click() { const index = $(this).data('index'); // Get clicked element data-index console.clear(); console.log( `INDEX: ${index}` ); // Do s/t with index } } })); } // Shuffle boxes shuffle(boxes); // Comment this line to see unshaffled boxes // Append boxes $puzzle.append(boxes);
 #puzzle { width: 400px; height: 400px; border: 1px solid #000; } #puzzle .box { float: left; box-shadow: inset 0 0 0 1px #000; color: #fff; }
 <div id="puzzle"></div> <script src="//code.jquery.com/jquery-3.1.0.js"></script>

以上应该有助于让你开始。
在每个项目上点击你可以获得元素的data-index 现在,单击两次后,您可以交换boxes数组中的这两个索引,并以相同的方式重新填充$puzzle
一旦所有的 DIV 索引都在0 to 15之间,这个谜题就应该结束了。

暂无
暂无

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

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