DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML5教程
使用 toDataURL 將 Canvas 內容輸出為圖片
編輯:HTML5教程     

toDataURL 的作用

Canvas 可透過 toDataURL() 將目前畫布內容轉成圖片資料,再觸發下載或在新視窗開啟。

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(125, 46, 138, 0.5)";
  ctx.fillRect(25,25,100,100);
  ctx.fillStyle = "rgba(0, 146, 38, 0.5)";
  ctx.fillRect(58,74,125,100);
  ctx.fillStyle = "rgba(0, 0, 0, 1)";
  ctx.fillText("Gloomyfish - Demo", 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");
  var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
  window.location.href = image;
}

使用時只需將 canvas 的 id 指向目标畫布,即可把繪圖結果轉成 PNG 圖片。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved