1

我试过用 react-native-webview 来做,但我无法让我的坐标到中心。同样,我也无法修复高度和宽度。以下是我的代码,任何建议将不胜感激。我试过用 react-native-webview 来做,但我无法让我的坐标到中心。同样,我也无法修复高度和宽度。以下是我的代码,任何建议将不胜感激。

import React, { useEffect, useRef } from 'react'
import { StyleSheet, View, Text, Dimensions } from 'react-native'
import { WebView } from 'react-native-webview';

const WebViewGraph = () => {

  const theCanvas = useRef(null);

  useEffect(() => {
    let xWidth = Dimensions.get('window').width, yHeight = Dimensions.get('window').height

    console.log(xWidth, yHeight);

    // const jscode = `document.getElementById("chart").getContext("2d").fillRect(200, 80, 100, 50)
    // document.getElementById("chart").getContext("2d").strokeRect(80, 20, 100, 50)`;
    const jscode = `document.getElementById("chart").getContext("2d").beginPath()
    document.getElementById("chart").getContext("2d").lineWidth = "5"
    document.getElementById("chart").getContext("2d").strokeStyle = "green"
    document.getElementById("chart").getContext("2d").moveTo(${xWidth/2},0)
    document.getElementById("chart").getContext("2d").lineTo(${xWidth/2},${yHeight})
    document.getElementById("chart").getContext("2d").stroke()
    document.getElementById("chart").getContext("2d").moveTo(0,${yHeight/2})
    document.getElementById("chart").getContext("2d").lineTo(${xWidth},${yHeight/2})
    document.getElementById("chart").getContext("2d").stroke()
    `;

    canvasRef.injectJavaScript(jscode);
  }, [])


  let init = `
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
      </head>
      <body>
        <div>
        <canvas id="chart"></canvas>
        </div>
      </body>
    </html>`

  const onMessage = (data) => {
    console.log(data)
  }

  return (
    <View style={styles.full}>
      <WebView
        ref={theCanvas => (canvasRef = theCanvas)}
        originWhitelist={['*']}
        style={{backgroundColor: 'grey', marginTop: 30, height: 400, width: 800}}
        source={{ html: init, baseUrl: 'web/' }}
        javaScriptEnabled
        domStorageEnabled
        scalesPageToFit
        scrollEnabled={false}
        automaticallyAdjustContentInsets
        onMessage={onMessage}
      />
      {/* <Text>Heyy</Text> */}
    </View>
  )
}

const styles = StyleSheet.create({
  full: {
    flex: 1,
    backgroundColor: '#c3c3c3'
  }
});

export default WebViewGraph;
4

0 回答 0