Reputation: 325
I've got a canvas and an image. I want to be able to drag and drop the image into the canvas. Get nothing in the console that e is not defined or anything.. anybody got a clue?
Thanks for the help now and all for all my other posts! :)
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);
Upvotes: 0
Views: 251
Reputation: 19294
The following code is working :
( 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);
With this 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>
Upvotes: 1