【问题标题】:How do I zoom/pan on enlarged canvas using d3?如何使用 d3 在放大的画布上缩放/平移?
【发布时间】:2017-09-22 17:30:17
【问题描述】:

我使用 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>

【问题讨论】:

    标签: javascript html css d3.js


    【解决方案1】:

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

    首先,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 映射到客户端画布坐标...

    【讨论】:

      猜你喜欢
      • 2017-01-15
      • 2018-05-13
      • 1970-01-01
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      • 2012-11-09
      • 2012-01-12
      • 2012-09-22
      相关资源
      最近更新 更多