Puppeteer: 鼠标移动
mouse.click 是 mouse.move,mouse.down 和 mouse.up 的快捷方式
main.js
const pptr = require('puppeteer');
const gotoUrl = 'http://127.0.0.1:5500/index.html';
(async () => {
const browser = await pptr.launch({
headless: false,
slowMo: 250,
});
const page = await browser.newPage();
page.on('console', msg => {
console.log(msg.text());
});
await page.goto(gotoUrl);
await page.mouse.move(100, 100);
await page.mouse.down();
await page.mouse.move(200, 100, {
steps: 3,
});
await page.mouse.move(200, 200);
await page.mouse.move(100, 200);
await page.mouse.move(100, 100);
await page.mouse.up();
await page.mouse.move(150, 150);
await page.mouse.down();
setTimeout(async () => {
await browser.close();
}, 2000);
})();
index.html
<!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>Document</title>
<style>
html,
body {
margin: 0;
}
</style>
</head>
<body>
<script src="https://unpkg.com/p5@0.7.2/lib/p5.min.js"></script>
<script src="https://unpkg.com/p5@0.7.2/lib/addons/p5.dom.min.js"></script>
<script>
let isButtonRight = false;
let make = null;
let root = null;
let makeSize = null;
function setup() {
root = createDiv();
createCanvas(600, 400)
.parent(root)
.id('js-canvas');
background(0);
makeSize = createVector(40, 40);
createmake();
document.getElementById('js-canvas').oncontextmenu = e =>
e.preventDefault();
document.getElementById('js-make').oncontextmenu = e =>
e.preventDefault();
}
function draw() {
if (mouseIsPressed) {
// 鼠标按下画
if (mouseIsPressed && mouseButton === LEFT) {
// stroke(random(255), random(255), random(255));
stroke('red');
strokeWeight(4);
line(
isButtonRight ? mouseX : pmouseX,
isButtonRight ? mouseY : pmouseY,
mouseX,
mouseY,
);
isButtonRight = false;
} else if (mouseButton === RIGHT) {
isButtonRight = true;
// if(keyCode === 18){// 按下 alt 相加
// makeSize.add(0.5, 0.5);
// }else if(keyCode === 17){ // 按下 ctrl 相减
// makeSize.sub(0.5, 0.5);
// }
make.size(makeSize.x, makeSize.y);
make.position(mouseX, mouseY).show();
fill(0);
noStroke();
ellipseMode(CENTER);
ellipse(mouseX, mouseY, makeSize.x);
}
}
if (keyIsPressed) {
// 按下空格键清空画布
if (keyCode == 32) background(0);
}
}
function mouseReleased() {
if (mouseButton === RIGHT) {
make.hide();
makeSize = createVector(40, 40);
}
}
// make在右键被呼起时才显示, 右键被抬起则隐藏
function createmake() {
make = createDiv()
.parent(root)
.id('js-make')
.size(makeSize.x, makeSize.y)
.style('background-color', '#fff')
.style('border-radius', '50%')
.style('transform', 'translate(-40%, -40%)')
.hide();
}
</script>
</body>
</html>