javascript - 缩放图像以在浏览器中使用画布
问题描述
我正在建立一个网站,用户可以在其中上传图像,并在画布中对其进行编辑。现在这是我的代码:
上传:
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%?
解决方案
我最终只是改变naturalHeight
了offsetHeight
naturalWidth
offsetWidth
推荐阅读
- android - 以编程方式创建 MaterialButton,主题错误
- javascript - 我正在使用这个 datepicker 插件 https://github.com/fengyuanchen/datepicker 。我想指定/突出显示一些日期。我怎样才能做到这一点?
- sas - 在 if 条件下调用不同的调用执行 - SAS
- html - HTML emmet 标签配置
- apache-spark - 我们在哪里可以找到 pyspark 的保存选项文档?
- wso2-am - 错误 - 尝试连接到端点时发生 DataEndpointConnectionWorker 错误。无法为 ssl://localhost:7712 借用客户端
- c# - 将可观察集合的数据访问到另一个可观察集合
- ubuntu - 如何在没有 sudo 访问的情况下在命令行中使程序的输出静音
- latex - LaTeX 参考书目文件中的变音符号
- reporting-services - SSRS 对具有相同值的行求和