经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 软件/图像 » SVG » 查看文章
《最新出炉》系列初窥篇-Python+Playwright自动化测试-64 - Canvas和SVG元素推拽 - 北京-宏哥
来源:cnblogs  作者:北京-宏哥  时间:2024/8/7 8:50:57  对本文有异议

1.简介

今天宏哥分享的在实际测试工作中很少遇到,比较生僻,如果突然遇到我们可能会脑大、懵逼,一时之间不知道怎么办?所以宏哥这里提供一种思路供大家学习和参考。

2.SVG简介

svg也是html5新增的一个标签,它跟canvas很相似。都可以实现绘图、动画。但是svg绘制出来的都是矢量图,不像canvas是以像素为单位的,放大会模糊。svg绘制出来的图是不会的。SVG英文全称为Scalable vector Graphics,意思为可缩放的矢量图,这种元素比较特殊,需要通过 ?name?() 函数来进行定位。

3.SVG元素拖拽

3.1svg拖拽demo

1.svg下的circle元素是可以拖动的,宏哥网上找了半天没有找到,然后自己动手写一个demo用于演示(可以看到circle的cx和cy在拖拽的过程中不断的发生变化),如下图所示:

 2.demo的参考代码:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.  
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  8. <title>北京-宏哥</title>
  9. <style>
  10. svg {
  11. margin-left: 100px;
  12. margin-top: 100px;
  13. border: 1px solid black
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. <svg width="500" height="300" id="svg-container">
  19. <circle cx="100" cy="100" r="20" fill="blue" id="draggable-circle"></circle>
  20. </svg>
  21. </body>
  22. <script>
  23. // 获取SVG容器和可拖拽元素
  24. const svgContainer = document.getElementById('svg-container');
  25. const draggableElement = document.getElementById('draggable-circle');
  26. let isDragging = false;
  27. let startX, startY;
  28. // 鼠标按下事件处理程序
  29. function dragStart(event) {
  30. isDragging = true;
  31. startX = event.clientX - parseInt(draggableElement.getAttribute('cx')),
  32. startY = event.clientY - parseInt(draggableElement.getAttribute('cy'));
  33. // 阻止默认的拖拽行为
  34. event.preventDefault();
  35. }
  36. // 鼠标移动事件处理程序
  37. function drag(event) {
  38. if (isDragging) {
  39. const dx = event.clientX - startX;
  40. const dy = event.clientY - startY;
  41. draggableElement.setAttribute('cx', dx);
  42. draggableElement.setAttribute('cy', dy);
  43. }
  44. }
  45. // 鼠标抬起事件处理程序
  46. function dragEnd(event) {
  47. isDragging = false;
  48. }
  49. // 添加事件监听器
  50. draggableElement.addEventListener('mousedown', dragStart);
  51. svgContainer.addEventListener('mousemove', drag);
  52. svgContainer.addEventListener('mouseup', dragEnd);
  53. </script>
  54. </html>

3.接下来我们用上边的svg的demo来演示拖拽,其实在我们上一篇中掌握如何定位svg元素后,拖拽就非常简单了,无非就是一些鼠标的操作事件罢了。

3.2代码设计

3.3参考代码

  1. # coding=utf-8??
  2.  
  3. # 1.先设置编码,utf-8可支持中英文,如上,一般放在第一行
  4.  
  5. # 2.注释:包括记录创建时间,创建人,项目名称。
  6. '''
  7. Created on 2024-05-27
  8. @author: 北京-宏哥
  9. 公众号:北京宏哥(微信搜索:北京宏哥,关注宏哥,提前解锁更多测试干货!)
  10. Project:《最新出炉》系列初窥篇-Python+Playwright自动化测试-64 - Canvas和SVG元素推拽
  11. '''
  12.  
  13. # 3.导入模块
  14.  
  15. from playwright.sync_api import Playwright, sync_playwright, expect
  16. def run(playwright: Playwright) -> None:
  17. browser = playwright.chromium.launch(headless=False)
  18. context = browser.new_context()
  19. page = context.new_page()
  20. page.goto("C:/Users/Administrator/Desktop/svg.html")
  21. page.wait_for_timeout(1000)
  22. # svg元素定位
  23. circle = page.locator('//*[name()="svg"]/*[name()="circle"]')
  24. print(circle.bounding_box())
  25. box = circle.bounding_box()
  26. # svg元素拖拽
  27. page.mouse.move(x=box['x'] + box['width'] / 2, y=box['y'] + box['height'] / 2)
  28. page.mouse.down()
  29. page.mouse.move(x=box['x'] + box['width'] / 2 + 100, y=box['y'] + box['height'] / 2)
  30. page.mouse.up()
  31. page.wait_for_timeout(5000)
  32. page.close()
  33. context.close()
  34. browser.close()
  35. with sync_playwright() as playwright:
  36. run(playwright)

3.4运行代码

1.运行代码,右键Run'Test',就可以看到控制台输出,如下图所示:

2.运行代码后电脑端的浏览器的动作(l蓝色的圆圈被拖走了)。如下图所示:

4.canvas元素拖拽

4.1canvas拖拽demo

1.canvas下的元素是可以拖动的,宏哥网上找了半天没有找到,然后自己动手写一个demo用于演示(可以看到circle的style在拖拽的过程中不断的发生变化),如下图所示:

2.demo的参考代码:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.  
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  8. <title>北京-宏哥</title>
  9. <style>
  10. canvas {
  11. border: 1px solid black
  12. }
  13. </style>
  14. </head>
  15. <body>
  16. </body>
  17. <script>
  18. const canvas = document.createElement('canvas')
  19. canvas.width = 400
  20. canvas.height = 400
  21. canvas.id = 'canvas'
  22. document.body.appendChild(canvas)
  23. let ctx = canvas.getContext('2d') //画笔
  24.  
  25. // 状态标志
  26. const statusConfig = {
  27. IDLE: 0, //
  28. DRAGSTART: 1, //鼠标按下
  29. DRAGGING: 2 //托拽中
  30. }
  31. // 画布信息
  32. const canvasInfo = {
  33. status: statusConfig.IDLE, //状态
  34. dragTarget: null, //拖拽对象
  35. lastEvtPos: { //前一位置
  36. x: null,
  37. y: null
  38. },
  39. offsetEvtPos: { //前一偏移
  40. x: null,
  41. y: null
  42. }
  43. }
  44. let circles = [] //存储画的圆
  45.  
  46. // 画圆
  47. const drawCircle = (ctx, cx, cy, r) => {
  48. ctx.save()
  49. ctx.beginPath() //开始画
  50. ctx.arc(cx, cy, r, 0, Math.PI * 2)
  51. ctx.strokeStyle = 'pink'
  52. ctx.fillStyle = 'pink'
  53. ctx.stroke() //描边模式
  54. ctx.fill()
  55. ctx.closePath() //结束
  56. ctx.restore()
  57. }
  58. drawCircle(ctx, 100, 100, 10)
  59. // 存储圆的位置
  60. circles.push({
  61. x: 100,
  62. y: 100,
  63. r: 10
  64. })
  65. drawCircle(ctx, 200, 150, 20)
  66. circles.push({
  67. x: 200,
  68. y: 150,
  69. r: 20
  70. })
  71. // 元素拖拽 鼠标的画布坐标
  72. const getCanvasPostion = e => {
  73. return {
  74. x: e.offsetX, //鼠标在页面中的位置的同时减去canvas元素本身的偏移量
  75. y: e.offsetY,
  76. }
  77. }
  78. // 两点之间的距离
  79. const getInstance = (p1, p2) => {
  80. // 指数运算符 **,它们分别对 (p1.x - p2.x) 和 (p1.y - p2.y) 进行自乘。
  81. return Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)
  82. // 或者
  83. // Math.pow 函数,它用于计算指定数字的指定次方。
  84. // return Math.sqrt(Math.pow((p1.x - p2.x), 2) + Math.pow((p1.y - p2.y), 2))
  85. }
  86. // 判断鼠标是否在圆内
  87. const ifInCirlce = (pos) => {
  88. for (let i = 0; i < circles.length; i++) {
  89. if (getInstance(circles[i], pos) < circles[i].r) {
  90. return circles[i]
  91. }
  92. }
  93. return false
  94. }
  95. // 鼠标按下监听
  96. canvas.addEventListener('mousedown', e => {
  97. const canvasPostion = getCanvasPostion(e)
  98. const circleRef = ifInCirlce(canvasPostion)
  99. if (circleRef) {
  100. console.log(circleRef);
  101. canvasInfo.dragTarget = circleRef //拖拽对象
  102. canvasInfo.status = statusConfig.DRAGSTART
  103. canvasInfo.lastEvtPos = canvasPostion
  104. canvasInfo.offsetEvtPos = canvasPostion
  105. }
  106. })
  107. // 鼠标移动
  108. canvas.addEventListener('mousemove', e => {
  109. const canvasPostion = getCanvasPostion(e)
  110. const {dragTarget} = canvasInfo
  111. if (ifInCirlce(canvasPostion)) {
  112. canvas.style.cursor = 'all-scroll'
  113. }else {
  114. canvas.style.cursor = ''
  115. }
  116. if (!dragTarget) return
  117. if (canvasInfo.status === statusConfig.DRAGSTART && getInstance(canvasPostion, canvasInfo.lastEvtPos) > 5) {
  118. console.log('try to drag');
  119. canvasInfo.status = statusConfig.DRAGGING
  120. canvasInfo.offsetEvtPos = canvasPostion
  121. }else if(canvasInfo.status === statusConfig.DRAGGING){
  122. console.log('draging');
  123. dragTarget.x += (canvasPostion.x - canvasInfo.offsetEvtPos.x)
  124. dragTarget.y += (canvasPostion.y - canvasInfo.offsetEvtPos.y) //基于偏移
  125. ctx.clearRect(0,0, canvas.width, canvas.height) //清空画布
  126. circles.forEach(c => drawCircle(ctx, c.x, c.y, c.r))
  127. canvasInfo.offsetEvtPos = canvasPostion
  128. }
  129. })
  130. canvas.addEventListener('mouseup', e => {
  131. canvasInfo.status = statusConfig.IDLE
  132. })
  133. canvas.addEventListener('mouseleave', e => {
  134. canvasInfo.status = statusConfig.IDLE
  135. canvas.style.cursor = ''
  136. })
  137. </script>
  138. </html>

3.接下来我们用上边的canvas的demo来演示拖拽,同理:其实在我们上一篇中掌握如何定位canvas元素后,拖拽就非常简单了,无非就是一些鼠标的操作事件罢了。然而却在实践过程中发现并不简单,虽然可以定位到但是操作不了。宏哥觉得原因可能是canvas定位到是整个一块画布,而其上边的圆圈是通过绘画出来的,无法定位所以就无法操作了。而且按F2查看元素确实没有圆圈的元素。如下图所示:

5.小结

今天主要讲解和分享了SVG元素的定位和拖拽,实践过程中发现canvas无法拖拽,有可以实现拖拽的小伙伴或者童鞋们可以给宏哥留言哈,大家一起学习进步。好了,今天时间也不早了,宏哥就讲解和分享到这里,感谢您耐心的阅读,希望对您有所帮助。

原文链接:https://www.cnblogs.com/du-hong/p/18177694

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号