我是d3的新手,我一直在阅读他们的文档并查看示例,但没有什么能满足我的需求。我正在使用react和typescript。
我需要创建2个函数,其中一个应该看起来像这样:
mapColor(value, lowerBoundColor, upperBoundColor)
@param value {float} - A decimal float which is between 0 and 1.
@param lowerBoundColor {string} - A hex color code corresponding to a value of 0.
@param upperBoundColor {string} - A hex color code corresponding to a value of 1.
@returns {string} - A hex color code corresponding to the value parameter passed in.
然后是这样的secound:
linearMap(value, lowerBound, upperBound)
@param value {float} - A decimal float between lowerBound and upperBound.
@param lowerBound {float} - A decimal float which represents the minimum value of the dataset to be clamped.
@param upperBound {float} - A decimal float which represents the maximum value of the dataset to be clamped
@returns {float} - A decimal float between 0 and 1 which corresponds to the value parameter passed in.
这就是我目前所拥有的:
import React from 'react'
import * as d3 from 'd3'
var data = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8,0.9,1]
const mapColor = d3.scaleLinear()
.domain([0,1])
.range(["f4a261", "264653"])
我如何在react中创建这两个函数,以便将来将它们用作组件。
- 有效的十六进制颜色必须以
#
开头。因此,该范围应该是["#f4a261","#2264653"]。可重复使用的函数应该如下所示:
function mapColor(value, lowerBoundColor, upperBoundColor) {
return d3.scaleLinear()
.domain([0,1])
.range([lowerBoundColor, upperBoundColor])(value)
}
function linearMap(value, lowerBound, upperBound) {
return d3.scaleLinear()
.domain([lowerBound, upperBound])
.range([0,1])(value)
}
尽管我认为你应该使用高阶函数来创建这些函数,比如:
function createLinearMap(lowerBound, upperBound) {
return d3.scaleLinear()
.domain([lowerBound, upperBound])
.range([0,1])
}
// Using the HOF
const linearMap = createLinearMap(0, 5)
console.log(linearMap(2)) // 0.4