首页 > 解决方案 > 如何在 D3 中响应 SVG 中的 HTML 画布?

问题描述

如图所示,我使用 SVG 层顶部的画布作为主要绘图层

在此处输入图像描述

我在stackoverflow上搜索了很多并遇到了

var container = d3.select('#chartContainer')
.append('svg')
.attr('viewbox', '0 0 900 400')
.append('g')
.attr('transform', 'translate(24, 24)')

上面的 viewbox 技巧对于纯 SVG 容器非常有效,但在我的情况下,我在 div 容器内有绝对位置的 SVG + canvas 元素

// Get a reference to our base container with the chart inside it
const container = d3.select('.scatter-container');

// Init SVG
// Notice how we translate to margin left and top
const svgChart = container.append('svg')
   .attr('width', outerWidth)
   .attr('height', outerHeight)
   .attr('class', 'svg-plot')
   .append('g')
.attr('transform', `translate(${margin.left}, ${margin.top})`);

// Init Canvas
// Notice how we set a margin left and top on the canvas to avoid it overlapping with our svg axes
const canvasChart = container.append('canvas')
   .attr('width', width)
   .attr('height', height)
   .style('margin-left', margin.left + 'px')
   .style('margin-top', margin.top + 'px')
   .attr('class', 'canvas-plot');
//CSS
.scatter-container {
    margin: auto;
    background: #1F242F;

/*   Dont remove the width and height here */
    width: 1080px;
    height: 640px;

}

.svg-plot, .canvas-plot {
    position: absolute;
}

如何使此设置响应?

标签: d3.jssvghtml5-canvas

解决方案


推荐阅读