【问题标题】:Why won't the the image drop into the canvas?为什么图像不会掉到画布中?
【发布时间】:2013-11-21 20:00:31
【问题描述】:

我有一张画布和一张图片。我希望能够将图像拖放到画布中。在控制台中什么都没有得到 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);

【问题讨论】:

  • 您应该将数据作为 img 本身(您检索 ById 或类似内容)。
  • 我不太明白。我想当你放下图像时,它会找到它存储的图像并粘贴它......

标签: javascript html drag-and-drop html5-canvas


【解决方案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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 2014-08-15
    • 2022-01-09
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 2021-04-06
    相关资源
    最近更新 更多