在画布中打开本地图像 [英] Open local image in canvas

查看:107
本文介绍了在画布中打开本地图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个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'/>


解决方案

不支持所有浏览器(IE和Opera AFAIK)但您可以使用 File API 获取数据URI

 函数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'm trying to make an javascript image color picker. It is possible to open local image in canvas, without uploading it to server ?

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' />

解决方案

Not supported in all browser (IE and Opera AFAIK) but you could get a data URI using the File API

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 here as an example.

这篇关于在画布中打开本地图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆