Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I alter the colour of a html5 canvas element using jquery?

Basically I have several canvas drawings on my page what I want to happen is when a the jquery function is activated the canvas drawings change to the colour of my choosing. I assume it involves some way of accessing context.fillStyle which defines the original colour but I am unsure how to alter it. In addition, would it be possible to instead give the canvas drawing a css style in the first instance and then change that style when the jquery is processed?

HTML

 <canvas class="canvaslink" id="canvasId" width="50" height="50"></canvas>

 <canvas class="canvaslink" id="canvasId2" width="50" height="50"></canvas>

Canvas script

<script>
function drawSomething(canvas) {
var context = canvas.getContext("2d");

var width = 125;  // Triangle Width
var height = 45; // Triangle Height
var padding = 5;

// Draw a path
context.beginPath();
context.moveTo(padding + width-125, height + padding);        // Top Corner
context.lineTo(padding + width-90,height-17 + padding); // point
context.lineTo(padding, height-35 + padding);         // Bottom Left
context.closePath();

// Fill the path
context.fillStyle = "#9ea7b8";
context.fill();


}

drawSomething(document.getElementById("canvasId"));
drawSomething(document.getElementById("canvasId2"));

</script>

Jquery Script

<script>
var counter = $('#counter div strong');

var counterH2 = $('h2 strong');

$('#box').click(function(){
    $("#counter").css("display", "block");
     var counterValue = counter.text();
     counterValue = ++counterValue;
     counter.text(counterValue);
     counterH2.text(counterValue);
     if (counterValue == 3){
        alert("Thanks for visiting!");
        $('body').css({"background-color":"#9ea7b8"});
        $('body').css({"color":"#11112c"});

        **//I'd like to change the canvas colour here!**

     }

});
</script> 

Many thanks

like image 395
Ollie Jones Avatar asked Jun 04 '12 14:06

Ollie Jones


2 Answers

It's as simple as this:

document.getElementById("ID").style.background = 'color';
like image 143
David Avatar answered Oct 04 '22 20:10

David


You can do that :

var context = canvas.getContext('2d');
context.fillStyle = "#000000";
context.fill();
// Other properties ...

You can see an HTML5 canvas tutorial (very simple) here.

like image 32
Val Avatar answered Oct 04 '22 19:10

Val