Jquery &引用;CanvasRenderingContext2D“;将jpeg转换为数据url时出错
我开发了我的chrome应用程序,内容安全政策令人紧张。我想从json(我不知道字符串/对象/数组)中获取jpeg图像,但csp每次都阻止了我。现在我知道使用数据链接更容易,所以 不幸的是,这不起作用。错误消息如下:Jquery &引用;CanvasRenderingContext2D“;将jpeg转换为数据url时出错,jquery,canvas,jpeg,drawimage,data-url,Jquery,Canvas,Jpeg,Drawimage,Data Url,我开发了我的chrome应用程序,内容安全政策令人紧张。我想从json(我不知道字符串/对象/数组)中获取jpeg图像,但csp每次都阻止了我。现在我知道使用数据链接更容易,所以 不幸的是,这不起作用。错误消息如下: Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': No function was found that matched the signature provided.
Uncaught TypeError:
Failed to execute 'drawImage' on 'CanvasRenderingContext2D':
No function was found that matched the signature provided.
我希望有人能帮我:)
对不起,我的英语不好您的代码有3个问题:
var img=new image()代码>
img.onload
回调中使用drawImage
和toDataURL
。这允许在尝试使用图像之前将其完全加载。这也意味着除了返回dataURL之外,还必须将使用dataURL的所有代码放在onload回调中。(是的,我知道,这很混乱,但你必须这样做,否则图像无法完全加载)toDataURL
,您的图像必须与您的网页位于同一域中。如果它们是不同的域,toDataURL
将因安全错误而失败。此安全问题是一个涉及的主题,因此您可以在此处了解避免安全错误的必要方法:image/jpeg
,因此您需要更改正则表达式
以下是您的代码重构,并使用以不创建安全错误的方式托管的映像:
var canvas=document.getElementById(“canvas”);
var ctx=canvas.getContext(“2d”);
var cw=画布宽度;
var ch=画布高度;
var img=新图像();
img.crossOrigin='anonymous';
img.onload=启动;
img.src=”https://dl.dropboxusercontent.com/u/139992952/multple/sun.png";
函数start(){
canvas.width=img.width;
canvas.height=img.height;
ctx.drawImage(img,0,0);
var dataURL=canvas.toDataURL();//png是默认格式
dataURL=dataURL.replace(/^data:image\/(png | jpeg);base64,/,“”);
//您的dataURL现在可用
//根据需要使用它
警报('dataURL为'+dataURL.length+'个字符,长度以:'+dataURL.substring(0,20))开头);
}
body{背景色:象牙色;填充:10px;}
#画布{边框:1px纯红;}
什么是img
?提供相关代码
Uncaught TypeError:
Failed to execute 'drawImage' on 'CanvasRenderingContext2D':
No function was found that matched the signature provided.