0

I am using this code to display data of two canvas into third canvas but it is not working. I am saving the two canvas data using localstorage and passing it to third canvas

var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); //First canvas data var img1 = loadImage(localStorage.getItem('cbdata'), main); //Second canvas data var img2 = loadImage(localStorage.getItem('cbdata1'), main); var imagesLoaded = 0; function main() { imagesLoaded += 1; if (imagesLoaded == 2) { // composite now ctx.drawImage(img1, 0, 0); ctx.globalAlpha = 0.5; ctx.drawImage(img2, 0, 0); } } function loadImage(src, onload) { var img = new Image(); img.onload = onload; img.src = src; return img; } 
4
  • 1
    What isn't working about it? Please give in your question examples of both the desired behavior and the actual behavior. Commented Oct 25, 2015 at 15:57
  • Code you have given looks ok. Have you checked the console for any errors? Are you sure there is data in localStorage["cddata"] and is that data the correct format? Commented Oct 25, 2015 at 15:57
  • yes it shows Uncaught TypeError: Cannot read property 'getContext' of null Commented Oct 25, 2015 at 16:38
  • 1
    The script has to run after the element with the id canvas has been created. Move the script block at the end of the page, just before the closing </body> tag. Commented Oct 25, 2015 at 17:15

1 Answer 1

1

Your code works. Check that the content of localStorage.getItem is non-empty. And I also slightly modified display of the images by changing ctx.drawImage commands:

var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); //First canvas data var img1 = loadImage('http://ep01.epimg.net/elpais/imagenes/2015/10/21/ciencia/1445444934_907402_1445781076_portada_normal.jpg', main); //Second canvas data var img2 = loadImage('http://ep01.epimg.net/economia/imagenes/2015/10/22/actualidad/1445508003_507635_1445508894_portada_normal.jpg', main); var imagesLoaded = 0; function main() { imagesLoaded += 1; if (imagesLoaded == 2) { // composite now ctx.drawImage(img1, 0, 0, 100, 100); ctx.globalAlpha = 0.5; ctx.drawImage(img2, 100, 0, 100, 100); } } function loadImage(src, onload) { console.log('loadImage', src); var img = new Image(); img.onload = onload; img.src = src; return img; } 

https://jsfiddle.net/4Le4g8ta/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.