如何在D3中响应的SVG中创建HTML Canvas?

时间:2018-08-27 11:49:40

标签: d3.js svg html5-canvas

我正在将SVG层上方的画布用作主绘图层,如图所示

enter image description here

我在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;
}

如何使该设置具有响应性?

0 个答案:

没有答案