How to drop texts and images on a canvas? (Firefox 41.0.1)

自闭症网瘾萝莉.ら 提交于 2019-12-12 03:16:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!