Making SVGs responsive is unfortunately not as simple as adding some media queries. This lesson introduces the viewBox attribute, which is used to control how SVGs scale. We’ll also examine a reusable function that can be used to make nearly any visualization responsive.

var margin = { top: 10, right: 20, bottom: 30, left: 30 };
var width = 400 - margin.left - margin.right;
var height = 600 - margin.top - margin.bottom; var svg = d3.select('.chart')
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.call(responsivefy)
.append('g')
.attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')'); svg.append('rect')
.attr('width', width)
.attr('height', height)
.style('fill', 'lightblue')
.style('stroke', 'green'); var yScale = d3.scaleLinear()
.domain([0, 100])
.range([height, 0]);
var yAxis = d3.axisLeft(yScale);
svg.call(yAxis); var xScale = d3.scaleTime()
.domain([new Date(2016, 0, 1, 6), new Date(2016, 0, 1, 9)])
.range([0, width]); var xAxis = d3.axisBottom(xScale)
.ticks(5)
.tickSize(10)
.tickPadding(5);
svg
.append('g')
.attr('transform', `translate(0, ${height})`)
.call(xAxis); function responsivefy(svg) {
// get container + svg aspect ratio
var container = d3.select(svg.node().parentNode),
width = parseInt(svg.style("width")),
height = parseInt(svg.style("height")),
aspect = width / height; // add viewBox and preserveAspectRatio properties,
// and call resize so that svg resizes on inital page load
svg.attr("viewBox", "0 0 " + width + " " + height)
.attr("preserveAspectRatio", "xMinYMid")
.call(resize); // to register multiple listeners for same event type,
// you need to add namespace, i.e., 'click.foo'
// necessary if you call invoke this function for multiple svgs
// api docs: https://github.com/mbostock/d3/wiki/Selections#on
d3.select(window).on("resize." + container.attr("id"), resize); // get width of container and resize svg to fit it
function resize() {
var targetWidth = parseInt(container.style("width"));
svg.attr("width", targetWidth);
svg.attr("height", Math.round(targetWidth / aspect));
}
}

最新文章

  1. 学习微信小程序之css9内边距
  2. .NET应用服务器
  3. 发现磁盘的shell
  4. springMVC3 ckeditor3.6 图片上传 JS回调
  5. 一个php类 Autoloader
  6. UITableView的详细使用
  7. linux下软件安装与卸载
  8. linux下查看文件内容cat,more,less
  9. php中实现快排与冒泡排序
  10. Web服务器Raspkate的RESTful API
  11. MD5加密。
  12. Java集合实现
  13. python学习中的bug
  14. eclipse中中文注释乱码怎么解决
  15. python简说(二十一)开发接口
  16. office2016word 每次打开都有进度条问题 解决方式
  17. 团队博客作业Week5 --- 团队贡献分--分配规则
  18. Only a type can be imported. classname resolves to a package的解决
  19. javascript与jQuery的each,map回调函数参数顺序问题
  20. jQuery实现18位身份证输入隔位添加空格及格式验证

热门文章

  1. [Python] Use Python Classes
  2. iOS 平台上常见的安装包有三种,deb、ipa 和 pxl
  3. Kinect 开发 —— 骨骼数据与彩色影像和深度影像的对齐
  4. Spark存储体系
  5. 深入了解"网上邻居"原理
  6. java高质量缩放图片
  7. Python Web框架要点
  8. C#引用c++DLL结构体数组注意事项(数据发送与接收时)
  9. 【Uva 1289】Stacking Plates
  10. iOS 创建静态库文件时去掉当中的Symbols