2017-04-17 86 views
1

我想绘制画布,也想下载,它与下载和文本工作正常,但我想添加图像也如何做到这一点?下面给出的代码绘制画布并将其作为PNG下载,但如何在画布中添加图像标题段落在里面?如何下载图像和画布?

这里是HTML:

<canvas width="500" height="300" id="canvas">Sorry, no canvas available</canvas> 
<a id="download">Download as image</a> 

这里是jQuery的:

<script type="text/javascript"> 

var canvas = document.getElementById('canvas'), 
    ctx = canvas.getContext('2d'); 

function doCanvas() { 
    /* draw something */ 
    ctx.fillStyle = '#B00000'; 
    ctx.fillRect(0, 0, canvas.width, canvas.height); 
    ctx.fillStyle = '#fff'; 
    ctx.font = '60px sans-serif'; 
    ctx.fillText('Some heading', 10, canvas.height/2 + 10); 
    ctx.fillText('Some Paragraph', 15, canvas.height/2 + 50); 
} 


function downloadCanvas(link, canvasId, filename) { 
    link.href = document.getElementById(canvasId).toDataURL(); 
    link.download = filename; 
} 

document.getElementById('download').addEventListener('click', function() { 
    downloadCanvas(this, 'canvas', 'test.png'); 
}, false); 

doCanvas(); 
</script> 
+0

问题如何从画布下载已经回答ERED。 http://stackoverflow.com/questions/11112321/how-to-save-canvas-as-png-image – SeregPie

+0

我的代码下载为PNG运行良好,但我想添加一个图像在它像http:// stackoverflow .com/questions/29657681/add-image-canvas-through-jquery,但它不起作用 – Zarttash

回答

0
var canvas = document.getElementById('canvas'), 
    ctx = canvas.getContext('2d'); 
    **var background = new Image(); 
background.src = "your image path";** 

你必须创建一个变量,然后如果你想帆布不是用它作为

的背景图片
function doCanvas() { 
    ctx.fillRect(0, 0, canvas.width, canvas.height); 
**ctx.drawImage(background,400,100,60,90);** 
    ctx.fillStyle = '#fff'; 
    ctx.font = '60px sans-serif'; 
    ctx.fillText('Some heading', 10, canvas.height/2 + 10); 
    ctx.fillText('Some Paragraph', 15, canvas.height/2 + 50); 
} 


function downloadCanvas(link, canvasId, filename) { 
    link.href = document.getElementById(canvasId).toDataURL(); 
    link.download = filename; 
} 

document.getElementById('download').addEventListener('click', function() { 
    downloadCanvas(this, 'canvas', 'test.png'); 
}, false); 

doCanvas(); 
</script>