<!DOCTYPE html>
<html lang="en">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
window.onload = function() {
draw();
// var saveButton = document.getElementById("saveImageBtn");
// bindButtonEvent(saveButton, "click", saveImageInfo);
var dlButton = document.getElementById("downloadImageBtn");
bindButtonEvent(dlButton, "click", saveAsLocalImage);
};
function draw(){
var canvas = document.getElementById("thecanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(15, 46, 138, 0.2)";
/* *.fillRect(x,y,width,height);绘制“已填色”的矩形
xy 矩形左上角的 xy , width height矩形的宽度高度像素*/
ctx.fillRect(11,11,200,200);
ctx.fillStyle = "rgba( 0, 146, 38, 0.5)";
/* context.fillStyle//填充的样式 context.lineWidth//图形边框宽度
其中,fillStyle后面,颜色的表示方式如下(和css基本相同):
直接用颜色名称:"red" "green" "blue"; 十六进制颜色值: "#EEEEFF"
rgb(1-255,1-255,1-255); rgba(1-255,1-255,1-255,透明度)*/
ctx.fillRect(58, 74, 125, 100);
ctx.fillStyle = "rgba( 10, 10, 110, 11)"; // black color
ctx.fillText("填充1字体", 50, 50);
}
function bindButtonEvent(element, type, handler)
{
if(element.addEventListener) {
element.addEventListener(type, handler, false);
} else {
element.attachEvent('on'+type, handler);
}
}
// function saveImageInfo ()
// {
// var mycanvas = document.getElementById("thecanvas");
// var image = mycanvas.toDataURL("image/png");
// var w=window.open('about:blank','image from canvas');
// w.document.write("<img src='"+image+"' alt='from canvas'/>");
// }
function saveAsLocalImage () {
var myCanvas = document.getElementById("thecanvas");
// here is the most important part because if you dont replace you will get a DOM 18 exception.
// var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream;Content-Disposition: attachment;filename=foobar.png");
var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
window.location.href=image; // it will save locally
}
</script>
</head>
<body bgcolor="#E6E6FA">
<div style="text-align:center">
<!-- 表格强制居中-->
<table border="1" align="center">
<tr>
<td>
<div>
<canvas width=400 height=400 id="thecanvas"></canvas>
<!-- <button id="saveImageBtn">Save Image</button>-->
</div></td>
</tr>
<tr>
<td>
<button id="downloadImageBtn">下载图片</button>
</td>
</tr>
</table>
</div>
</body>
</html>
|