【发布时间】: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