iOS设备中Canvas toDataURL函数失效问题及解决方法
iOS设备中Canvas绘制图片显示空白的问题
我的应用中的_drawImage函数从Blob加载图片后,调用Canvas的toDataURL函数绘制图片。该代码在Android及桌面浏览器中正常运行,但在iPhone/iPad的所有浏览器中均失效,仅显示空白画面。我尝试过为toDataURL指定图片类型、设置Canvas默认宽高以避免宽高为0,但均无效果,且该代码在Mac端Safari中可正常运行。
问题代码
_drawImage(img) { // console.log("drawimage"); this.setState({ isGenerating: true }); if (img) { fetch(img) .then((r) => r.blob()) .then((blob) => { loadImage( blob, (img) => { if (img.type === "error") { this.setState({ error: true }); // console.log(img, "Error loading image "); } else { const image = new window.Image(); const height = this.props.height; const width = this.props.width; image.src = img.toDataURL('image/jpeg'); console.log(image.src, height, width) image.onload = () => { let offsetX, offsetY, renderableWidth = image.width, renderableHeight = image.height; var imageDimensionRatio = image.width / image.height; var canvasDimensionRatio = width / height; // console.log( // "ratios of image and canvas =", // imageDimensionRatio, // canvasDimensionRatio // ); if (imageDimensionRatio < canvasDimensionRatio) { renderableHeight = height; renderableWidth = image.width * (renderableHeight / image.height); offsetX = (width - renderableWidth) / 2; offsetY = 0; } else if (imageDimensionRatio > canvasDimensionRatio) { renderableWidth = width; renderableHeight = image.height * (renderableWidth / image.width); offsetX = 0; offsetY = (height - renderableHeight) / 2; } else { renderableHeight = height; renderableWidth = width; offsetX = 0; offsetY = 0; } console.log(renderableHeight, renderableWidth, image) this.setState( { image: image, renderableHeight, renderableWidth, imgHeight: image.height, imgWidth: image.width, offsetX, offsetY, height, width, }, () => { this.setState({ isGenerating: false }); } ); }; } }, { orientation: true, canvas: true, } ); }); } }
解决方案
编辑补充:我已通过在loadImage的配置参数中添加maxWidth: 10000(与orientation、canvas参数一同传入)解决该问题,此参数限制iOS设备中的图片宽度,使onload函数正常执行。
内容的提问来源于stack exchange,提问作者Ridham Sharma
相关产品推荐
相关产品推荐

