一 介绍
toDataURL()是canvas中将图片的二进制格式转为dataURL格式使用的方法。
dataURL是将数据按base64进行编码,它是一种保存二进制的方式。
下面通过这种方法输出位图。
二 代码下载
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
- <meta http-equiv="Content-Type" content="text/html; charset=GBK" />
- <title> 位图输出 </title>
- </head>
- <body>
- <h2> 位图输出 </h2>
- <canvas id="mc" width="360" height="280"
- style="border:1px solid black"></canvas>
- <img id="result" src="" alt="图片输出"/>
- <script type="text/javascript">
- // 获取canvas元素对应的DOM对象
- var canvas = document.getElementById('mc');
- // 获取在canvas上绘图的CanvasRenderingContext2D对象
- var ctx = canvas.getContext('2d');
- ctx.save();
- ctx.translate(30 , 20);
- var image = new Image();
- image.src = "wjc.gif";
- image.onload = function()
- { 下载
- // 创建位图填充
- imgPattern = ctx.createPattern(image, "repeat");
- // 设置使用位图填充作为填充颜色
- ctx.fillStyle = imgPattern;
- // 填充一个矩形
- ctx.fillRect(0 , 0 , 160 , 80);
- // 恢复坐标系统
- ctx.restore();
- // 平移坐标系统
- ctx.translate(280 , 160)
- ctx.beginPath();
- // 添加圆弧
- ctx.arc(0 , 0 , 80 , 0 , Math.PI * 2 , true);
- ctx.closePath();
- ctx.lineWidth = 12;
- // 设置使用位图填充作为边框颜色
- ctx.strokeStyle = imgPattern;
- ctx.stroke();
- // 使用img元素来显示Canvas的输出结果
- document.getElementById("result").src = canvas.toDataURL("image/png");
- }
- </script>
- </body>
- </html>
三 运行结果