javascript - 在 Canvas 上绘制方形图像

标签 javascript html canvas

我正在尝试在 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

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

例如这张图片:

enter image description here

我应该得到:

enter image description here

最佳答案

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

    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('/image/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>

关于javascript - 在 Canvas 上绘制方形图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37868726/

相关文章:

html - three.js 阴影截止

javascript - 我正在尝试使用脚本在 HTML 中创建一个 8x8 正方形的表格

php - PHP 中通过变量将十进制度转换为小时、分钟、秒

javascript - 谷歌折线图吓坏了,以随机 Angular 绘制

javascript - 动态添加属性到 JSON 数组

python - Div Python 中的 URL 网页抓取 (BeautifulSoup)

javascript - 使用 Javascript 进行不同的计算(加、减、按百分比减去...)

javascript - canvas 或 requestAnimationFrame 在移动设备上速度很慢

javascript - 如何在 4 帧之间连续制作动画

javascript - 如何在angularjs中检查条件复选框