javascript 在画布中打开本地图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10209227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:02:29 来源:igfitidea点击:
Open local image in canvas
提问by user1093555
i'm trying to make an javascript image color picker. It is possible to open local image in canvas, without uploading it to server ?
我正在尝试制作一个 javascript 图像颜色选择器。可以在画布中打开本地图像,而无需将其上传到服务器吗?
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
}
img.src = $('#uploadimage').val();
}
<input type='file' name='img' size='65' id='uploadimage' />
回答by Phil Parsons
Not supported in all browser (IE and Opera AFAIK) but you could get a data URI using the File API
并非所有浏览器(IE 和 Opera AFAIK)都支持,但您可以使用File API获取数据 URI
function draw() {
var ctx = document.getElementById('canvas').getContext('2d')
, img = new Image()
, f = document.getElementById("uploadimage").files[0]
, url = window.URL || window.webkitURL
, src = url.createObjectURL(f);
img.src = src;
img.onload = function(){
ctx.drawImage(img,0,0);
url.revokeObjectURL(src);
}
}
<input type='file' name='img' size='65' id='uploadimage' />
I added a fiddle hereas an example.