获取 canvas id "OnClick"

Get canvas id "OnClick"

我正在尝试使用 pdf.js 生成 pdf,现在我想在单击特定 canvas.[=16 时获得 canvas "id" =]

这是我的 fiddle 演示 https://jsfiddle.net/14953eak/

代码:

<div class="container">
    <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12">
        <div id='pdf-viewer'></div>
    </div>
</div>

脚本:

url = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf';
    var thePdf = null;
    var scale = 1;
    var canvas;
    var inst = this;
    var ctx;

    pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://mozilla.github.io/pdf.js/build/pdf.worker.js';
    pdfjsLib.getDocument(url).promise.then(function (pdf) {
        thePdf = pdf;
        viewer = document.getElementById('pdf-viewer');
        for (page = 1; page <= pdf.numPages; page++) {
            canvas = document.createElement("canvas");
            canvas.id = "Page-" + page;
            canvas.className = 'pdf-page-canvas';
            viewer.appendChild(canvas);
            renderPage(page, canvas);
        }
    });

    function renderPage(pageNumber, canvas) {
        thePdf.getPage(pageNumber).then(function (page) {
            viewport = page.getViewport(scale);
            canvas.height = viewport.height;
            canvas.width = viewport.width;
            newcanvas = document.getElementById("Page-" + pageNumber);
            ctx = canvas.getContext('2d');
            var renderContext = {
                canvasContext: ctx,
                viewport: viewport
            };
            var renderTask = page.render(renderContext);
            renderTask.promise.then(function () {
                console.log('Page rendered');
            });
        });
    }

为此,您需要在创建 canvas 元素的 for 循环中添加 click 事件处理程序。然后您可以在事件处理函数中使用 this.id 检索元素的 id。试试这个:

canvas.addEventListener('click', function() {
  console.log(this.id);
  // work with the id here...
});

Updated fiddle