2017-04-17 90 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>