javascript - Lit-Element 绑定到 svg 图像。TypeError:无法读取 null 的属性“拆分”
问题描述
我一直在尝试将一个简单的 url(字符串)绑定到 svg 元素内的图像标签。
但我收到以下错误:TypeError: Cannot read property 'split' of null
浏览器中没有显示图片。
图像和绑定工作正常,在普通<img>
标签内或在<image/>
元素中硬编码时没有错误。
SVG 示例:
import { LitElement, svg } from 'lit-element';
class AppDevice extends LitElement {
static get properties() {
return {
selectedImage: {
type: String
}
};
}
constructor() {
super();
this.selectedImage = 'https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png';
}
render() {
return svg`
<svg width="600px" height="600px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<image xlink:href="${this.selectedImage}" id="canvas" x="176.32" y="145.932" width="252.068" height="252.068"/>
<!-- Works -->
<!-- <image xlink:href="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" id="canvas" x="176.32" y="145.932" width="252.068" height="252.068"/> -->
</svg>
`;
}
}
解决方法示例:
在阅读了这个问题的评论中指出的 github 上的讨论后,我更新了我的答案:
const namespaced = directive((namespace, value) => (part) => {
part.committer.element.setAttributeNS(namespace, part.committer.name, value);
});
const xlinkNamespace = 'https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png';
import { LitElement, html } from 'lit-element';
class AppDevice extends LitElement {
static get properties() {
return {
};
}
constructor() {
super();
}
render() {
return html`
<svg width="600px" height="600px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<image xlink:href="${namespaced(xlinkNamespace, 'something')}" id="canvas" x="176.32" y="145.932" width="252.068" height="252.068"/>
</svg>
`;
}
}
解决方案
由于我无法从评论中获得示例,因此我想出了一个不同的解决方案来解决我的问题。尽管这不是我正在寻找的确切答案,但我认为将其发布在这里可能仍然是一个好主意。
不用多说,我的解决方案:
我利用 css 剪辑路径在我的 SVG 元素中显示图像,特别是能够通过绑定来切换它。
<img .src="${this.selectedimg}" style="clip-path: url(#myClip);" width="250" height="250">
<svg>
<defs>
<clipPath id="myClip">
<rect width="250" height="250"/>
</clipPath>
</defs>
</svg>
推荐阅读
- windows - 在 Windows 中激活 conda 环境时如何更改目录
- java - 自动记录在 catch 块中,仅当注释异常变量时,对于 Java 或 Kotlin
- mongodb - 带有条件,排序和限制的mongodb组
- jquery - jQuery + .each() + .post()... 同步运行?
- node.js - 我怎样才能只看到 Sequelize.js 生成的 SQL?
- amazon-web-services - Hyperledger Fabric 应用程序中的 Orderer 断开连接
- node.js - ExpressJS Handlebars 在文件更改时更新部分
- google-api - Ruby on rails:Google API dailyLimitExceededUnreg
- android - 如何在 Android N 中从 URI 获取文件路径
- keras - 自定义损失函数会影响 Keras 中的反向传播吗?