首先祝大家新年快乐,2016好运!!!
在这里问个之前问的问题,
我下面显示canvas
生成的base64
图片后是黑色背景这是怎么回事?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
body{margin: 0;padding: 0;}
.box{width:100%;overflow:hidden;margin: 0 auto;}
.piclistbox{width: 50%;float: left;overflow: hidden;border: 1px solid red;box-sizing: border-box;height:300px;}
.canvasbox{width: 50%;float:right;overflow: hidden;border: 1px solid red;box-sizing: border-box;height:300px;}
</style>
</head>
<body>
<div class="box">
<div class="piclistbox">
<canvas id="pic_canvas" width="400" height="400"></canvas>
</div>
<div class="canvasbox">
<img src="#" id="imgshow"/>
</div>
</div>
<input type="button" value="生成" class="btnpoptailor"></input>
</body>
<script type="text/javascript">
var canvas = document.getElementById('pic_canvas');
var img = new Image();
var _this = this;
img.src = "http://img1.3lian.com/img013/v1/83/d/1.jpg";
img.onload = function(){
var ctx = canvas.getContext("2d");
ctx.clearRect(0,0,canvas.width,canvas.height);
if(img.height > 400){
img.width *= 400 / img.height;
img.height = 400;
}
if(img.width > 400){
img.height *= 400 / img.width;
img.width = 400;
}
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
}
var imgUrl = canvas.toDataURL("image/jpeg");
document.getElementById("imgshow").setAttribute('src',imgUrl);
</script>
</html>
你这段代码有两个问题,
一是
图片跨域,请使用同域名下的图片或者用base64。
img.src = "http://img1.3lian.com/img013/v1/83/d/1.jpg";
图片跨域,输出不了,所以一片黑。
二是
这段代码放在了img.onload外面,这样图片还没有画好就开始转成base64了当然是一片黑,请把这段代码放到img.onload里面。