更改画布填充样式而不与先前颜色重叠

时间:2015-04-16 06:39:07

标签: javascript html5-canvas

我试图改变焦点上的填充样式并集中注意事件。当事件多次调用时,它会重叠。这是我的代码:

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]);
    }
}

2 个答案:

答案 0 :(得分:2)

只需使用context.clearRect(x, y, width, height)即可。其目的是删除任何先前绘制的矩形内容(请查看documentation)。有关示例,请参阅this forked fiddle

答案 1 :(得分:0)

我将图像设置为画布背景图像,而不是将其绘制到画布上。它现在正常工作。

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);  
});