2017-04-17 18 views
1

私はキャンバスを描こうとしており、ダウンロードしたいと思っています。ダウンロードとテキストでうまくいきましたが、画像を追加する方法も追加しますか?以下のコードはキャンバスを描画し、それをPNG形式でもダウンロードしますが、キャンバスに画像を追加する方法見出し段落です。 jQueryのここ イメージとキャンバスはどうやってダウンロードできますか?

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

は次のとおりです:ここで

はhtmlです

<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-to-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> 
関連する問題