简体   繁体   中英

How to remove transparent whitespace from image after a crop HTML5 Canvas/JavaScript?

So I have a function that dynamically produces a cropped section of a world map. The map has various points plotted onto it, plotted by longitude and latitude, depending on the data passed into the function from elsewhere in the script. (Don't worry about how these values are calculated, just accept they are calculated where I have put [number] in my code). I've worked out how to crop my map dynamically, but what I'm noticing is that there is a lot of transparent whitespace to the right of the image after the crop, when the image is appended to a div on the page. How do I remove this whitespace?

Please note that each crop will be of a different size. Setting overflow:hidden property on the containing div and limiting the containing div to a precise pixel width will not achieve what I want to achieve.

Thx u -- Gaweyne

createZoomedMapImage: function(imageURL){
  var imageObj = new Image();

  imageObj.onload = _.bind(function(){
    var canvas = document.createElement("canvas"),
        context = canvas.getContext("2d"),
        $canvas = $(canvas),
        w = imageObj.width,
        h = imageObj.height;
  canvas.width = w;
  canvas.height = h;

  var startingX = [number]
  var starting Y = [number]
  var deltaWidth = [number]
  deltaHeight = [number]
  context.drawImage(imageObj, startingX, startingY, deltaWidth, deltaHeight, 0, 0, (deltaWidth*2), (deltaHeight*2));
  var zoomedImage = canvas.toDataURL('image/png');

  }, this);
  imageObj.src = imageURL;
}

jsfiddle.net/Gaweyne/r0t3hoo6

The image tag looks like what is displayed in the result. I have an image of, say, 300 x 600px. But the actual graphic only takes up 300 x 300 pixels. I don't want the graphic to take up the full width of the image. I want the image to be 300 x 300 pixels. I don't want to set this explicitly with CSS because the cropped maps will differ in size depending on the data.

Try to use:

canvas.width = deltaWidth;
canvas.height = deltaHeight;
context.drawImage(imageObj, startingX, startingY, deltaWidth, deltaHeight, 0, 0, (deltaWidth*2), (deltaHeight*2));
var zoomedImage = canvas.toDataURL('image/png');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM