gpt4 book ai didi

javascript - 拖放图像,在 Canvas 上显示该图像

转载 作者:行者123 更新时间:2023-12-04 07:53:16 25 4
gpt4 key购买 nike

我想做一个拖放图像,然后在 Canvas 上显示该图像,但我真的不知道该怎么做。但这是我尝试过的:

var canvas = document.getElementById("canvas2");
var c = canvas.getContext("2d");
//console.log(canvas)


canvas.ondrop = function(e){
e.preventDefault();
c.drawImage(e.dataTransfer.files[0], 0, 0, c.canvas.width, c.canvas.height);
}

canvas.ondragover = function(e){
console.log("test")
return false;
}
#canvas2{
position:relative;
z-index:100;
margin-top: 100px;
border:1px solid #000000;
}
<html lang="en">
<head>
<!-- <meta http-equiv="refresh" content="5" > -->
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<!-- <label for="GridCheck">Grid:</label> -->
<!-- <input type="checkbox" id="GridCheck" onclick="GridToggle('canvas1')"> -->
<div class="canvasContainer">
<canvas id = "canvas2" class="canvas"></canvas>
</div>
<script src="main.js"></script>
</body>
</html>

我知道问题是“c.drawImage(e.dataTransfer.files[0], 0, 0, c.canvas.width, c.canvas.height);”部分。我是否需要实际上传图像才能访问它在 Canvas 上显示它?我糊涂了...

最佳答案

您可以这样做,尽管它可能与您所说的有所不同,但我认为您可以对其进行足够的编辑以使其像您想要的那样:
代码

const fill = document.querySelector('.fill');
const empties = document.querySelectorAll('.empty');


fill.addEventListener('dragstart', dragStart);
fill.addEventListener('dragend', dragEnd);


for (const empty of empties) {
empty.addEventListener('dragover', dragOver);
empty.addEventListener('dragenter', dragEnter);
empty.addEventListener('dragleave', dragLeave);
empty.addEventListener('drop', dragDrop);
}



function dragStart() {
this.className += ' hold';
setTimeout(() => (this.className = 'invisible'), 0);
}

function dragEnd() {
this.className = 'fill';
}

function dragOver(e) {
e.preventDefault();
}

function dragEnter(e) {
e.preventDefault();
this.className += ' hovered';
}

function dragLeave() {
this.className = 'empty';
}

function dragDrop() {
this.className = 'empty';
this.append(fill);
}
body {
background: #1a911a;
}

.fill {
background-image: url('https://source.unsplash.com/random/150x150');
position: relative;
height: 150px;
width: 150px;
top: 5px;
left: 5px;
cursor: pointer;
}

.hold {
border: solid 5px #ccc;
}

.empty {
display: grid;
height: 160px;
width: 160px;
margin: 10px;
border: solid 3px red;
background: white;
grid-row: 1/4;
grid-column: 3/4;
}

.hovered {
background: #f4f4f4;
border-style: dashed;
}
<!DOCTYPE HTML>
<html lang="en">

<head>
<script src="(Filename).js"></script>
<title>Drag and Drop</title>
</head>

<body>
<div class="empty">
<div class="fill" draggable="true"> </div>
</div>
<div class="empty"></div>
</body>

</html>

关于javascript - 拖放图像,在 Canvas 上显示该图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66837015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com