Canvas How to - Resize canvas with slider








Question

We would like to know how to resize canvas with slider.

Answer


<!--   ww  w .  j  av  a2s .co m-->


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var canvas = document.getElementById('canvas'),
    context = canvas.getContext('2d'),
    slider = document.getElementById('width'),
    width = 400;
context.strokeStyle = 'red';
canvas.width = slider.value = 400;
slider.onchange = function() {
    canvas.width = parseInt(slider.value);
};
var render = function() {
    context.strokeStyle = 'red';
    var t = new Date().getTime();
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.fillStyle = 'black';
    context.fillRect(0, 0, canvas.width, canvas.height);
    for (var m = 1; m < 5; m++) {
    context.beginPath();
    for (var x = 0; x < canvas.width; x++) {
        var halfHeight = canvas.height/2,
            y = Math.sin((t * m)/500 + x/10)*halfHeight + halfHeight;
        context.lineTo(x, y);
    }
    context.stroke();
    }
};
var animate = function() {
    render();
    window.requestAnimationFrame(animate);
};
animate();
}//]]>  
</script>
</head>
<body>
  <div>
    <canvas id="canvas" />
  </div>
  <div>
    <input id="width" type="range" min="0" max="500" style="width: 500px" />
  </div>
</body>
</html>

The code above is rendered as follows: