HTML5 Canvas画五角星图并保存为图片 - html教程,html5教程,html知识积累 - CSS模版园-免费网站模版下载
当前位置 CSS模版园 >> 网站制作 >> html >> HTML5 Canvas画五角星图并保存为图片

原创HTML5 Canvas画五角星图并保存为图片

HTML5 Canvas画五角星图并保存为图片

采用canvas的toDataURL()函数来获取canvas图片数据,保存下载

demo.jpg

<canvas id="thecanvas" height="300" width="400"></canvas>
<button id="btnSave">保存图片</button>
<button id="btnDown">下载图片</button>

<script>
	//canvas画图
	draw();
	function draw() {
		var canvas = document.getElementById("thecanvas");
		if (canvas == null)
			return false;
		var context = canvas.getContext("2d");
		context.fillStyle = "#EEEEFF";
		context.fillRect(0, 0, 400, 300);
		context.shadowOffsetX = 10;
		context.shadowOffsetY = 10;
		context.shadowColor = "rgba(100,100,100,0.5)";
		context.shadowBlur = 5;
		//图形绘制
		context.translate(0, 50);
		for (var i = 0; i < 3; i++) {
			context.translate(50, 50);
			create5Star(context); //画五角星
			context.fill();
		}
	}
	//保存按钮click
	document.getElementById("btnSave").onclick = function () {
		var image = document.getElementById("thecanvas").toDataURL("image/png");
		window.open("about:blank", "保存canvas为图片").document.write("<img src=" + image + " alt=canvas图片 />");
	}
	//下载按钮click
	document.getElementById("btnDown").onclick = function () {
		var myCanvas = document.getElementById("thecanvas");
		var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream;Content-Disposition: attachment;filename=canvas.png");
		window.location.href = image;
	}
	//画五角星
	function create5Star(context) {
		var n = 0;
		var dx = 100;
		var dy = 0;
		var s = 50;
		//创建路径
		context.beginPath();
		context.fillStyle = "rgba(255,0,0,0.5)";
		var x = Math.sin(0);
		var y = Math.cos(0);
		var dig = Math.PI / 5 * 4;
		for (var i = 0; i < 5; i++) {
			var x = Math.sin(i * dig);
			var y = Math.cos(i * dig);
			context.lineTo(dx + x * s, dy + y * s);
		}
		context.closePath();
	}
</script>

原创文章内容原创,转载请注明出处:cssteach.com

声明本站所有资源仅供学习与参考,请勿用于商业用途。转载请注明来自:cssteach.com

原文http://cssteach.com/html/show-9-120.html

若文章内容有错误或无法下载,请在回复中说明(可无需登录,直接评论)

最新文章

图文

热门网站模版