是自动创建为PNG文件的HTML Canvas标记的内容

Is the content of an HTML Canvas tag automatically created as a PNG file?

本文关键字:Canvas HTML 文件 创建 PNG      更新时间:2023-09-26

当我右键单击绘制到<canvas>标记中的图像时,唯一要保存为的文件选项类型是.png。即使上传的文件是。jpeg, Save Image As的快捷菜单中显示的唯一选项是。png文件。图像数据绘制到<canvas>标签作为png文件吗?

HTML

<form class='frmUpload'>
  <input name="picOneUpload" type="file" accept="image/*" onchange="picUpload(this.files[0])" >
</form>
<canvas id="cnvsForFormat" width="400" height="266"></canvas>
脚本

window.picUpload = function(frmData) {
  console.log("picUpload ran: " + frmData);
    var cnvs=document.getElementById("cnvsForFormat");
    console.log("cnvs: " + cnvs);
    var ctx=cnvs.getContext("2d");
    cnvs.style.border="1px solid #c3c3c3";
    var img = new Image;
    img.src = URL.createObjectURL(frmData);
    img.onload = function() {
      var picWidth = this.width;
      var picHeight = this.height;
      var wdthHghtRatio = picHeight/picWidth;
      console.log('picWidth: ' + Number(picWidth));
      console.log('picHeight: ' + Number(picHeight));
      console.log('wdthHghtRatio: ' + wdthHghtRatio);
      if (Number(picWidth) > 400) {
        var newHeight = Math.round(Number(400) * wdthHghtRatio);
      } else {
        return false;
      };
      document.getElementById('cnvsForFormat').height = newHeight;
      console.log('width: ' + picWidth + " h: " + picHeight);
      console.log('width: 400  h: ' + newHeight);
      //Must change the width and height settings in order to decrease the image size, but
        //it needs to be proportional to the original dimensions.
        ctx.drawImage(img,0,0, 400, newHeight);
    };

jsFiddle上传图像并绘制到新尺寸的画布

html5画布内容的原生格式是位图。

实际上,最好将其描述为像素图,但请将其视为位图。

你不能右键点击保存作为画布元素,但是你可以:

  • 使用. todataurl()获取画布位图作为png dataURL。

  • 使用. todataurl ('image/jpeg')获取画布位图作为jpg dataURL。

  • 使用context.getImageData获取/设置位图像素数据