缩放图像以供浏览器中的画布使用

时间:2019-01-17 11:00:50

标签: javascript css reactjs canvas

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

上传:

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'}/>

问题是这样的:

enter image description here

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

如果我将画布宽度设置为父级的100%,则会裁切其一部分图像。如何获得画布以绘制缩放图像?总是有父母宽度的100%?

1 个答案:

答案 0 :(得分:0)

我最终只是将naturalHeight更改为offsetHeight,将naturalWidth更改为offsetWidth