在撰写本文时,Kotlin 似乎没有类似于 kotlinx.html 的 svg 库。
话虽如此,通过逆向工程 kotlin-react 和 kotlinx.html 交互的方式,可以在 kotlin-react 中创建任意 xml。
或者只使用基本反应函数。
方法一:使用kotlinx.html
import kotlinx.html.HTMLTag
import react.*
import react.dom.*
// a custom tag builder, reuses the tag(...) function from kotlin-react and HTMLTag from kotlinx.html
inline fun RBuilder.custom(tagName: String, block: RDOMBuilder<HTMLTag>.() -> Unit): ReactElement = tag(block) {
HTMLTag(tagName, it, mapOf(), null, true, false) // I dont know yet what the last 3 params mean... to lazy to look it up
}
// example use
inline fun RBuilder.mySVG(animTime: Double) {
svg() {
attrs["width"] = "800"
attrs["height"] = "600"
attrs["viewBox"] = "0 0 800 600"
custom("circle") {
attrs["cx"] = 150
attrs["cy"] = 150
attrs["r"] = 50.0 + sin(animTime) * 50.0
attrs["style"] = object {
val stroke = "black"
val fill = "red"
}
}
}
}
方法2:使用react.dom中的child和createElement
open class CircleProps (
val cx: Int,
val cy: Int,
val r: Int,
val stroke: String,
val fill: String,
val strokeWidth: Int
): RProps {
}
inline fun RBuilder.mySVG2(animTime: Double) {
svg() {
attrs["width"] = "800"
attrs["height"] = "600"
attrs["viewBox"] = "0 0 800 600"
child(createElement("circle", CircleProps(150,150, 50.0 + sin(animTime) * 50.0, "black", "blue", 3)))
}