HTML5 canvas响应性不起作用 [英] HTML5 canvas responsiveness does not work

查看:176
本文介绍了HTML5 canvas响应性不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图绘制一组使用HTML5 canvas元素的圆圈(如图1所示)。
在此输入图片描述



当我调整浏览器大小时,上面的图片被裁剪。
当我调整浏览器大小时,我希望它能够响应。



请帮助我做出响应。谢谢。



  var canvas = document.getElementById(canvas); var ctx = canvas.getContext(2d); canvas.width = window.innerWidth; ///等于window dimensioncanvas.height = window.innerHeight; var radius = canvas.height / 2; ctx.translate(radius,radius); radius = radius * 0.9; drawClock(); function drawClock(){drawCircle ,radius);} function drawCircle(ctx,radius){var ang; var num; for(num = 1; num <= 40; num ++){ang = num * Math.PI / 20; ctx.rotate(ang); ctx.translate(0,-radius * 0.85); ctx.rotate(-ang); ctx.beginPath(); ctx.arc(0,0,radius / 20,0,2 * Math.PI); ctx.stroke(); ctx.rotate(ang); ctx.translate(0,radius * 0.85); ctx.rotate(-ang); }}  

  #canvas {display:block;}  

 < canvas id =canvas>< / canvas> ;  

解决方案

和height在你初始化canvas元素时设置,所以你需要监听窗口的resize事件并重置你的canvas宽度和高度。

  window.onresize = function(){
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};


I am trying to plot group of circles using HTML5 canvas element(as shown in fig 1). enter image description here

Above figure gets cropped, when I resize the browser. I want it to be responsive when i resize the browser.

Please help me to make it responsive. Thank you.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

canvas.width = window.innerWidth; /// equal to window dimension
canvas.height = window.innerHeight;

var radius = canvas.height / 2;
ctx.translate(radius, radius);
radius = radius * 0.9;
drawClock();

function drawClock() {
  drawCircle(ctx, radius);
}

function drawCircle(ctx, radius) {
  var ang;
  var num;

  for (num = 1; num <= 40; num++) {
    ang = num * Math.PI / 20;
    ctx.rotate(ang);
    ctx.translate(0, -radius * 0.85);
    ctx.rotate(-ang);
    ctx.beginPath();
    ctx.arc(0, 0, radius / 20, 0, 2 * Math.PI);
    ctx.stroke();
    ctx.rotate(ang);
    ctx.translate(0, radius * 0.85);
    ctx.rotate(-ang);
  }
}

#canvas {
  display: block;
}

<canvas id="canvas"></canvas>

解决方案

The width and height get set when you initialize your canvas element, so you need to listen to the window resize event and reset your canvas width and height.

window.onresize = function() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
};

这篇关于HTML5 canvas响应性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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