javascript - 如何触发使用闭包变量的事件?
问题描述
在 Pixi.js 游戏中,我想模拟鼠标在画布上的点击。在下面的代码中,事件处于关闭状态,但我想从外部触发它。如果可能的话,您能帮我弄清楚如何从浏览器控制台执行此操作吗?
jsfiddle:https ://jsfiddle.net/mwLwkebo/4/
HTML:
<body>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/4.5.3/pixi.min.js"></script>
JavaScript:
(function () {
'use strict';
const Container = PIXI.Container,
autoDetectRenderer = PIXI.autoDetectRenderer,
loader = PIXI.loader,
resources = PIXI.loader.resources,
Sprite = PIXI.Sprite,
Point = PIXI.Point,
width = window.innerWidth,
height = window.innerHeight;
const renderer = autoDetectRenderer(width, height),
stage = new Container();
document.body.appendChild(renderer.view);
loader
.add('pixel', 'https://pbs.twimg.com/profile_images/751168765191081988/3y6h5fRA.jpg')
.load(go);
function go() {
const pixelContainer = new Container(),
pixel = new Sprite(resources.pixel.texture);
pixelContainer.name = 'pixelContainer';
pixelContainer.interactive = true;
pixelContainer.on('mousedown', event => {
console.log(`Container clicked (${pixelContainer.name})`);
});
pixel.name = 'pixel';
pixel.width = width;
pixel.height = height;
pixel.interactive = true;
pixel.on('mousedown', event => {
console.log(`Sprite clicked (${pixel.name})`);
});
pixelContainer.addChild(pixel);
stage.addChild(pixelContainer);
renderer.render(stage);
setTimeout(simulateClick, 3000);
}
const el = document.querySelector('canvas');
el.addEventListener('click', event => {
console.log('Canvas clicked');
});
function simulateClick(mode) {
const x = 10,
y = 10,
ev = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true,
'clientX': x,
'clientY': y
});
if (mode) document.elementFromPoint(x, y).dispatchEvent(ev);
else el.dispatchEvent(ev);
};
})();
解决方案
为了使simulateClick()
开发工具控制台中的功能可用,您可以:
- 打开开发工具并转到
Sources
选项卡 - 加载页面
- 在源代码的 Sources 选项卡中找到函数的定义位置
- 在那里设置断点
- 重新加载页面
- 当您的函数定义后执行暂停时,转到
Console
开发工具中的选项卡 - 写
window.simulate = simulateClick
(或任何你想访问的功能)并按回车 - 恢复页面的执行
- 现在,在控制台中,您可以运行
simulate(true)
并且您的函数将被执行
推荐阅读
- php - 如何在三重内连接表中显示适当的数据?
- ios - 自定义 UILongPressGestureRecognizer 无法使用 VoiceOver 的问题
- javascript - 我们能否在 oracle apex 中使全局页面上的区域不每次都加载(使其成为静态)。有没有办法限制它?
- reactjs - React Router v5 恢复滚动位置
- c# - 为什么在.Net C# 中从 MySql 读取后日期格式会发生变化?
- here-api - HERE API 直通航点
- python - Python 记录器忽略类中的 FileHandler 和 StreamHandler 级别
- gmail-addons - 如何发布 Google Docs 插件以便只有我的 G-Suite 中的人可以安装它?
- c# - 如何在我的实体上下文中直接访问我的 Auth0 令牌?
- python - Slack 通知不会在自定义标签上触发