问题
The following code should output 'hello' in the console, when I mark either the text "Canvas" or the image "testimage.png" and drag and drop it on the canvas. But it doesn't work.
When I add the eventListener to a textarea, it does work. But it really should be on the canvas. :/
I do not assume it is not possible.
How to do it? (The html file is on my domain, and the image file is on the same domain in the same directory.)
<html><head>
<script type="application/javascript">
function someInits() {
document.getElementById('canvas').addEventListener("drop", function( event ) {
console.log('hello'); //event.target.id
//event.target.style.opacity = "";
}, false);
}
</script>
</head>
<body onload="someInits();">
<hr>Canvas: <br>
<canvas id="canvas" width="300" height="300"></canvas>
<hr>
<img src="http://example.com/testimage.png">
</body>
</html>
回答1:
In firefox, you need to block the default behavior of the dragover event in order to tell the browser you're handling it.
More info on how to handle drag events
function someInits() {
// block the default dragover
document.getElementById('canvas').addEventListener("dragover", function(event) {
event.preventDefault();
}, false);
//handle the drop
document.getElementById('canvas').addEventListener("drop", function(event) {
event.preventDefault();
this.style.backgroundColor = 'pink';
console.log('hello');
}, false);
}
someInits();
canvas{border: 1px solid;}
<hr>Canvas:<br>
<canvas id="canvas" width="300" height="100"></canvas>
<hr>
<img id="img" src="http://lorempixel.com/200/200" draggable="true" />
来源:https://stackoverflow.com/questions/34761204/how-to-drop-texts-and-images-on-a-canvas-firefox-41-0-1