因为创建的命名空间元素
createElementNS
,您需要使用
element.setAttributeNS
而不是
element.setAttribute
.
试试这个:
let svg = document.getElementById('canvas');
let boxSide = 200;
const svgns = 'http://www.w3.org/2000/svg';
let element = document.createElementNS(svgns, 'image');
element.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'icons/remove.svg');
element.setAttributeNS(null, 'width', boxSide.toString());
element.setAttributeNS(null, 'height', boxSide.toString());
element.setAttributeNS(null, 'x', '0');
element.setAttributeNS(null, 'y', '0');
svg.appendChild(element);