首页 > 解决方案 > 如何触发使用闭包变量的事件?

问题描述

在 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);
  };
})();

标签: javascriptdebuggingclosurespixi.js

解决方案


为了使simulateClick()开发工具控制台中的功能可用,您可以:

  • 打开开发工具并转到Sources选项卡
  • 加载页面
  • 在源代码的 Sources 选项卡中找到函数的定义位置
  • 在那里设置断点
  • 重新加载页面
  • 当您的函数定义后执行暂停时,转到Console开发工具中的选项卡
  • window.simulate = simulateClick(或任何你想访问的功能)并按回车
  • 恢复页面的执行
  • 现在,在控制台中,您可以运行simulate(true)并且您的函数将被执行

推荐阅读