窗口调整大小事件的响应画布 [英] responsive canvas on window resize event

查看:152
本文介绍了窗口调整大小事件的响应画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是画布概念的新手,我正在尝试使用D3.js绘制画布。我想根据窗口大小使画布响应。

I am new one to canvas concept,I am trying to draw canvas using D3.js. I want to make canvas as responsive based on window screen size.

  function onResize(){
           var element = document.getElementsByTagName("canvas")[0];
           var context = element .node().getContext("2d");
           var scrnWid = window.innerWidth,
               scrnHgt = window.innerHeight,
               elementHgt = element.height,
               elementWid = element.width;

           var aspWid = elementWid/scrnWid;
           var aspHig = elementHgt/scrnHgt;
           context.scale(aspWid,aspHig);    
         } 

   window.addEventListener("resize",onResize);

这是我用来调整画布大小的代码,但它不起作用。我不想使用除D3.js之外的任何库。有谁能建议我更好的解决方案?

This is the code I used to resize canvas, but it not working.I don't want to use any library except D3.js. Can anyone suggest me better solution ?

推荐答案

2DContext.scale()更改呈现的内容不显示大小/分辨率



您没有更改画布大小,您所做的只是缩放画布的内容。

2DContext.scale() changes rendered content not display size / resolution

You are not changing the canvas size, all you are doing is scaling the content of the canvas.

您可以通过其样式属性设置画布的页面大小

You can set the page size of the canvas via its style properties

canvas.style.width = ?; // a valid CSS unit 
canvas.style.height = ?; // a valid CSS unit 

这不会影响画布的分辨率(像素数)。画布分辨率通过其宽度和高度属性设置,并始终以像素为单位。这些是与实际设备显示像素不直接相关的抽象像素,也不直接与CSS像素(px)相关。宽度和高度是没有CSS单位后缀的数字

This does not affect the resolution (number of pixels) of the canvas. The canvas resolution is set via its width and height properties and is always in pixels. These are abstract pixels that are not directly related to actual device display pixels nor do they directly relate to CSS pixels (px). The width and height are numbers without a CSS unit postfix

 canvas.width = ?; // number of pixel columns 
 canvas.height = ?; // number of pixel rows

设置2D上下文比例对显示大小或显示没有影响分辨率, context.scale(?,?)仅影响渲染内容

Setting the 2D context scale has no effect on the display size or the display resolution, context.scale(?,?) only affects the rendered content

缩放画布以适合页面

const layout = {  // defines canvas layout in terms of fractions of window inner size
    width : 0.5,
    height : 0.5,
}

function resize(){
    // set the canvas resolution to CSS pixels (innerWidth and Height are in CSS pixels)
    canvas.width = (innerWidth * layout.width) | 0;  // floor with |0
    canvas.height = (innerHeight * layout.height) | 0;

    // match the display size to the resolution set above
    canvas.style.width = canvas.width + "px"; 
    canvas.style.height = canvas.height + "px"; 
}

这篇关于窗口调整大小事件的响应画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆