Я создаю веб-сайт, на котором пользователь может загрузить изображение и отредактировать его на холсте. Прямо сейчас это мой код:
Загрузить:
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 вместе с шириной и высотой.
Canvas:
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](https://i.stack.imgur.com/zfvqu.png)
Меньшее изображение сверху - <ImageContainer/>
. Ниже приведен <CanvasContainer/>
. Как вы можете видеть, хотя я установил ширину на 100% от модального, холст игнорирует это и соответствует ширине и высоте, найденным в базовом изображении.
Если я установлю ширину холста равной 100% от родительского, он обрезает часть изображения. Как я могу заставить холст рисовать масштабированные изображения? Всегда иметь 100% ширины родителя?