display portion of scaled image in div

前端 未结 1 1821
慢半拍i
慢半拍i 2021-01-27 17:15

So I have a script, to which when I provide a image detail and a div size, it calculates a region in the image, and a scale factor in order to show the best area of the image in

相关标签:
1条回答
  • 2021-01-27 17:34

    Note, Note certain about expected result of values within

    {"scale":1.34,"x1":502,"x2":822,"y1":178,"y2":578}
    

    at

    "rect("+data.y1+"px,"+data.x2+"px,"+data.y2+"px,"+data.x1+"px)"
    

    ?

    Utilized

    {"scale":1.34,"x1":100,"x2":200,"y1":100,"y2":200};
    

    below. See CanvasRenderingContext2D.drawImage()

    Try

    var data = {"scale":1.34,"x1":100,"x2":200,"y1":100,"y2":200};
    function showImageInDiv(image, data) {   
        $("#iDiv").empty()
        .append("<canvas id=iDivImage width=500px height=400px></canvas>");
        var img = new Image;
        img.onload = function() {
        var canvas = $("#iDivImage");
        var ctx = canvas.get(0).getContext("2d");
        ctx.drawImage(this, data.x1, data.y1, 500, 400, 0, 0, data.x2, data.y2);
        canvas.css("transform", "scale(" + data.scale + ", "+ data.scale +")");
        };
        img.src = image[0].src;    
    };
    
    showImageInDiv($("img"), data);
    

    var data = {"scale":1.34,"x1":100,"x2":200,"y1":100,"y2":200};
    function showImageInDiv(image, data) {   
        $("#iDiv").empty().append("<canvas id=iDivImage width=500px height=400px></canvas>");
        var img = new Image;
        img.onload = function() {
        var canvas = $("#iDivImage");
        var ctx = canvas.get(0).getContext("2d");
        ctx.drawImage(this, data.x1, data.y1, 500, 400, 0, 0, data.x2, data.y2);
        canvas.css("transform", "scale(" + data.scale + ", "+ data.scale +")");
        };
        img.src = image[0].src;
    
        //"rect("+data.y1+"px,"+data.x2+"px,"+data.y2+"px,"+data.x1+"px)"
    
    };
    
    showImageInDiv($("img"), data);
    #iDiv {
      display:block;
      width:500px;
      height:400px;
    }
    
    #iDiv {
      clip-path():
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div id="iDiv"></div>
    <img src="http://lorempixel.com/1536/1024/cats/" />

    0 讨论(0)
提交回复
热议问题