简体   繁体   English

将图像绘制为固定的画布宽度和高度

[英]drawimage to a secified canvas width and height

If the source svg is in a responsive environment , how do I use drawImage() to draw a to a given canvas size? 如果源svg在响应环境中 ,如何使用drawImage()将a绘制为给定的画布大小?

Example: How do I get the svg drawn to a 412.5 x 487.5 canvas, if the original svg is 550 x 650 and it is being viewed on a mobile device (so obviously the svg will be seen smaller than the original size)? 示例:如果原始svg为550 x 650并在移动设备上查看,那么如何将svg绘制到412.5 x 487.5画布上(显然svg会小于原始大小)?

Fiddle 小提琴

svgToImage(svg2, function(img2){
        ctx2.drawImage(img2, 0, 0);
      });

      function svgToImage(svg2, callback) {
        var nurl = "data:image/svg+xml;utf8," + encodeURIComponent(svg2),
            img2 = new Image;

          img2.onload = function() {
             callback(img2);
          }
          img2.src = nurl;
      }

When you SVG has loaded, simply set the canvas size, then draw in the image using the width and height arguments of drawImage. 加载SVG后,只需设置画布大小,然后使用drawImage的width和height参数绘制图像。

Note that a bitmap can only take integer values so your canvas has to be either 413x488 or 412x487. 请注意,位图只能使用整数值,因此您的画布必须为413x488或412x487。 If you don't set the canvas size it will default to 300x150 and then stretch to the size you use for style/CSS: 如果未设置画布大小,则默认设置为300x150,然后拉伸至用于样式/ CSS的大小:

  svgToImage(svg2, function(img2){
      ctx2.canvas.width = 413;               // set canvas size
      ctx2.canvas.height = 488;
      ctx2.drawImage(img2, 0, 0, 413, 488);  // draw SVG/image at same size
  });

Updated fiddle 更新的小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM