使用HTML5在画布内拖放功能

前端之家收集整理的这篇文章主要介绍了使用HTML5在画布内拖放功能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
大家好我们可以使用 html5在canvas中放置拖放功能吗?

我的实际要求是将图像拖动到应该在画布内完成的文本框中…
分享您的想法.以下链接我曾经学习拖放但它应该在画布内完成..

http://www.w3schools.com/html5/tryit.asp?filename=tryhtml5_draganddrop

解决方法

您可以在本教程中了解更多信息: http://html5.litten.com/how-to-drag-and-drop-on-an-html5-canvas/

从您在问题中的有限描述中,听起来像是在画布上拖动项目,本教程可能是最佳匹配.

这是您可以粘贴到文件中并在符合HTML5的浏览器中打开的实际代码,它将起作用:

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <Meta charset="UTF-8" />
  5. <title>Canvas Drag and Drop Test</title>
  6. </head>
  7. <body>
  8. <section>
  9.  
  10. <div>
  11. <canvas id="canvas" width="400" height="300">
  12. This text is displayed if your browser does not support HTML5 Canvas.
  13. </canvas>
  14. </div>
  15.  
  16. <script type="text/javascript">
  17.  
  18. var canvas;
  19. var ctx;
  20. var x = 75;
  21. var y = 50;
  22. var WIDTH = 400;
  23. var HEIGHT = 300;
  24. var dragok = false;
  25.  
  26. function rect(x,y,w,h) {
  27. ctx.beginPath();
  28. ctx.rect(x,h);
  29. ctx.closePath();
  30. ctx.fill();
  31. }
  32.  
  33. function clear() {
  34. ctx.clearRect(0,WIDTH,HEIGHT);
  35. }
  36.  
  37. function init() {
  38. canvas = document.getElementById("canvas");
  39. ctx = canvas.getContext("2d");
  40. return setInterval(draw,10);
  41. }
  42.  
  43. function draw() {
  44. clear();
  45. ctx.fillStyle = "#FAF7F8";
  46. rect(0,HEIGHT);
  47. ctx.fillStyle = "#444444";
  48. rect(x - 15,y - 15,30,30);
  49. }
  50.  
  51. function myMove(e){
  52. if (dragok){
  53. x = e.pageX - canvas.offsetLeft;
  54. y = e.pageY - canvas.offsetTop;
  55. }
  56. }
  57.  
  58. function myDown(e){
  59. if (e.pageX < x + 15 + canvas.offsetLeft && e.pageX > x - 15 +
  60. canvas.offsetLeft && e.pageY < y + 15 + canvas.offsetTop &&
  61. e.pageY > y -15 + canvas.offsetTop){
  62. x = e.pageX - canvas.offsetLeft;
  63. y = e.pageY - canvas.offsetTop;
  64. dragok = true;
  65. canvas.onmousemove = myMove;
  66. }
  67. }
  68.  
  69. function myUp(){
  70. dragok = false;
  71. canvas.onmousemove = null;
  72. }
  73.  
  74. init();
  75. canvas.onmousedown = myDown;
  76. canvas.onmouseup = myUp;
  77.  
  78. </script>
  79.  
  80. </section>
  81. </body>
  82. </html>

猜你在找的HTML5相关文章