繁体   English   中英

如何适合画布包装图像尺寸

[英]How to fit canvas to wrap image size

您好,我有此画布和图像,但是我需要制作它,以便画布将链接到其尺寸的图像包裹起来。 现在,我已经放置了测试图像,并固定了尺寸。 我希望在放置画布并对其进行成像时将其包装成图像的100%宽度100%高度。

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/

如果您始终将图像加载到位置(0,0) ,则可以通过添加将画布的大小设置为加载的图像的大小

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

start()函数的最开始。 前两行调整画布的大小。 调整大小后,必须更新上下文以使其正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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