如何调整html<画布>动态使用Javascript

How do I resize the html <canvas> dynamically using Javascript?

本文关键字:gt 画布 动态 Javascript 何调整 lt 调整 html      更新时间:2023-09-26

我想知道如何使画布与浏览器窗口一起调整大小?现在,使用innerWidth和innerHeight,它的大小将仅为初始浏览器的宽度和高度。如何使用浏览器进行扩展?

编辑:有没有一种方法可以在不清除画布的情况下执行此操作?

JS

  canvas.onmousemove = draw;
       var ctx = canvas.getContext('2d');
       var video = document.createElement("video");
       video.setAttribute("src", "some_video.mp4");
       video.autoplay = true;
       var img2 = new Image;
       img2.src = "some_image.png";
           ctx.canvas.width = window.innerWidth;
           ctx.canvas.height = window.innerHeight;
        function draw(e){
            var rect = canvas.getBoundingClientRect();
           var x = e.clientX-rect.left-img2.width/2;
           var y = e.clientY-rect.top-img2.height/2;
           ctx.drawImage(video, x, y, 830, 644);
           ctx.drawImage(img2, x, y, img2.width, img2.height);
  }

resize 上使用

$(window).resize(function(){
   // Place your code here which sets the width and height of canvas.
});