问题演示:
踏上画布绘画之旅,你发现自己面临着一个令人困惑的难题。通过drawImage()渲染的图像难以理解,留下了空的数据URL。此外,尝试显示画布不会产生可见的结果,控制台仍然保持诡异的沉默。
揭开困惑:
问题的症结在于过早的你的画布艺术的本质。在drawImage() 发挥其魔力之前,图像必须首先完成其加载过程。为了满足 onLoad 的必要性,请采用以下策略:
// Create the image var img = new Image(); // Define the onload function img.onload = function() { // Canvas setup var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; var context = canvas.getContext("2d"); // Draw the image context.drawImage(img, 0, 0); // Obtain the data URL var dataURL = canvas.toDataURL(); // Perform desired actions with dataURL doSomething(dataURL); }; // Set the image source img.src = "http://somerandomWebsite/picture.png";
CORS 难题和缓解:
为了确保无缝 toDataURL() 和 getImageData() 执行,坚持跨域资源共享(CORS)势在必行。通过确保以下场景之一来防止画布“污染”:
重要提示:
边缘情况:图像源中的差异:
如果您的图像来自同一服务器和符合 CORS 的源的混合,请考虑使用onerror 事件处理程序。将跨域作为“匿名”分配给非 CORS 服务器并侦听错误。
function corsError() { this.crossOrigin = ""; this.src = ""; this.removeEventListener("error", corsError, false); } img.addEventListener("error", corsError, false);
以上是为什么我的 Canvas drawImage() 无法渲染图像,如何解决 onload 和 CORS 问题?的详细内容。更多信息请关注PHP中文网其他相关文章!