首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何设置自定义大小,以导出图像中的react konva?

如何设置自定义大小,以导出图像中的react konva?
EN

Stack Overflow用户
提问于 2022-03-27 04:48:20
回答 1查看 468关注 0票数 3

我已经创建了一个响应阶段使用react konva,但我无法找到一种方法来设置一个自定义大小来导出图像。通常情况下,右击并保存图像就像当时窗口中的大小一样。我想要添加一个按钮来下载图像,但是我无法设置这样的方法,因为我刚开始使用响应钩子,我无法找到设置数据URL的方法。请参阅此

代码语言:javascript
运行
复制
    import React, { Component, useState, useRef, useCallback } from "react";
    import { render } from "react-dom";
    import { Stage, Layer, Text, Image, Rect, Transformer, Circle, Line } from "react-konva";
    import card01 from "../images/01.jpg"
    import useImage from "use-image";
    import "./styless.css";
    import Button from '@mui/material/Button';
    
    const WIDTH = 875;
    const HEIGHT = 500;
    const ZOOM = 1;
    
    class Canvas extends Component {
      state = {
        stageWidth: WIDTH,
        zoom: 1,
      };
    
      render() {
        
        const { containerWidth } = this.props;
        var scale = (containerWidth / WIDTH) * ZOOM;
        let width = WIDTH * scale;
        let height = HEIGHT * scale;
        console.log({ containerWidth, width, height, scale });
    
        const LionImage = () => {
            const [image] = useImage(card01);
            return <Image image={image} width={width} height={height} scale={scale}/>;
          };
    
        return (
          <div style={{ width: `100%`, border: "1px solid grey" }}>
          
            <Stage width={width} height={height} scale={scale}>
              <Layer>
              <LionImage />
              <Text
                x={containerWidth / 10}
                y={scale*35}
                text="Some text"
                fontSize={28}
                fontFamily="Poppins"
                fill="gray"
                scaleX={scale}
                scaleY={scale}
    
                width={width}
                height={height}
              />
              </Layer>
            </Stage>
          </div>
        );
      }
    }
    
    class App extends Component {
      state = {
        zoom: 1
      };
      componentDidMount() {
        this.checkSize();
        window.addEventListener("resize", this.checkSize);
      }
    
      componentWillUnmount() {
        window.removeEventListener("resize", this.checkSize);
      }
    
      checkSize = () => {
    
        const containerWidth = this.container.offsetWidth;
        const containerHeight = this.container.offsetHeight;
        this.setState({ ...this.state, containerWidth, containerHeight });
    
      };
    
      render() {
        const pWidht = this.state.containerWidth
          ? `${this.state.containerWidth * this.state.zoom}px`
          : "100%";
    
        return (
            <>
          
            <div
                style={{ width: "80%", height: "100%", left: "10%", position: "absolute" }}
                ref={(node) => {
                    this.container = node;
                } }
            >
                <div style={{ overflow: "auto;", width: `${pWidht}` }}>
                    <div>
                        <Button color="inherit" size="small" variant="outlined" sx={{boxShadow:3}} style={{marginTop:"20px",marginRight:"10px",marginBottom:"10px", fontSize:"12pt", color:"white"}}
                            type="button"
                            value="+"
                            onClick={() => this.setState({ ...this.state, zoom: this.state.zoom + 0.2 })}> + </Button>
                        <Button color="inherit" size="small" variant="outlined" sx={{boxShadow:3}} style={{marginTop:"20px",marginRight:"10px",marginBottom:"10px", fontSize:"12pt", color:"white"}}
                            type="button"
                            value="-"
                            onClick={() => this.setState({ ...this.state, zoom: this.state.zoom - 0.2 })} > - </Button>
                    </div>
                    <Canvas containerWidth={pWidht.replace("px", "")} />
                </div>
            </div>
      
            </>
        );
      }
    }
    
    const X = () => {
      return <App />;
    };
    
    render(<X />, document.getElementById("root"));
    export default App;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-27 05:25:31

您需要使用refStage并获取图像URL并下载它。

在画布组件中使用createRef.创建ref

代码语言:javascript
运行
复制
  constructor(props) {
    super(props);
    this.stageRef = createRef(null);
  }

Stage.添加到

代码语言:javascript
运行
复制
<Stage  ... ref={this.stageRef}>
        ...
        ...
</Stage>

ref.

  • 添加了以下两个实用程序函数:downloadURI作为文件下载图像;handleExport

  • 中获取数据URI

代码语言:javascript
运行
复制
  downloadURI = (uri, name) => {
    var link = document.createElement("a");
    link.download = name;
    link.href = uri;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  handleExport = () => {
    const uri = this.stageRef.current.toDataURL();
    this.downloadURI(uri, "stage.png");
  };

  1. 添加一个新按钮,将单击处理程序设置为handleExport函数.

代码语言:javascript
运行
复制
<button onClick={this.handleExport}>Download</button>

工作实例:

手动设置图像大小

使用以下实用程序函数,它将使用从Stage width接收到的数据URI更改图像heightref

代码语言:javascript
运行
复制
resizeImage = (url, width, height, callback) => {
  var sourceImage = new Image();

  sourceImage.onload = function () {
    var canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    canvas.getContext("2d").drawImage(sourceImage, 0, 0, width, height);
    callback(canvas.toDataURL());
  };

  sourceImage.src = url;
};

// fixed the image size to 200px by 200px before download
handleExport = () => {
  const uri = this.stageRef.current.toDataURL();
  this.resizeImage(uri, 200, 200, (sizeUpdatedDataURL) => {
    this.downloadURI(sizeUpdatedDataURL, "stage.png");
  });
};

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71633768

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档