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的参考代码:
- <!DOCTYPE html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>北京-宏哥</title>
- <style>
- svg {
- margin-left: 100px;
- margin-top: 100px;
- border: 1px solid black
- }
-
- </style>
- </head>
- <body>
- <svg width="500" height="300" id="svg-container">
- <circle cx="100" cy="100" r="20" fill="blue" id="draggable-circle"></circle>
- </svg>
- </body>
- <script>
- // 获取SVG容器和可拖拽元素
- const svgContainer = document.getElementById('svg-container');
- const draggableElement = document.getElementById('draggable-circle');
-
- let isDragging = false;
- let startX, startY;
-
- // 鼠标按下事件处理程序
- function dragStart(event) {
- isDragging = true;
- startX = event.clientX - parseInt(draggableElement.getAttribute('cx')),
- startY = event.clientY - parseInt(draggableElement.getAttribute('cy'));
- // 阻止默认的拖拽行为
- event.preventDefault();
- }
-
- // 鼠标移动事件处理程序
- function drag(event) {
- if (isDragging) {
- const dx = event.clientX - startX;
- const dy = event.clientY - startY;
- draggableElement.setAttribute('cx', dx);
- draggableElement.setAttribute('cy', dy);
- }
- }
-
- // 鼠标抬起事件处理程序
- function dragEnd(event) {
- isDragging = false;
- }
-
- // 添加事件监听器
- draggableElement.addEventListener('mousedown', dragStart);
- svgContainer.addEventListener('mousemove', drag);
- svgContainer.addEventListener('mouseup', dragEnd);
- </script>
- </html>
3.接下来我们用上边的svg的demo来演示拖拽,其实在我们上一篇中掌握如何定位svg元素后,拖拽就非常简单了,无非就是一些鼠标的操作事件罢了。
3.2代码设计

3.3参考代码
- # coding=utf-8??
-
- # 1.先设置编码,utf-8可支持中英文,如上,一般放在第一行
-
- # 2.注释:包括记录创建时间,创建人,项目名称。
- '''
- Created on 2024-05-27
- @author: 北京-宏哥
- 公众号:北京宏哥(微信搜索:北京宏哥,关注宏哥,提前解锁更多测试干货!)
- Project:《最新出炉》系列初窥篇-Python+Playwright自动化测试-64 - Canvas和SVG元素推拽
- '''
-
- # 3.导入模块
-
- from playwright.sync_api import Playwright, sync_playwright, expect
- def run(playwright: Playwright) -> None:
- browser = playwright.chromium.launch(headless=False)
- context = browser.new_context()
- page = context.new_page()
- page.goto("C:/Users/Administrator/Desktop/svg.html")
- page.wait_for_timeout(1000)
- # svg元素定位
- circle = page.locator('//*[name()="svg"]/*[name()="circle"]')
- print(circle.bounding_box())
- box = circle.bounding_box()
- # svg元素拖拽
- page.mouse.move(x=box['x'] + box['width'] / 2, y=box['y'] + box['height'] / 2)
- page.mouse.down()
- page.mouse.move(x=box['x'] + box['width'] / 2 + 100, y=box['y'] + box['height'] / 2)
- page.mouse.up()
- page.wait_for_timeout(5000)
- page.close()
- context.close()
- browser.close()
- with sync_playwright() as playwright:
- run(playwright)
3.4运行代码
1.运行代码,右键Run'Test',就可以看到控制台输出,如下图所示:

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

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

2.demo的参考代码:
- <!DOCTYPE html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>北京-宏哥</title>
- <style>
- canvas {
- border: 1px solid black
- }
-
- </style>
- </head>
- <body>
-
- </body>
- <script>
- const canvas = document.createElement('canvas')
- canvas.width = 400
- canvas.height = 400
- canvas.id = 'canvas'
- document.body.appendChild(canvas)
- let ctx = canvas.getContext('2d') //画笔
-
- // 状态标志
- const statusConfig = {
- IDLE: 0, //
- DRAGSTART: 1, //鼠标按下
- DRAGGING: 2 //托拽中
- }
- // 画布信息
- const canvasInfo = {
- status: statusConfig.IDLE, //状态
- dragTarget: null, //拖拽对象
- lastEvtPos: { //前一位置
- x: null,
- y: null
- },
- offsetEvtPos: { //前一偏移
- x: null,
- y: null
- }
- }
- let circles = [] //存储画的圆
-
- // 画圆
- const drawCircle = (ctx, cx, cy, r) => {
- ctx.save()
- ctx.beginPath() //开始画
- ctx.arc(cx, cy, r, 0, Math.PI * 2)
- ctx.strokeStyle = 'pink'
- ctx.fillStyle = 'pink'
- ctx.stroke() //描边模式
- ctx.fill()
- ctx.closePath() //结束
- ctx.restore()
- }
- drawCircle(ctx, 100, 100, 10)
- // 存储圆的位置
- circles.push({
- x: 100,
- y: 100,
- r: 10
- })
- drawCircle(ctx, 200, 150, 20)
- circles.push({
- x: 200,
- y: 150,
- r: 20
- })
- // 元素拖拽 鼠标的画布坐标
- const getCanvasPostion = e => {
- return {
- x: e.offsetX, //鼠标在页面中的位置的同时减去canvas元素本身的偏移量
- y: e.offsetY,
- }
- }
- // 两点之间的距离
- const getInstance = (p1, p2) => {
- // 指数运算符 **,它们分别对 (p1.x - p2.x) 和 (p1.y - p2.y) 进行自乘。
- return Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)
- // 或者
- // Math.pow 函数,它用于计算指定数字的指定次方。
- // return Math.sqrt(Math.pow((p1.x - p2.x), 2) + Math.pow((p1.y - p2.y), 2))
- }
- // 判断鼠标是否在圆内
- const ifInCirlce = (pos) => {
- for (let i = 0; i < circles.length; i++) {
- if (getInstance(circles[i], pos) < circles[i].r) {
- return circles[i]
- }
- }
- return false
- }
- // 鼠标按下监听
- canvas.addEventListener('mousedown', e => {
- const canvasPostion = getCanvasPostion(e)
- const circleRef = ifInCirlce(canvasPostion)
- if (circleRef) {
- console.log(circleRef);
- canvasInfo.dragTarget = circleRef //拖拽对象
- canvasInfo.status = statusConfig.DRAGSTART
- canvasInfo.lastEvtPos = canvasPostion
- canvasInfo.offsetEvtPos = canvasPostion
- }
- })
- // 鼠标移动
- canvas.addEventListener('mousemove', e => {
- const canvasPostion = getCanvasPostion(e)
- const {dragTarget} = canvasInfo
- if (ifInCirlce(canvasPostion)) {
- canvas.style.cursor = 'all-scroll'
- }else {
- canvas.style.cursor = ''
- }
- if (!dragTarget) return
- if (canvasInfo.status === statusConfig.DRAGSTART && getInstance(canvasPostion, canvasInfo.lastEvtPos) > 5) {
- console.log('try to drag');
- canvasInfo.status = statusConfig.DRAGGING
- canvasInfo.offsetEvtPos = canvasPostion
- }else if(canvasInfo.status === statusConfig.DRAGGING){
- console.log('draging');
- dragTarget.x += (canvasPostion.x - canvasInfo.offsetEvtPos.x)
- dragTarget.y += (canvasPostion.y - canvasInfo.offsetEvtPos.y) //基于偏移
- ctx.clearRect(0,0, canvas.width, canvas.height) //清空画布
- circles.forEach(c => drawCircle(ctx, c.x, c.y, c.r))
- canvasInfo.offsetEvtPos = canvasPostion
- }
- })
- canvas.addEventListener('mouseup', e => {
- canvasInfo.status = statusConfig.IDLE
- })
- canvas.addEventListener('mouseleave', e => {
- canvasInfo.status = statusConfig.IDLE
- canvas.style.cursor = ''
- })
- </script>
- </html>
3.接下来我们用上边的canvas的demo来演示拖拽,同理:其实在我们上一篇中掌握如何定位canvas元素后,拖拽就非常简单了,无非就是一些鼠标的操作事件罢了。然而却在实践过程中发现并不简单,虽然可以定位到但是操作不了。宏哥觉得原因可能是canvas定位到是整个一块画布,而其上边的圆圈是通过绘画出来的,无法定位所以就无法操作了。而且按F2查看元素确实没有圆圈的元素。如下图所示:

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