使用drawImage()作为图像下载画布 [英] Download Canvas with drawImage() as Image
本文介绍了使用drawImage()作为图像下载画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当doCanvas()函数仅包含fillText()时,下载画布作为图像的代码非常有用。但是,当我尝试(本地和远程)通过drawImage()绘制图像时,不幸的是它不起作用。
Hi,
Your code for downloading canvas as image works perfect when doCanvas() function includes only fillText(). But, when I tried (both local and remote) to draw an image via drawImage() it doesn't work unfortunately.
<img id="soundc_icon" src="http://i1.wp.com/www.slate.com/content/dam/slate/articles/life/dear_prudence/PRUDIE_STANDING_MEDIUM.jpg.CROP.rectangle-large.jpg?resize=200%2C133"/>
<canvas width="500" height="300" id="canvas">Sorry, no canvas available</canvas>
<a id="download">Download as .PNG</a>
<script>
/**
* Ken Fyrstenberg Nilsen
* Abidas Software
*/
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
var img = document.getElementById("soundc_icon");
/**
* Demonstrates how to download a canvas an image with a single
* direct click on a link.
*/
function doCanvas() {
/* draw something */
ctx.fillStyle = '#f90';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#fff';
ctx.font = '60px Lucida Grande';
ctx.fillText('Code Project', 10, canvas.height / 2 - 15);
ctx.font = '26px Lucida Grande';
ctx.fillText('Click link below to save this as image', 15, canvas.height / 2 + 35);
ctx.drawImage(img,10,10);
}
/**
* This is the function that will take care of image extracting and
* setting proper filename for the download.
* IMPORTANT: Call it from within a onclick event.
*/
function downloadCanvas(link, canvasId, filename) {
link.href = document.getElementById(canvasId).toDataURL();
link.download = filename;
}
/**
* The event handler for the link's onclick event. We give THIS as a
* parameter (=the link element), ID of the canvas and a filename.
*/
document.getElementById('download').addEventListener('click', function() {
downloadCanvas(this, 'canvas', 'test.png');
}, false);
/**
* Draw something to canvas
*/
doCanvas();
</script>
推荐答案
这篇关于使用drawImage()作为图像下载画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文