【问题标题】:Draw a square version of image in canvas在画布中绘制方形版本的图像
【发布时间】:2016-10-18 12:48:30
【问题描述】:

我正在尝试在画布中显示上传图像的预览。预览应该是方形版本的图片。

我有什么:

var img = new Image;
img.src = imageSrc;
var c = document.getElementById('file-preview-' + data.response.id);
var ctx = c.getContext("2d");
img.onload = function() {
    ctx.drawImage(img, 0, 0);
};

还有预览:

那么我怎样才能在画布上绘制一个 150x150 的正方形并保持图像的比例裁剪版本?

例如这张图片:

我应该得到:

【问题讨论】:

  • 你的问题是......?
  • 我更新了问题。
  • 该示例无法让我创建一个保持比例裁剪的正方形。
  • 您应该使用此要求更新您的问题。你没有具体说明。另外,请包含您迄今为止尝试过但不起作用的代码。

标签: javascript html canvas


【解决方案1】:

这是一种方法,可以精确地产生您想要的结果,裁剪、调整大小和居中(用注释掉的行代替产生基于左侧的裁剪)...

    var ctx;
    function init(event) {
    	ctx = document.getElementById('canvas').getContext('2d');
        // Your preview is actually 120x120,
        // but I've stuck with the textual description of
        // your requirements here.
    	ctx.canvas.width = 150;
    	ctx.canvas.height = 150;
    	loadBackground('http://i.stack.imgur.com/PCKEo.png');
    }
    
    function loadBackground(path) {
    	var img = new Image();
    	img.onload = drawBackground;
    	img.src = path;
    }

    function drawBackground(event) {
    	var img = event.target;
    	var imgSize = Math.min(img.width, img.height);
        // The following two lines yield a central based cropping.
        // They can both be amended to be 0, if you wish it to be
        // a left based cropped image.
    	var left = (img.width - imgSize) / 2;
    	var top = (img.height - imgSize) / 2;
        //var left = 0; // If you wish left based cropping instead.
        //var top = 0; // If you wish left based cropping instead.
    	ctx.drawImage(event.target, left, top, imgSize, imgSize, 0, 0, ctx.canvas.width, ctx.canvas.height);
    }
    
    window.addEventListener('load', init, false);
<canvas id="canvas"></canvas>

【讨论】:

    【解决方案2】:

    根据来自这个问题的信息:SO Question

    我能够修改在画布中创建方形裁剪图像的操作:

    var img = new Image;
    img.src = "http://cdn.bmwblog.com/wp-content/uploads/2016/02/M-Performance-Parts-BMW-M2-3.jpg"; //Or whatever image source you have
    var c= document.getElementById('file-preview');
    var ctx=c.getContext("2d");
    
    img.onload = function(){
          ctx.drawImage(img, img.width/2, img.height/2, img.width, img.height, 0, 0, img.width, img.height);
    };
    

    您只需修改传递给 drawImage 函数的参数并添加更多参数。

    你可以在这里看到一个小提琴:https://jsfiddle.net/4d93pkoa/3/

    请记住,前两个参数指定图像在画布元素内的左上角坐标。

    记得将 HTML 中的 canvas 元素的宽度和高度设置为方形。

    【讨论】:

    • "在 css 中设置画布元素的宽度和高度" - 你的意思是在 HTML 中吗?通过 CSS 调整 canvas 元素大小而不设置 HTML 元素的高度和宽度通常会导致结果混乱
    • (如果您的画布的heightwidth HTML 属性与其heightwidth CSS 属性的比例不同,则它不会有1:1纵横比,因此画布上绘制的正方形在屏幕上不会是正方形)
    猜你喜欢
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多