Search code examples
javascripthtmlcanvasfill

Need to dynamically change fill pattern


I have done this code: http://www.cozeez.co.uk/test.php

How do I change the fill image from 3 buttons to 3 different colors?


Solution

  • Add three buttons with id 'button1', 'button2', 'button3'

    Rewrite your current code so you dont repeat yourself (DRY):

    function fillCircle(canvasId, color) {
        var canvas=document.getElementById(canvasId);
        var cxt=canvas.getContext("2d");
    
        var imageObj = new Image();
        imageObj.src = "images/" + color + ".jpg";
        imageObj.onload = function() {
            var pattern = cxt.createPattern(imageObj, "repeat");
            cxt.fillStyle=pattern;
            cxt.fill();
        }
    
    
        cxt.beginPath();
        cxt.arc(51,51,50,0,Math.PI*2,true);
        cxt.closePath();
        cxt.stroke();
    } 
    
    fillCircle("myCanvas", "pink");
    fillCircle("myCanvas2", "green");
    

    And add (with jQuery): EDITED

    $('#button1').click(function() {fillCircle("myCanvas", "blue")});
    $('#button2').click(function() {fillCircle("myCanvas", "red")});
    $('#button3').click(function() {fillCircle("myCanvas", "yellow")});
    

    Or whatever colors you want, and depending on which canvas you want to change of course.