Javascript JS-画布元素内的中心图像

Javascript JS-画布元素内的中心图像,javascript,html,canvas,Javascript,Html,Canvas,我正在缩小图像以使其适合画布,我正在努力做的事情是将其置于canavas元素的中心,请问有人知道如何做到这一点吗?任何帮助都将不胜感激 var canvas=document.getElementById('canvas'); var image=新图像(); image.src=http://placehold.it/300x550'; image.onload=函数(){ var canvasContext=canvas.getContext('2d'); var wrh=image.w

我正在缩小图像以使其适合画布,我正在努力做的事情是将其置于canavas元素的中心,请问有人知道如何做到这一点吗?任何帮助都将不胜感激

var canvas=document.getElementById('canvas');
var image=新图像();
image.src=http://placehold.it/300x550';
image.onload=函数(){
var canvasContext=canvas.getContext('2d');
var wrh=image.width/image.height;
var newWidth=canvas.width;
var newHeight=newWidth/wrh;
如果(新高度>画布高度){
newHeight=canvas.height;
新宽度=新高度*wrh;
}
var xOffset=newWidth

一种既适用于水平方向也适用于垂直方向的解决方案

首先找到适合宽度或高度的最小比例

var scale = Math.min(canvas.width / img.width, canvas.height / img.height);
使用该比例获得img宽度和高度

var w = img.width * scale;
var h = img.height * scale;
然后使用该比例计算左上角距离中心的一半

var left = canvas.width / 2 - w / 2;
var top = canvas.height / 2 - h / 2;

如果您想要类似于
对象匹配:contain

如果您希望
对象适合:cover

const fitImageToCanvas = (image,canvas) => {
  const canvasContext = canvas.getContext("2d");
  const ratio = image.width / image.height;
  let newWidth = canvas.width;
  let newHeight = newWidth / ratio;
  if (newHeight < canvas.height) {
    newHeight = canvas.height;
    newWidth = newHeight * ratio;
  }
  const xOffset = newWidth > canvas.width ? (canvas.width - newWidth) / 2 : 0;
  const yOffset =
    newHeight > canvas.height ? (canvas.height - newHeight) / 2 : 0;
  canvasContext.drawImage(image, xOffset, yOffset, newWidth, newHeight);
};
const fitmagetocanvas=(图像,画布)=>{
const canvasContext=canvas.getContext(“2d”);
常数比=image.width/image.height;
设newWidth=canvas.width;
设newHeight=newWidth/比值;
if(新高度<画布高度){
newHeight=canvas.height;
新宽度=新高度*比率;
}
const xOffset=newWidth>canvas.width?(canvas.width-newWidth)/2:0;
常数约夫特=
newHeight>canvas.height?(canvas.height-newHeight)/2:0;
drawImage(image,xOffset,yOffset,newWidth,newHeight);
};

您可以获得如下元素:

var ctx = document.getElementById('digitalrain').getContext('2d');
并将图像的x和y设置为:

ctx.drawImage(img, width/2-img.width/2, height/2-img.height/2);
ctx.drawImage(img, width/2-img.width/2, height/2-img.height/2);