HTML - Canvas元素以相同比例的画布

时间:2017-04-20 15:50:10

标签: javascript html html5 canvas html5-canvas

我发现要从HTML画布中获取base64数据,您必须执行canvas.toDataURL();。这个的问题是,当它给你base64时,它被缩放到通用的300 x 150画布大小,但实际画布是600 x 100.有没有办法将图像拉伸为600 x 100,或者要在base64中导出它吗?提前谢谢!

1 个答案:

答案 0 :(得分:0)

我在CSS中定义的宽度和高度不是HTML,因此文档没有记录宽度和高度。  以下是更新后的代码:



<body>
<script>
var granmoe = 0;
var hai = 5;
var runnin = 0;
while(runnin != hai){
	var can = document.createElement("canvas");
	can.id = "canvasite"
	can.style = "width: 150px; height: 100px; display:none;"
	document.body.appendChild(can);
	c = document.getElementById('canvasite'),
    ctx = c.getContext('2d');
    var x = 0
    if(runnin == 0){
		var endheight = c.height/2
	}
    var y = endheight;
	var widd = 0
	while(widd != c.width){
    	ctx.fillStyle = "rgba("+0+","+255+","+0+","+(255/255)+")";
		ctx.fillRect( x, y, 1, 1 );
		var ychan = Math.floor((Math.random() * 6) + 1);
		if(ychan == 1){
			var y=y+2
		}else if(ychan == 2){
			var y=y+1
		}else if(ychan == 3){
			var y=y-1
		}else if(ychan == 4){
			var y=y-2
		}else{
			var y=y
		}
		var hig = y
		while(hig != c.height){
    		ctx.fillStyle = "rgba("+0+","+255+","+0+","+(255/255)+")";
			ctx.fillRect( x, hig, 1, 1 );
			var hig = hig+1
		}
		var widd = widd+1
		var x=x+1
	}
    {
	var endheight = y
	var runnin = runnin+1
	document.getElementById('canvasite').setAttribute('id','nAn')
	var imgm = document.createElement("img");
	imgm.src = c.toDataURL();
    imgm.id = "imageitem"
    imgm.style = "display:none;"
	document.body.appendChild(imgm)
	var xid = granmoe*(300*(1/hai));
	if(granmoe == 0){
		var cansfoo = document.createElement("canvas")
		cansfoo.id = "fullimage";
		cansfoo.style = 'width: '+(hai*150)+'px; height: 100px; display:none;'
		document.body.appendChild(cansfoo);
	}
	var ci=document.getElementById("fullimage");
	var ctxi=ci.getContext("2d");
	var imd=document.getElementById("imageitem");
	ctxi.drawImage(imd,xid,0,(300*(1/hai)),180);
	//end
	var granmoe=granmoe+1
	document.getElementById("imageitem").setAttribute('id','non');
}
}
var base64 = ci.toDataURL();
var bass = document.createElement("img");
bass.src = base64
bass.id = "resiz"
bass.style = "display:none;"
document.body.appendChild(bass);
{
		var resize = document.createElement("canvas")
		resize.id = "resize";
        resize.width = (hai*150);
        resize.height = 100;
		resize.style = 'display:none;'
		document.body.appendChild(resize);
	var re=document.getElementById("resize");
	var res=re.getContext("2d");
    	var imag=document.getElementById("resiz");
	res.drawImage(imag,0,50,(hai*150),50);
    document.write(resize.toDataURL());
    }
</script>
</body>
&#13;
&#13;
&#13;