如何使用d3缩放/平移放大的画布?

时间:2017-09-22 07:39:48

标签: javascript html css d3.js

我使用d3进行了画布缩放/平移,效果很好 但这是我的问题。我需要放大并放大里面的图像 画布。
由于图像太小而且不适合父div而不改变画布的实际宽度和高度,我将canvas.style.width设置为90%,以便画布填充父div的90%。 /> 但是进行缩放时,缩放不正常。你能告诉我怎么办才能解决这个问题吗?

在画布样式上设置90%宽度后,我应该在d3侧设置什么?



var imgCanvas = document.getElementById("canvas");
var imgCtx = imgCanvas.getContext('2d');
var d3Zoom = d3.zoom().scaleExtent([1, 3]).on("zoom", zoom),
	d3Canvas  = d3.select("canvas").call(d3Zoom).on("dblclick.zoom", null),
	d3Ctx     = d3Canvas.node().getContext("2d"),
	d3width   = d3Canvas.property("width"),
	d3height  = d3Canvas.property("height");
var img = new Image();

function zoom() {
var transform = d3.event.transform;
d3Ctx.save();
imgCtx.clearRect(0, 0, imgCanvas.width, imgCanvas.height),
d3Ctx.clearRect(0, 0, d3width, d3height);
d3Ctx.translate(transform.x, transform.y);
d3Ctx.scale(transform.k, transform.k);
d3Ctx.beginPath();
d3Ctx.drawImage(img, 0, 0);
d3Ctx.fill();
d3Ctx.restore();
}

window.onload=function() {
img.src = 
	"https://www.bullionstar.com/files/"
	+ "gold-coins/100_100_gold-coin-canada-maple-leaf-2017-1oz-back.jpg";
img.onload = function() {
	
	imgCanvas.height = img.naturalHeight;
	imgCanvas.width = img.naturalWidth;
	imgCtx.drawImage(img, 0, 0, imgCanvas.width, imgCanvas.height);
	imgCanvas.style.height = "90%";
}
};

<script src="https://d3js.org/d3.v4.min.js"></script>
<div width ="500px" height ="500px">
<div width ="100%" height ="500px">
	<div width ="100%" height ="100%">
		<canvas id="canvas"></canvas>
	</div>
</div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

你的意思是设置画布高度不起作用吗?

首先,div没有宽度/高度属性(通过style / css设置)

第二,你应该将你的xform更改为

d3Ctx.scale( imgCanvas.width/imgCanvas.clientWidth,imgCanvas.height/imgCanvas.clientHeight);
d3Ctx.translate(transform.x, transform.y);
d3Ctx.scale(transform.k, transform.k);
d3Ctx.scale( imgCanvas.clientWidth/imgCanvas.width, imgCanvas.clientHeight/imgCanvas.height);

其中两个缩放(一个与另一个相反)将缩放xform映射到客户端画布坐标......