在画布上绘制正方形图像

时间:2016-06-16 20:23:31

标签: javascript html5 canvas

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

我有什么:

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);
};

预览:

enter image description here

那么如何在画布上绘制一个150x150的正方形,并保持比例裁剪版的图像?

例如,对于此图片:

enter image description here

我应该得到:

enter image description here

2 个答案:

答案 0 :(得分:2)

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



    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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

根据此问题的信息: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/

请记住,前两个参数指定了canvas元素中图像的左上角坐标。

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