简体   繁体   中英

How to fit canvas to wrap image size

Hello I have this canvas and image in it but I need to make it so the canvas wraps the image linked to its size. Right now i have put a test image and put size to be fixed. I want when i put and image the canvas to wrap it 100% width 100% height of the image.

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var boxWidth=100;
var boxHeight=100;
var boxRows=Math.ceil(865/boxHeight);
var boxCols=Math.ceil(1152/boxWidth);
var boxes=new Array(boxRows*boxCols);
for(var i=0;i<boxes.length;i++){boxes[i]=false;}

var img=new Image();
img.onload=start;
img.crossOrigin='anonymous';
img.src="http://i.imgur.com/RrHayx8.png?1";
function start(){

ctx.drawImage(img,0,0);

var d=ctx.getImageData(0,0,cw,ch).data;

for(var i=0;i<d.length;i+=4){
if(d[i+3]>200){
  var px=parseInt(i/4);
  var pixelY=parseInt(px/cw);
  var pixelX=px-pixelY*cw;
  var boxX=parseInt(pixelX/boxWidth);
  var boxY=parseInt(pixelY/boxHeight); 
  boxes[boxY*boxCols+boxX]=true;
 }
  }

 ctx.globalAlpha=0.25;
 ctx.fillStyle='red';

 for(var i=0;i<boxes.length;i++){
 var y=parseInt(i/boxCols);
 var x=i-y*boxCols;
 if(boxes[i]==true){
  ctx.fillRect(x*boxWidth,y*boxHeight,boxWidth,boxHeight);        
 }
 }

ctx.globalAlpha=1.00;
ctx.fillStyle='black';

}

https://jsfiddle.net/kdichev/Lmqdrkp2/

If you always load the image to position (0,0) , then you can set the size of the canvas to the size of the loaded image by adding

  canvas.width = img.width;
  canvas.height = img.height;
  ctx=canvas.getContext("2d");

to the very beginning of your start() function. The first two lines resize the canvas. After resizing the context has to be updated to make it work properly.

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