如何将div或文件的图像传输到某些可辍学的帆布区域(内部画布(?我的目的是制作一本photobook。
我正在使用DIV标签进行操作,但是我已经看到所有的photobooks都用画布来。他们甚至将照片作为滴剂作为画布发送。
<canvas id="canvas" style="position:absolute;"></canvas>
<canvas id="canvas-encima" style="position:absolute;left:8em;top:7em;"></canvas>
<script>
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width= 1000;
canvas.height = 481;
var background = new Image();
background.src = "upload/plantilla5prueba.jpg";
background.onload = function() {
ctx.drawImage(background,0,0);
}
var canvas2 = document.getElementById("canvas-encima"),
ctx2 = canvas2.getContext("2d");
canvas2.width= 330;
canvas2.height = 280;
var image2 = new Image();
image2.src = "upload/celular.png";
image2.onload = function() {
ctx2.drawImage(image2,0,0);
;}
</script>
我相信,随着斑点或上载文件的拖放,可以将photobook几乎制成。
为了使画布中的一个区域掉落,我首先标记了可辍学的区域。请参阅markDroppableZone()
功能。在dragenter
,dragover
和drop
上,我首先使用isPointInPath
检查鼠标是否在辍学区域内。请参阅onEvent()
功能。
如果鼠标在路径中,则使用e.stopPropagation(); e.preventDefault();
。这阻止了新窗口中拖动图像的打开。
在drop
I程序上接下来要处理丢弃的文件。请参阅handleFiles()
功能。
const ctx = canvas.getContext("2d")
let cw = canvas.width;
let ch = canvas.height;
//the mouse
let m = {}
ctx.setLineDash([4]);
markDroppableZone();
ctx.stroke();
ctx.setLineDash([]);
function markDroppableZone(){
ctx.beginPath();
ctx.rect(10,10,160,160);
}
canvas.addEventListener("dragenter", dragenter, false);
canvas.addEventListener("dragover", dragover, false);
canvas.addEventListener("drop", drop, false);
function dragenter(e) {
onEvent(e);
}
function dragover(e) {
onEvent(e);
}
function drop(e) {
onEvent(e);
let data = e.dataTransfer;
let files = data.files;
// handle files
handleFiles(files);
}
function handleFiles(files){
for (var i = 0; i < files.length; i++) {
var theFile = files[i];
// check if the file is an image
var isImagen = /^image//;
// if it's not an image continu
if (!isImagen.test(theFile.type)) {
continue;
}
var img = new Image();
img.src = window.URL.createObjectURL(theFile);
img.onload = function() {
ctx.save();
markDroppableZone();
// clip the context
ctx.clip();
// draw the image
ctx.drawImage(this, 10, 10);
ctx.restore();
window.URL.revokeObjectURL(this.src);
}
}
}
function onEvent(e){
m = oMousePos(canvas, e);
markDroppableZone();
if (ctx.isPointInPath(m.x, m.y)){
e.stopPropagation();
e.preventDefault();
}
}
function oMousePos(canvas, evt) {
var ClientRect = canvas.getBoundingClientRect();
return { //objeto
x: Math.round(evt.clientX - ClientRect.left),
y: Math.round(evt.clientY - ClientRect.top)
}
}
canvas{background:#e9e9e9}
<canvas id="canvas" width="500" height="500"></canvas>