React Native Canvas

思路:React-Native自己是没有Canvas,可以利用react-native-webview注入html做一个Canvas,把写入Webviewhtml作为可变的字符串,每写一条canvas就在字符串上的script标签里添加对应的语句,每一次添加都是异步的,通过onMessage去获取Webview往外传的值

  1. 初始化一个html页面
    window.onload里去执行我们要添加的js字符串
private state: State = {
    js: `const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
window.document.body.appendChild(canvas);
`,
    end: '', // js尾巴
    style: {width: 1, height: 1}
};
 {

   }}
   source={{
         html: `
              
              
                  
                  
              
              
              
              
              `
   }}
/>
  1. 写js的代码
    设置宽高
    public setStyle = (options: { width: number; height: number }, ratio = 1) => {
        return new Promise((resolve) => {
            const {style, js} = this.state;
            this.setState({
                style: {...style, ...options},
                js: js + `canvas.width = ${options.width * ratio};
canvas.height = ${options.height * ratio};
`
            } as State, () => resolve(this));
        });
    };
  1. 特殊处理
    画图片,需要在图片image.load完成之后写别的js
private changeJs = (newJs: string, callback: () => void, newEnd?: string) => {
    const {js, end} = this.state;
    this.setState({
        js: js + newJs,
        end: end + (newEnd || "")
    } as State, callback);
};
// 设置图片
public setImage = (src: string, x: number, y: number, w: number, h: number) => {
    const imageName = this.randCode(); // 随机字符串
    return new Promise((resolve) => {
        this.changeJs(`const ${imageName} = new Image();
${imageName}.src = "${src}";
${imageName}.setAttribute("crossOrigin", 'Anonymous');
${imageName}.onload = function()  {
     ctx.drawImage(${imageName}, ${x}, ${y}, ${w}, ${h});
     window['ReactNativeWebView'] && window['ReactNativeWebView'].postMessage(JSON.stringify({
         onKey: "${imageName}",
     }));
// 把尾巴 }; 作为一段放在最后面的
`, () => resolve(this), `};
`);
    });
};
  1. 获取webview的值(window.ReactNativeWebView.postMessage)
    打印

你可能感兴趣的:(React Native Canvas)