簡體   English   中英

HTML5 Canvas中的超高分辨率圖像

[英]Very High Resolution Images in HTML5 Canvas

該問題的末尾是一個SSCCE,它將在HTML5畫布上顯示24000x12000 Miller衛星圖像的投影。 它有幾個問題:

  1. 而不是像我希望的那樣在一個屏幕上顯示整個圖像,只顯示了左上角的一小部分。
  2. 圖像遭受極端像素化,不應出現在所顯示的比例尺上,因為圖像分辨率很高

在此處輸入圖片說明

  • 使用的圖像可從Wikimedia獲得 我將其重命名為“ world.jpg”。
  • 這不是正常的Web應用程序,並且在應用程序執行期間不會下載大圖像,因此不建議下載不需要下載如此大圖像的任何建議。
  • 該應用程序將動態縮放到各個地圖區域,因此圖像較大。
  • 在實際代碼中,我使用了外部樣式表和javascript文件。 我僅將它們集成到SSCCE的html中。

這是代碼。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>The Earth</title>
<script type="text/javascript">
function draw() {
   var canvas = document.getElementById("canvas");
   var ctx = canvas.getContext("2d");
   var map = new Image();
   map.src = "world.jpg";
   map.onload = function() {
      var width = window.innerWidth;
      var height = window.innerHeight;
      ctx.drawImage(map, 0, 0, width, height);
   };
}
</script>
<style>
html, body {
  width:  100%;
  height: 100%;
  margin: 0px;
}
#canvas {
   width: 100%;
   height: 100%;
   position: absolute;
   top: 0px;
   left: 0px;
   background-color: rgba(0, 0, 0, 0);
}
</style>
</head>
<body onload="draw();">
   <canvas id="canvas"></canvas>
</body>
</html>

使用用於裁剪和縮放原始圖像的context.drawImage版本:

context.drawImage(
    sourceImage,
    clipSourceAtX, clipSourceAtY, sourceClipWidth, sourceClipHeight,
    canvasX, canvasY, canvasDrawWidth, canvasDrawHeight
)

例如,假設您正在關注圖像上的坐標[x == 1000,y == 500]。

要以[1000,500]顯示圖像的640px x 512px部分,可以使用如下所示的drawImage:

context.drawImage(

    // use "sourceImage" 
    sourceImage

    // clip a 640x512 portion of the source image at left-top = [1000,500]
    sourceImage,1000,500,640,512,

    // draw the 640x512 clipped subimage at 0,0 on the canvas
    0,0,640,512            
);

演示: http : //jsfiddle.net/m1erickson/MtAEY/

在此處輸入圖片說明

這是有效的javascript代碼,格式正確。

function draw() {
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");
  var map = new Image();
  map.src = "world.jpg";
  map.onload = function() {
    var width = window.innerWidth;
    var height = window.innerHeight;
    canvas.width=width;
    canvas.height=height;
    var mapWidth=map.width;
    var mapHeight=map.height;
    var scale=scalePreserveAspectRatio(mapWidth,mapHeight,width,height);
    ctx.mozImageSmoothingEnabled = false;
    ctx.imageSmoothingEnabled = false;
    ctx.webkitImageSmoothingEnabled = false;
    ctx.drawImage(map, 0, 0, mapWidth, mapHeight, 0, 0, mapWidth*scale, mapHeight*scale);
  };
}
function scalePreserveAspectRatio(imgW,imgH,maxW,maxH){
  return(Math.min((maxW/imgW),(maxH/imgH)));
}

關鍵是兩行

canvas.width=width;
canvas.height=height;

在CSS中將它們簡單地設置為100%是行不通的,這100%顯然不是我假設的窗口內部尺寸的100%。 由於這些尺寸是動態的,因此必須通過JS而不是CSS進行設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM