使用HTML5画布在背景图像上绘制并缩放

3
如何编写一个简单的脚本来在背景图上绘制并放大选定的位置。使用HTML5画布同时缩放背景图和绘制内容。
1个回答

3

Canvas提供了一种相当简单的方式,使用变换缩放到一个点。

  • 使用context.translate(x,y)将画布平移到所需的缩放点。平移会将画布的[0,0]原点重置为指定的[x,y]坐标。

  • 使用context.scale(sx,sy)将画布缩放到所需的大小。缩放会导致任何未来的绘图被调整为指定的[scaleX,scaleY]大小。注意:缩放发生在画布的当前原点处(当前原点由上面的translate重置)。

  • 使用context.drawImage(image,-x,-y)将图像和绘画偏移-x,-y进行绘制。这个偏移是必需的,以便在保持所需缩放点的同时重新绘制图像。

演示:http://jsfiddle.net/m1erickson/5kQHb/

在红点处缩小:

enter image description here

在红点处放大:

enter image description here

示例代码:

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color:ivory; }
    canvas{border:1px solid red;}
    input.vrange1 {height:250px; -webkit-appearance: slider-vertical; writing-mode: bt-lr; }
</style>
<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var PI=Math.PI;
    var PI2=PI*2;
    var cw,ch,imgW,imgH,mouseX,mouseY;
    var scaleFactor=1.00;

    $scaler=$("#scaler");
    $scaler.val(scaleFactor);
    $scaler.hide();

    var img=new Image();
    img.onload=start;
    img.src="https://dl.dropboxusercontent.com/u/139992952/multple/mapSmall.png";
    function start(){
        cw=canvas.width=imgW=img.width;
        ch=canvas.height=imgH=img.height;
        ctx.drawImage(img,0,0);

        $("#canvas").mousedown(function(e){handleMouseDown(e);});   
    }

    function dot(x,y,color,radius){
        ctx.save();
        ctx.beginPath();
        ctx.arc(x,y,radius,0,PI2);
        ctx.closePath();
        ctx.fillStyle=color;
        ctx.fill();
        ctx.restore();
    }

    function draw(x,y,scale){
        ctx.clearRect(0,0,cw,ch);
        ctx.save();
        ctx.translate(x,y);
        ctx.scale(scale,scale);
        ctx.drawImage(img,-x,-y);
        ctx.restore();
        dot(x,y,"red",3);
    }

    $('#scaler').on('change', function(){
        scaleFactor=($(this).val());
        draw(mouseX,mouseY,scaleFactor);    
    });

    function handleMouseDown(e){
      e.preventDefault();
      e.stopPropagation();
      if(!mouseX){
          var BB=canvas.getBoundingClientRect();
          var offsetX=BB.left;
          var offsetY=BB.top;  
          mouseX=parseInt(e.clientX-offsetX);
          mouseY=parseInt(e.clientY-offsetY);
          draw(mouseX,mouseY,1.00);
          $("#instructions").text("Change the slider to zoom the map");
          $scaler.show();
      }
    }

}); // end $(function(){});
</script>
</head>
<body>
    <h4 id=instructions>Click on the map to select a zoom-point.</h4>
    <input type="range" class=vrange id="scaler" value=1.00 min=0.00 max=3.00 step=0.10"><br>   
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接