使用.scale()调整HTML画布的大小 [英] Resize HTML canvas with .scale()

查看:295
本文介绍了使用.scale()调整HTML画布的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用已绘制的图片调整< canvas> 的大小,但我误解了如何使用画布。 scale()方法因为它不缩小...

I'm trying to resize a <canvas> with an image already drawn, but I'm misunderstanding how to use the canvas.scale() method because it doesn't shrink...

代码:

ImageRender.prototype.resizeTo = function () {

    var canvas          = $('#myCanvas')[0];
    var ctx             = canvas.getContext("2d");

    //current image
    var currImg         = ctx.getImageData(0, 0, canvas.width, canvas.height);

    //
    var tempCanvas      = $('canvas')[0];
    var tempCtx         = tempCanvas.getContext("2d");
    tempCtx.putImageData(currImg, 0, 0)

    //
    ctx.scale(0.5, 0.5);

    //redraw
    ctx.drawImage(tempCanvas, 0, 0);
  };

我在俯瞰什么?

谢谢!

推荐答案

通过在调整原始画布大小时从临时画布弹回内容,可以使用内容缩放画布。此保存+重绘过程是必要的,因为在调整画布宽度或高度时会自动清除画布内容。

You can scale your canvas with content by "bouncing" the content off a temporary canvas while you resize the original canvas. This save+redraw process is necessary because canvas content is automatically cleared when you resize the canvas width or height.

示例代码:

var myCanvas=document.getElementById("canvas");
var ctx=myCanvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var tempCanvas=document.createElement("canvas");
var tctx=tempCanvas.getContext("2d");

var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/Dog-With-Cute-Cat.jpg";
function start(){
  myCanvas.width=img.width;
  myCanvas.height=img.height;
  ctx.drawImage(img,0,0);
  resizeTo(myCanvas,0.50);
}

function resizeTo(canvas,pct){
  var cw=canvas.width;
  var ch=canvas.height;
  tempCanvas.width=cw;
  tempCanvas.height=ch;
  tctx.drawImage(canvas,0,0);
  canvas.width*=pct;
  canvas.height*=pct;
  var ctx=canvas.getContext('2d');
  ctx.drawImage(tempCanvas,0,0,cw,ch,0,0,cw*pct,ch*pct);
}

body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }

<h4>Canvas resized to 50%</h4>
<canvas id="canvas" width=300 height=300></canvas>
<h4>Img with original image</h4>
<img src='https://dl.dropboxusercontent.com/u/139992952/multple/Dog-With-Cute-Cat.jpg'>

这篇关于使用.scale()调整HTML画布的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆