Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

HTML Canvas problem.

  • 20-10-2013 11:06AM
    #1
    Registered Users, Registered Users 2 Posts: 48


    I am new to website design and I cannot get my canvas to run images. I would appreciate some advice as any fixes I have tried are not working. This is the javascript and html code,

    function drawOnCanvas(){
    var canvas = document.getElementById('mycanvas');
    canvas = canvas.getContext('2d');

    var image = new image();
    image.src= "images/img1.jpg";
    image.addEventListener("load", function(){canvas.drawOnCanvas(image,0,0);}, false);
    }


    window.addEventListener("load", drawOnCanvas, false);

    <section id="sect">
    <div>
    <canvas id ="mycanvas" width= "595" height= "595">
    Your browser does not support the HTML5 Canvas.
    </canvas>
    </div>
    </section>


Comments

  • Registered Users, Registered Users 2 Posts: 1,311 ✭✭✭Procasinator


    You have a few small mistakes.

    The object you need when creating the image variable is "Image" rather than "image" (JavaScript is case-sensitive).

    Secondly, the method you are looking for is drawImage rather than drawOnCanvas inside your event listener.

    That should leave you with:
    function drawOnCanvas(){
    	var canvas = document.getElementById('mycanvas');
    	canvas = canvas.getContext('2d');
    
    	var image = new Image();
    	image.src= "images/img1.jpg";
    	image.addEventListener("load", function() {
    		canvas.drawImage(image,0,0);
    	}, false);
    }
    
    window.addEventListener("load", drawOnCanvas, false);
    


  • Registered Users, Registered Users 2 Posts: 48 donedl1


    Thanks Procasinator, I have been stuck on this for quite a few days and looking at on-line references for a fix. Frustrated would be an understatement, thanks again.


Advertisement