canvas转图片
关键点:
canvas.toDataURL(‘image/png’) ,返回生成的图片地址(base64)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>canvas转换成图片</title>
</head>
<body>
<canvas id="myCanvas" width="200" height="200" ></canvas>
<div id="pic"></div>
<script>
//给原有的画布,绘画颜色
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext('2d');
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,200,200);
//创建图片 重点关键canvas.toDataURL('image/png');
var img=new Image();
img.src= canvas.toDataURL('image/png');
//添加到html中
var pic = document.getElementById('pic');
pic.appendChild(img);
</script>
</body>
</html>
图片转canvas
注意:
1,必须是在图片加载完成再执行canvas画图片!!!!
2,ctx.drawImage(img,x,y,width,height)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<img id="pic" src="img/1.jpg" style="width:200px;height:200px;" />
<canvas id="myCanvas" width="200" height="200" style="border:2px solid #dddddd;"></canvas>
</body>
<script>
var image = document.getElementById('pic');
image.onload = function(){
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var w = image.width,
h = image.height;
ctx.drawImage(image,0,0,w,h);
}
</script>
</html>