HTML5 Canvas显示本地图片实例1、Canvas预览图片实例1
1.前台代码:
<input id="fileOne" type="file" /> <canvas id="canvasOne" class="myCanvas" width="500" height="500"></canvas> <script > //读取本地文件 var inputOne = document.getElementById('fileOne'); inputOne.onchange = function () { //1.获取选中的文件列表 var fileList = inputOne.files; var file = fileList[0]; //读取文件内容 var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function (e) { //将结果显示到canvas showCanvas(reader.result); } } //指定图片内容显示 function showCanvas(dataUrl) { console.info(dataUrl); var canvas = document.getElementById('canvasOne'); var ctx = canvas.getContext('2d'); //加载图片 var img = new Image(); img.onload = function () { ctx.drawImage(img, 0, 0, img.width, img.height); } img.src = dataUrl; // document.body.appendChild(img); } </script>