首页 > 解决方案 > 缩放图像以在浏览器中使用画布

问题描述

我正在建立一个网站,用户可以在其中上传图像,并在画布中对其进行编辑。现在这是我的代码:

上传:

const handleChange = async e => {
    const {files} = e.target;
    const file = files[0];
    setImage(file);
};

<input id={'fileInput'} value={filePath} 
   onChange={handleChange} type="file" accept=".jpeg, .jpg" capture="camera"/>

取尺寸:

componentDidMount() {
    const reader = new FileReader();
    reader.onload = async (e) => {
        const {result} = e.target;
        const {setEditedImage, setCanvasWidth, setCanvasHeight, setOriginalImage} = this.props;
        const image = document.getElementById('image');
        setOriginalImage(result);
        setEditedImage(result);
        if (image) {
            const {naturalHeight, naturalWidth} = image;
            setCanvasWidth(naturalWidth);
            setCanvasHeight(naturalHeight);
        }
    };
    try {
        reader.readAsDataURL(this.props.image);
    } catch (e) {
        console.log('caught', e);
    }
}

<img style={{display: 'block', width: '100%'}} id={'image'} src={this.props.originalImage} alt={''}/>

所以在这里,我将 dataURL 与宽度和高度一起放入 Redux 状态。

帆布:

componentWillReceiveProps(nextProps) {
    this.drawImage(nextProps.width, nextProps.height, nextProps.editedImage)
}

drawImage = (width, height, image) => {
    this.ctx = document.getElementById('canvas').getContext('2d');
    const img = new Image();
    img.onload = () => {
        this.ctx.drawImage(img, 0, 0, width, height);
    };
    img.src = image
};

handleClick = (e) => {
    const makeDrawing = (canvas) => {
        this.Draw(e.pageX - 305  - canvas.offsetLeft, e.pageY-100 - canvas.offsetTop);
    };
    const {textLength, tasks} = this.props;
    const canvas = document.getElementById('canvas');
    if (textLength === 'over200' || textLength === 'under200') {
        if (tasks !== 0) {
            return null;
        }
    }
    makeDrawing(canvas);
    this.props.setTasks(tasks + 1);

    const img = new Image();
    img.src = canvas.toDataURL();
    this.props.setImageURL(canvas.toDataURL());
    this.props.setEditedImage(img);
};

Draw = (x, y) => {
    this.ctx.beginPath();
    this.ctx.strokeStyle = 'red';
    this.ctx.lineWidth = 5;
    // x, y are the cords, 5 is the radius of the circle and the last 2 things specify full circle.
    this.ctx.arc(x, y, 5, 0, 2 * Math.PI);
    this.ctx.stroke();
    this.lastX = x;
    this.lastY = y;
};

<canvas onClick={this.handleClick} width={this.props.width} height={this.props.height} id={'canvas'}/>

问题是这样的:

在此处输入图像描述

顶部较小的图像是<ImageContainer/>. 下面的一个是<CanvasContainer/>。如您所见,即使我将宽度设置为模态框的 100%,画布仍会忽略这一点,并使用基本图像中的宽度和高度。

如果我将画布宽度设置为父级的 100%,它会剪切部分图像。如何让画布绘制缩放图像?总是有父级宽度的 100%?

标签: javascriptcssreactjscanvas

解决方案


我最终只是改变naturalHeightoffsetHeightnaturalWidthoffsetWidth


推荐阅读