0

I'm trying to change fillstyle on focus in and focus out event. When the event call multiple time it's overlapping. Here my code:

function FillColorToFields(id, isOnFocus) {
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    var coordinates = $('#hidCoord_' + id).val().split(',');
    if (isOnFocus) {
        context.fillStyle = "rgba(0,255,0,0.1)";
        context.fillRect(coordinates[0], coordinates[1], coordinates[2], coordinates[3]);
    } else {
        context.fillStyle = "rgba(255, 255, 255, 0.5)";
        context.fillRect(coordinates[0], coordinates[1], coordinates[2], coordinates[3]);
    }
}
Sachin
  • 40,216
  • 7
  • 90
  • 102
Jega
  • 33
  • 7

2 Answers2

2

Simply use context.clearRect(x, y, width, height). Its purpose is to erase any previously drawn content of the rectangle (check out the documentation). See this forked fiddle for an example.

Tadeáš Peták
  • 567
  • 2
  • 13
  • In my case, I have to load an image to canvas and draw rectangle on it. Please check this https://jsfiddle.net/vm47p2sk/3 – Jega Apr 16 '15 at 07:50
  • Oooh, much more fun! You would have to use `getImageData` and `putImageData` to restore the original state. See [this fiddle](http://jsfiddle.net/TadeasPetak/vm47p2sk/7/) for an example. You then run into an issue of a **tainted** canvas, solution to which is described in [this question](http://stackoverflow.com/questions/22097747/getimagedata-error-the-canvas-has-been-tainted-by-cross-origin-data). – Tadeáš Peták Apr 16 '15 at 08:06
0

I set the image as canvas background image instead of drawing it to canvas. It's working fine now.

http://jsfiddle.net/vm47p2sk/8/

<canvas id="myCanvas"></canvas>
<a id = "green" href="#">On focus</a>
<a id = "transparent" href="#">On focus out</a>



 $('#myCanvas').css("background-image", "url(https://www.webkit.org/blog-files/acid3-100.png)");
                    var canvas = document.getElementById('myCanvas');
var context  = canvas.getContext('2d');
   context.strokeStyle = "#009900";
        context.lineWidth = 3;
        context.strokeRect (5, 5, 100, 100);

$('#green').click(function (){
        context.clearRect (8, 8, 94, 94);  
        context.fillStyle = "rgba(0,255,0,0.1)";
        context.fillRect (8, 8, 94, 94);  
});

$('#transparent').click(function (){
        context.clearRect (8, 8, 94, 94); 
        context.fillStyle = "rgba(255, 255, 255, 0.1)";
        context.fillRect (8, 8, 94, 94);  
});
Andrew Walters
  • 4,763
  • 6
  • 35
  • 49
Jega
  • 33
  • 7