- 使用 Canvas 的 toDataURL() 方法,將 Canvas 繪出的圖形,轉成 Data URI scheme 形式。
- HTML5 的連結 a 元素,新增 dowload 屬性,有強制下載的效果。
只要設定 dowload 屬性,並將產生的 Data URI 設定到 href 屬性,即可。
但 IE 目前( IE11 之前)不支援 dowload 屬性,所以此方法對 IE 無效。
dowload 屬性在各瀏覽器的支援:http://caniuse.com/#feat=download
範例:
<canvas id="myCanvas" width="160" height="160"></canvas>
<a href="#" download="test.png" onclick="this.href=document.getElementById('myCanvas').toDataURL()">下載</a>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = 80;
var centerY = 80;
var radius = 70;
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 2;
context.strokeStyle = '#000000';
context.stroke();
</script>
參考:
http://www.w3.org/TR/html5/embedded-content-0.html#dom-canvas-todataurl
http://www.w3.org/TR/html5/links.html#attr-hyperlink-download
沒有留言:
張貼留言