Canvas How to - Change fill style between drawing








Question

We would like to know how to change fill style between drawing.

Answer


<!--   ww w .  ja v  a2s  . co m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var myCanvas = document.getElementById("buffer");
    var context = myCanvas.getContext('2d');
    var myCanvas1 = document.createElement('canvas');
    myCanvas1.width = myCanvas1.height = 100;
    var newContext = myCanvas1.getContext('2d');
    newContext.translate(30, 30);
    newContext.rotate(0.5);
    newContext.fillStyle = 'rgb(255, 0, 0)';
    newContext.fillRect(-15, -15, 30, 30);
    context.fillStyle = 'rgb(0, 255, 0)';
    context.fillRect(30, 30, 30, 30);
    context.drawImage(buffer, 50, 50);
}//]]>  
</script>
</head>
<body>
    <canvas id="buffer" width="100" height="100"></canvas>
</body>
</html>

The code above is rendered as follows: