我遵循这两个教程......但我不知道如何完成
答案 0 :(得分:0)
此示例允许您的用户将图片从桌面拖到背景画布上:
var canvas = document.getElementById("bk");
var bkctx = canvas.getContext("2d");
// dropzone event handlers
var dropzone;
dropzone = document.getElementById("dropzone");
dropzone.addEventListener("dragenter", dragenter, false);
dropzone.addEventListener("dragover", dragover, false);
dropzone.addEventListener("drop", drop, false);
//
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
//
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
//
function drop(e) {
e.stopPropagation();
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
handleFiles(files);
}
//
function handleFiles(files) {
for (var i = 0; i < files.length; i++) {
// get the next file that the user selected
var file = files[i];
var imageType = /image.*/;
// don't try to process non-images
if (!file.type.match(imageType)) {
continue;
}
// a seed img element for the FileReader
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
// get an image file from the user
// this uses drag/drop, but you could substitute file-browsing
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.onload = function() {
// draw the aImg onto the canvas
bkctx.clearRect(0, 0, canvas.width, canvas.height);
bkctx.drawImage(aImg, 0, 0);
}
// e.target.result is a dataURL for the image
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
} // end for
} // end handleFiles
&#13;
body {
background-color: ivory;
}
#dropzone {
border: 1px solid blue;
position: relative;
width: 300px;
height: 300px;
}
canvas {
border: 1px solid red;
position: absolute;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Drag an image from desktop to blue dropzone.</h4>
<div id="dropzone" width=300 height=300>
<canvas id="bk" width=300 height=300></canvas>
<canvas id="canvas" width=300 height=300></canvas>
</div>
&#13;