javascript - Onload() 处理程序在 IE 中没有响应

标签 javascript jquery html canvas svg

我正在创建一个 Canvas 并使用drawImage()来绘制一个内联svg。一切正常,但由于以下问题我陷入困境......

我的问题是 onload 处理程序在 IE 中没有响应? Rhis 在 FF 和 chrome 中工作。如何修复它以在 IE 9 及以上版本中工作?

img2.onload = function() {
     console.log("load");
}

jsFiddle

function createme() {
      var test = $('<canvas />', { id : 'mycanvs' })
      $('#album').append(test);

      var svg2 = document.getElementById('sSource').innerHTML,
          vms = test[0], //canvas
          ctx2 = vms.getContext('2d');

      svgToImage(svg2);

      function svgToImage(svg2) {
        var nurl = "data:image/svg+xml;utf8," + encodeURIComponent(svg2),
            img2 = new Image;
          alert("just before onload")
          img2.onload = function() {
              console.log("load"); // does not show
          }
          img2.src = nurl;
      }
}

最佳答案

我目前没有运行 IE VM,但根据their docs处理程序必须在对象本身之前定义:

To ensure that an event handler receives the onload event for these objects, place the script object that defines the event handler before the object and use the onload attribute in the object to set the handler.

我不明白为什么你的代码在 IE 中不起作用,但是这个 fiddle 稍微调整了它,以便在创建图像对象之前定义你的处理程序...尝试一下:

function createme() {
      var test = $('<canvas />', { id : 'mycanvs' });
      var onloadHandler = function() {
          console.log("load");
      };
      $('#album').append(test);

      var svg2 = document.getElementById('sSource').innerHTML,
          vms = test[0], //canvas
          ctx2 = vms.getContext('2d');

      function svgToImage(svg2) {
        var nurl = "data:image/svg+xml;utf8," + encodeURIComponent(svg2),
            img2 = new Image;

          img2.onload = onloadHandler

          img2.src = nurl;
      }
      svgToImage(svg2);
}
createme();

https://jsfiddle.net/z769z7af/10/

关于javascript - Onload() 处理程序在 IE 中没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29438749/

相关文章:

javascript - 根据另一个输入值更改输入值

javascript - 可折叠的 Bootstrap 4 Accordion 无法正常工作

javascript - Jquery 尝试使用 html() 获取 src

javascript - 通过两个文本查找元素

Python 抓取无法提取所有 <li> 的

html - CSS 中的宽度无法正常工作

javascript - Bootstrap 标签输入不显示标签

php - 无法运行 AJAX 请求

jQuery 模拟选择选项上的点击事件

html - 如何使 iframe 具有指针事件 : none; but not on a div inside that?