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

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

问题描述

我正在尝试使用 HTML5 画布元素(如下所示)绘制一组圆圈图片).

当我调整浏览器大小时,上图被裁剪.我希望它在我调整浏览器大小时能够响应.

请帮助我使其响应.谢谢.

var canvas = document.getElementById("canvas");var ctx = canvas.getContext("2d");canvas.width = window.innerWidth;///等于窗口尺寸canvas.height = window.innerHeight;var 半径 = canvas.height/2;ctx.translate(半径,半径);半径 = 半径 * 0.9;绘制时钟();函数 drawClock() {drawCircle(ctx,半径);}函数drawCircle(ctx,半径){变种;变量号;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, 半径 * 0.85);ctx.rotate(-ang);}}

#canvas {显示:块;}

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

解决方案

宽度和高度是在初始化画布元素时设置的,所以需要监听窗口调整大小事件并重置画布宽度和高度.

>

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

I am trying to plot a group of circles using an HTML5 canvas element (as shown in this image).

The 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 画布响应性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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