javascript - HTML5 Canvas 中的超高分辨率图像

标签 javascript html css canvas html5-canvas

此问题的末尾是一个 SSCCE,用于在 HTML5 Canvas 上显示卫星图像的 24000x12000 米勒投影。它有几个问题:

  1. 我希望只显示左上角的一小部分,而不是在一个屏幕上显示整个图像。
  2. 该图片存在极端像素化问题,由于该图片的分辨率非常高,因此不应出现在显示的比例上

enter image description here

  • 所用图像可在 Wikimedia 获得.我将其重命名为“world.jpg”。
  • 这不是一个普通的网络应用程序,在应用程序执行期间不会下载大图像,因此任何不需要下载这么大图像的建议都没有实际意义。
  • 该应用程序将动态放大到各个 map 区域,因此图像尺寸较大。
  • 在实际代码中,我使用了外部样式表和 javascript 文件。我将它们集成到 html 中,专门用于 SSCCE。

这是代码。

<!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/

enter image description here

关于javascript - HTML5 Canvas 中的超高分辨率图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24214639/

相关文章:

javascript - WebStorm 中 CoffeeScript 中的 "Duplicate catch block #loc"?

javascript - 使用javascript的可折叠元素如何默认折叠

html - 设置全局CSS属性时html、body和*有什么区别

javascript - 是否可以在JS中验证URL

javascript - 如何在具有相同功能的类似 div 上复制功能

javascript - rxjs Observable.if 在使用 map 时总是执行这两个语句

php - 检测 DIV 打开和关闭并应用样式以匹配已存在的样式

python - 是否有内置包将 html 解析为 dom?

javascript - 在 Javascript 中使用 Django 变量

css - 有人知道 LESS CSS "theme sheet"吗?