简体   繁体   中英

How to change the fillStyle of a canvas element using javascript or jquery?

I have some html5 canvas code to make an image, the current fillstyle is green, but when I link is clicked, it should change to red, but it's not working. How do I fix this? thanks

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>  
 <head>  
    <script>
        window.onload = function() {


            var canvas = document.getElementById('myCanvas');
            var context  = canvas.getContext('2d');  

            context.fillStyle = "rgb(0,200,0)";  
            context.fillRect (0, 0, 608, 105);  

            var img = new Image();  
            img.src = 'Round Borders.png';  
            context.drawImage(img,0,0);  


            var dataURL = canvas.toDataURL();
            document.getElementById("canvasImg").src = dataURL;


        };

  </script>  

  <script type="text/javascript">
        function change_bg_color(val) {
            document.getElementById('myCanvas').getContext('2d').fillStyle = val;
        }
  </script>

 </head>  
 <body onmousedown="return false;">
   <canvas id="myCanvas" width="608" height="105" style="display:none;"></canvas>  
   <img id="canvasImg" title="Right click to save me!">
   <br/>
   <a href="#" onclick="change_bg_color('rgb(200,0,0)');">change to red</a>
 </body>  
</html> 

Working Demo

Think of fillStyle like choosing your paint for an actual painters canvas. You have to choose your paint first, then begin painting. If you want to change your color you have to dip your brush and repaint.

So basically you need to redraw the everything on the canvas with the new fillStyle like the following.

var link = document.getElementsByTagName("a")[0],
    canvas = document.getElementById('myCanvas'),
    context  = canvas.getContext('2d'); 

link.onclick = function(){
    draw('rgb(200,0,0)');
}

function draw(val){
        context.fillStyle = val;
        context.fillRect (0, 0, 608, 105);  
        var img = new Image();  
        img.src = 'Round Borders.png';  
        context.drawImage(img,0,0);  
        var dataURL = canvas.toDataURL();
        document.getElementById("canvasImg").src = dataURL;
}

draw("rgb(0,200,0)");

Just pass the color to draw and it will repaint with the chosen color.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM