[英]Draw a square version of image in canvas
這是一種可以精確產生所需結果,裁剪,調整大小和居中的方法(帶有注釋的行改為產生基於左側的裁剪)...
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>
根據此問題的信息: SO問題
我能夠修改在畫布上創建方形裁剪圖像的操作:
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元素的寬度和高度設置為正方形。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.