本文介绍了如何在画布上放置文本和图像? (Firefox 41.0.1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我标记文本Canvas或图像testimage.png并将其拖放到画布上时,以下代码应在控制台中输出hello。
但它不工作。



当我添加eventListener到一个textarea,它的工作。但它真的应该在画布上。 :/



我不认为这是不可能的。



如何操作?
(html文件在我的域上,图像文件在同一目录下的同一个域中。)

 < 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 =canvaswidth =300height =300>< / canvas>
< hr>
< img src =http://example.com/testimage.png>
< / body>
< / html>


解决方案

在firefox中,您需要阻止默认行为 dragover 事件,以告诉正在处理它的浏览器。





 

 < hr& < br>< canvas id =canvaswidth =300height =100>< / canvas>< hr>< img id =imgsrc =http:// lorempixel。 com / 200/200draggable =true/>  


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

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" />

这篇关于如何在画布上放置文本和图像? (Firefox 41.0.1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 15:15