Canvas How to - Hover to change triangle color








Question

We would like to know how to hover to change triangle color.

Answer


<!--   www . j  av  a2  s . c  o m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.7.1.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
    function drawTriangle(color) {
        var context = document.getElementById("canvasId").getContext("2d");
        var width = 150; 
        var height = 105; 
        context.clearRect(0,0,width,height);
        context.beginPath();
        context.moveTo(75, 0);       
        context.lineTo(150, 105); 
        context.lineTo(0, 105);       
        context.closePath();
        context.fillStyle = color;
        context.fill();
    }
    drawTriangle("#ffc821");
    $('#canvasId').hover(function () {
        drawTriangle("#0000FF");
    }, function () {
        drawTriangle("#ffc821");
    });
});//]]>  
</script>
</head>
<body>
  <canvas id="canvasId"></canvas>
</body>
</html>

The code above is rendered as follows: