toDataURL을 사용하여 HTML5 Canvas의 내용을 이미지로 저장

不言
풀어 주다: 2018-06-22 14:33:03
원래의
2143명이 탐색했습니다.

HTML5 Canvas의 콘텐츠를 이미지로 저장하는 주요 아이디어는 이를 달성하기 위해 Canvas 자체 API인 toDataURL()을 사용하는 것입니다. 관심 있는 친구들은 다음을 참고하면 좋습니다. 당신에게. 주요 아이디어는 이를 달성하기 위해 Canvas의 자체 API인 toDataURL()을 사용하는 것입니다.
HTML + JavaScript 코드는 매우 간단합니다.

<html> 
<meta http-equiv="X-UA-Compatible" content="chrome=1"> 
<head> 
<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(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)"; // black color 
ctx.fillText("Gloomyfish - Demo", 50, 50); 
} 
function bindButtonEvent(element, type, handler) 
{ 
if(element.addEventListener) { 
element.addEventListener(type, handler, false); 
} else { 
element.attachEvent(&#39;on&#39;+type, handler); 
} 
} 
function saveImageInfo () 
{ 
var mycanvas = document.getElementById("thecanvas"); 
var image = mycanvas.toDataURL("image/png"); 
var w=window.open(&#39;about:blank&#39;,&#39;image from canvas&#39;); 
w.document.write("<img src=&#39;"+image+"&#39; alt=&#39;from canvas&#39;/>"); 
} 
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"> 
<p> 
<canvas width=200 height=200 id="thecanvas"></canvas> 
<button id="saveImageBtn">Save Image</button> 
<button id="downloadImageBtn">Download Image</button> 
</p> 
</body> 
</html>
로그인 후 복사

작동 효과는 다음과 같습니다

위 내용은 모두의 학습에 도움이 되기를 바랍니다.

관련 권장 사항:

HTML5 정보 캔버스 이벤트 처리

angularJS와 캔버스 그리기 구현의 결합

위 내용은 toDataURL을 사용하여 HTML5 Canvas의 내용을 이미지로 저장의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!