向画布中导入的svg元素添加侦听器

Add listener to a svg element which is imported in canvas

本文关键字:元素 添加 侦听器 svg 布中 导入      更新时间:2023-09-26

我需要在画布元素上添加事件侦听器(我知道它们实际上不是元素)。我明白这只有通过svg才能实现。因此,我按照这里给出的示例将一些svg元素导入画布。我的代码是这样的:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
//wherever I put the id inside the svg element it does not fire the event
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
       '<foreignObject width="100%" height="100%">' +
       '<div id="asdf" xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +
         '<em >I</em> like ' + 
         '<span style="color:white; text-shadow:0 0 2px blue;">' +
         'cheese</span>' +
       '</div>' +
       '</foreignObject>' +
       '</svg>';
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
var url = DOMURL.createObjectURL(svg);
img.onload = function () {
   ctx.drawImage(img, 0, 0);
   DOMURL.revokeObjectURL(url);
}
img.src = url;
document.getElementById('asdf').addEventListener("click", function(){
    alert('AJDEEE');
});

如果我将监听器附加到画布上,它就会工作。但是,当它附加到svg中的元素时,它不会。是我错了吗,还是那样根本不可能?如有任何帮助,不胜感激。

你把SVG渲染到画布上,现在你有了一个栅格。你只要点击光栅就行了。