|

楼主 |
发表于 2023-12-11 12:23:15
|
显示全部楼层
最终代码
- // index.js
- Page({
- data: {
- editText: 'concentration'
- },
- //const maxValue = 10;
- inputChange(event) {
- //console.log(event.detail.value) // 输出input的值
- // 可以将获取的值传递给其他方法
- var y = (-8.678*Math.log(event.detail.value)-44.860)/100+0.36768;
- this.setData({
- editText: Math.round(y).toString()+" mg/L",
- })
- this.changeColor(y,event.detail.value)
-
- },
- onReady: function () {
- this.changeColor('#ff0000',"input current")
- },
- changeColor: function (value,text) {
- wx.createSelectorQuery() .select('#myCanvas').fields({ node: true, size: true })
- .exec((res) => {
- // Canvas 对象
- const canvas = res[0].node
- console.log()
- // Canvas 画布的实际绘制宽高
- const renderWidth = res[0].width
- const renderHeight = res[0].height
- // Canvas 绘制上下文
- const ctx = canvas.getContext('2d')
- // 初始化画布大小
- const dpr = wx.getWindowInfo().pixelRatio
- canvas.width = renderWidth* dpr
- canvas.height = renderHeight* dpr
- ctx.scale(dpr, dpr)
- const x = 50, y = 50, w = 200, h = 200, r = 10;
- const BarNum = 50;
- ctx.beginPath();
- ctx.moveTo(x + r, y);
- ctx.lineTo(x + w - r, y);
- ctx.arcTo(x + w, y, x + w, y + r, r);
- ctx.lineTo(x + w, y + h - r);
- ctx.arcTo(x + w, y + h, x + w - r, y + h, r);
- ctx.lineTo(x + r, y + h);
- ctx.arcTo(x, y + h, x, y + h - r, r);
- ctx.lineTo(x, y + r);
- ctx.arcTo(x, y, x + r, y, r);
- ctx.closePath();
- ctx.fillStyle = this.getColorMap(value,0,10);
- ctx.fill();
- for(let i = 0; i < BarNum; i++){
- this.drawColorBar(ctx,BarNum-i,Math.floor(h/BarNum),this.getColorMap(i,0,BarNum));
- }
- //ctx.textAlign = "center";
- //ctx.font="24px Verdana";
- //ctx.fillStyle = "#FFFF00";
- //ctx.fillText(text,150,160);
- })
-
-
- },
- drawColorBar: function (ctx,i,h1,color) {
- const x1 = 260, y1 = 50, w1 = 20 ;
- ctx.fillStyle = color;ctx.fillRect(x1,y1+i*h1,w1,h1);
- },
- getColorMap:function(colorNumber,startNum,EndNum){
- const topColorR = 0x00,topColorG = 0x00,topColorB = 0xFF;
- const bottomColorR = 0xFF ,bottomColorG = 0x00,bottomColorB = 0x00 ;
- var ratio = (colorNumber-startNum)/(EndNum-startNum);
- var R = Math.floor(topColorR+(bottomColorR-topColorR)*ratio);
- var G = Math.floor(topColorG+(bottomColorG-topColorG)*ratio);
- var B = Math.floor(topColorB+(bottomColorB-topColorB)*ratio);
- return "#"+this.NumToString(R)+this.NumToString(G)+this.NumToString(B);
- },
- NumToString:function(num) {
- var numlen = num.toString(16).length; //得到num的长度
- var strChar = "0"; //空缺位填充字符
- var str = num.toString(16);
- //console.log(str)
- for (var i = 0; i < 2 - numlen; i++) {
- str = strChar + str;
- }
- return str;
- }
- })
复制代码 |
|