1

I am trying to draw canvas and also want to download, it working fine with download and text but I want to add image also how to do it? The code given bellow draws canvas and downloads it as a png also but how to add image in canvas heading and paragraph in it?

Here is html:

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

Here is 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>
arghtype
  • 4,376
  • 11
  • 45
  • 60
Zarttash
  • 9
  • 4
  • The question how to download from a canvas is already answered. http://stackoverflow.com/questions/11112321/how-to-save-canvas-as-png-image – SeregPie Apr 17 '17 at 20:06
  • My code for download as png is working well but i want to add an image in it like http://stackoverflow.com/questions/29657681/add-image-to-canvas-through-jquery but its not working – Zarttash Apr 18 '17 at 11:33

1 Answers1

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

you have to create a variable and then if you want background image of canvas than use it as

    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>
Zarttash
  • 9
  • 4