Canvas How to - Use Slider to control image pattern








Question

We would like to know how to use Slider to control image pattern.

Answer


<!-- www  .  j ava2  s .c om-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var ctx = canvas.getContext('2d');

var img = document.createElement('img');
img.onload = function() {fillPattern(this, 64, 64)};
img.src = 'http://www.java2s.com/style/download.png';
function fillPattern(img, w, h) {
    //draw once
    ctx.drawImage(img, 0, 0, w, h);
    while (w < canvas.width) {
        ctx.drawImage(canvas, w, 0);
        w *= 2;
    }
    while (h < canvas.height) {
        ctx.drawImage(canvas, 0, h);
        h *= 2;
    }
}
change.onchange = function(e) {
    if (img) fillPattern(img, this.value, this.value);
}
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width=500 height=400></canvas>
  <input id="change" type=range min=8 max=120 value=64 />
</body>
</html>

The code above is rendered as follows: