0

我有一个画布和一个图像。我希望能够将图像拖放到画布中。在控制台中什么都没有得到 e 没有定义或任何东西..有人知道吗?

感谢您现在的帮助以及我所有其他帖子的帮助!:)

javascript:

function first(){
    dragedPic = document.getElementById('firstPic');
    dragedPic.addEventListener("dragstart", startDrag, false);
    canvas = document.getElementById('Canvas');
    canvas.addEventListener("dragenter", function(e){e.preventDefault();}, false);
    canvas.addEventListener("dragover", function(e){e.preventDefault();}, false);
    canvas.addEventListener("drop", dropped, false);
}
function startDrag(e){
    var code = '<img src="FärgadePapper.png">';
    e.dataTransfer.setData('Text', code);
}
function dropped(e){
    e.preventDefault();
    canvas.innerHTML = e.dataTransfer.getData('Text');
}
window.addEventListener("load", first, false);
4

1 回答 1

1

以下代码正在工作:

( http://jsbin.com/ukAFev/1/ )

var dragedPic = null;
var canvas = null;


function first(){
    dragedPic = document.getElementById('firstPic');
    dragedPic.addEventListener("dragstart", startDrag, false);
    canvas = document.getElementById('Canvas');
    canvas.addEventListener("dragenter", function(e){e.preventDefault();}, false);
    canvas.addEventListener("dragover", function(e){e.preventDefault();}, false);
    canvas.addEventListener("drop", dropped, false);  
}

function startDrag(e){
  // the general case is to send the image id.
  e.dataTransfer.setData('Image', 'firstPic' );
}

function dropped(e){
 //   e.preventDefault();
    var imgId = e.dataTransfer.getData('Image'); 
    var img = document.getElementById(imgId);
    var ctx = canvas.getContext('2d');
    var ratio = canvas.width/img.naturalWidth;   
    ctx.save();
    ctx.scale(ratio, ratio);
    ctx.drawImage(img, 0,0);
    ctx.restore();
}
window.addEventListener("load", first);

有了这个 html:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <canvas width=400 height=400 id='Canvas'>Canvas not supported on this Browser </canvas>
  <br/>
  <img id = 'firstPic' 
  src='http://www.tlh.ch/images/vote/zoom/4.jpg'/>    
</body>
</html>
于 2013-11-09T21:00:55.000 回答